day10-1-中文乱码处理

打印 上一主题 下一主题

主题 914|帖子 914|积分 2742

中文乱码处理

1.问题抛出

当表单提交的数据为中文时,会出现乱码:
(1)Monster.java:
  1. package com.li.web.datavalid.entity;
  2. import org.hibernate.validator.constraints.Email;
  3. import org.hibernate.validator.constraints.NotEmpty;
  4. import org.hibernate.validator.constraints.Range;
  5. import org.springframework.format.annotation.DateTimeFormat;
  6. import org.springframework.format.annotation.NumberFormat;
  7. import javax.validation.constraints.NotNull;
  8. import java.util.Date;
  9. /**
  10. * @author 李
  11. * @version 1.0
  12. */
  13. public class Monster {
  14.     @NotNull(message = "id不能为空")
  15.     private Integer id;
  16.     @Email
  17.     @NotEmpty(message = "邮件不能为空")
  18.     private String email;
  19.     @Range(min = 1, max = 100)
  20.     @NotNull(message = "年龄age不能为空")
  21.     private Integer age;
  22.     @NotEmpty
  23.     private String name;
  24.     @DateTimeFormat(pattern = "yyyy-MM-dd")
  25.     @NotNull(message = "生日不能为空")
  26.     private Date birthday;
  27.     @NumberFormat(pattern = "###,###.##")
  28.     @NotNull(message = "工资不能为空")
  29.     private Float salary;
  30.     public Monster() {
  31.     }
  32.     public Monster(Integer id, String email, Integer age, String name, Date birthday, Float salary) {
  33.         this.id = id;
  34.         this.email = email;
  35.         this.age = age;
  36.         this.name = name;
  37.         this.birthday = birthday;
  38.         this.salary = salary;
  39.     }
  40.     public Integer getId() {
  41.         return id;
  42.     }
  43.     public Date getBirthday() {
  44.         return birthday;
  45.     }
  46.     public void setBirthday(Date birthday) {
  47.         this.birthday = birthday;
  48.     }
  49.     public Float getSalary() {
  50.         return salary;
  51.     }
  52.     public void setSalary(Float salary) {
  53.         this.salary = salary;
  54.     }
  55.     public void setId(Integer id) {
  56.         this.id = id;
  57.     }
  58.     public String getEmail() {
  59.         return email;
  60.     }
  61.     public void setEmail(String email) {
  62.         this.email = email;
  63.     }
  64.     public Integer getAge() {
  65.         return age;
  66.     }
  67.     public void setAge(Integer age) {
  68.         this.age = age;
  69.     }
  70.     public String getName() {
  71.         return name;
  72.     }
  73.     public void setName(String name) {
  74.         this.name = name;
  75.     }
  76.     @Override
  77.     public String toString() {
  78.         return "Monster{" +
  79.                 "id=" + id +
  80.                 ", email='" + email + '\'' +
  81.                 ", age=" + age +
  82.                 ", name='" + name + '\'' +
  83.                 ", birthday=" + birthday +
  84.                 ", salary=" + salary +
  85.                 '}';
  86.     }
  87. }
复制代码
(2)MonsterHandler.java
  1. package com.li.web.datavalid;
  2. import com.li.web.datavalid.entity.Monster;
  3. import org.springframework.context.annotation.Scope;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.validation.BeanPropertyBindingResult;
  6. import org.springframework.validation.Errors;
  7. import org.springframework.validation.ObjectError;
  8. import org.springframework.web.bind.WebDataBinder;
  9. import org.springframework.web.bind.annotation.InitBinder;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import javax.validation.Valid;
  13. import java.util.List;
  14. import java.util.Map;
  15. /**
  16. * @author 李
  17. * @version 1.0
  18. */
  19. @Controller
  20. @Scope(value = "prototype")
  21. public class MonsterHandler {
  22.     @RequestMapping(value = "/save", method = RequestMethod.POST)
  23.     public String save(@Valid Monster monster, Errors errors, Map<String, Object> map) {
  24.         System.out.println("----monster----" + monster);
  25.         //为了查看验证的情况,输出map和errors
  26.         System.out.println("=======map=======");
  27.         for (Map.Entry<String, Object> entry : map.entrySet()) {
  28.             System.out.println("key=" + entry.getKey() +
  29.                     " value=" + entry.getValue());
  30.             System.out.println("--------");
  31.         }
  32.         System.out.println("=======errors=======");
  33.         if (errors.hasErrors()) {//判断是否有错误
  34.             List<ObjectError> allErrors = errors.getAllErrors();
  35.             for (ObjectError error : allErrors) {
  36.                 System.out.println("error=" + error);
  37.             }
  38.             return "datavalid/monster_addUI";
  39.         }
  40.         return "datavalid/success";
  41.     }
  42. }
复制代码
(3)前端表单提交的信息:
后端输出:
2.解决方案1-自定义过滤器

分析:
我们知道在Javaweb中,三大组件的加载顺序为:监听器-->过滤器-->Servlet。
由于前端控制器 DispatcherServlet 本质上是一个Servlet,因此可以在过滤器中首先将 Request 的编码设为 utf-8,前端控制器反射目标方法时就不会出现中文乱码问题了。
(1)Monster.java 不变
(2)MonsterHandler.java 不变
(3)在web.xml 文件中配置过滤器
  1. <filter>
  2.     <filter-name>myCharacterFilter</filter-name>
  3.     <filter-class>com.li.web.filter.MyCharacterFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6.     <filter-name>myCharacterFilter</filter-name>
  7.     <url-pattern>/*</url-pattern>
  8. </filter-mapping>
复制代码
(4)MyCharacterFilter.java
  1. package com.li.web.filter;
  2. import javax.servlet.*;
  3. import java.io.IOException;
  4. /**
  5. * @author 李
  6. * @version 1.0
  7. * 编写过滤器处理中文乱码问题
  8. */
  9. public class MyCharacterFilter implements Filter {
  10.     @Override
  11.     public void init(FilterConfig filterConfig) throws ServletException {}
  12.     @Override
  13.     public void doFilter(ServletRequest servletRequest,
  14.                          ServletResponse servletResponse,
  15.                          FilterChain filterChain) throws IOException, ServletException {
  16.         //加入对编码的处理
  17.         servletRequest.setCharacterEncoding("utf-8");
  18.         //放行请求
  19.         filterChain.doFilter(servletRequest, servletResponse);
  20.     }
  21.     @Override
  22.     public void destroy() {}
  23. }
复制代码
(5)启动 tomcat,提交表单数据如下:
后台输出:
3.解决方案2-Spring提供的过滤器处理中文

除了自定义过滤器可以解决,Spring 专门提供了一个过滤器进行编码处理。并且更加简便,因为 Spring 提供的过滤器实现了在init-param标签直接读取编码格式,不用在过滤器中频繁改动编码。
(1)修改 web.xml 文件,换成 spring 提供的过滤器,处理中文乱码问题
  1. <filter>
  2.     <filter-name>characterEncodingFilter</filter-name>
  3.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  4.     <init-param>
  5.         <param-name>encoding</param-name>
  6.         
  7.         <param-value>utf-8</param-value>
  8.     </init-param>
  9. </filter>
  10. <filter-mapping>
  11.     <filter-name>characterEncodingFilter</filter-name>
  12.     <url-pattern>/*</url-pattern>
  13. </filter-mapping>
复制代码
(2)其他文件不变
(3)测试,提交的表单数据如下:
后台输出如下:
同样解决中文乱码问题。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

麻花痒

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表