[错误解决]SpringMVC接收对象 中文乱码问题解决
错误描述 :
对于以下一段简单前端代码示例:
1 <!-- 请求对象实体类 --> 2 <form action="SpringMVCHandler/testObjectProperties" method="post"> 3 学号:<input type="text" name="id"><br> 4 姓名:<input type="text" name="name"><br> 5 家庭住址:<input type="text" name="address.homeAddress"><br> 6 学校地址:<input type="text" name="address.schoolAddress"><br> 7 <input type="submit" value="实体类传参(便捷)"> 8 </form>
以及后台接收代码:
1 @RequestMapping(value="testObjectProperties") 2 public String testCookieValue(Student student) {//student 必须与form表单中的属性一致(支持级联属性) 3 System.out.println(student.getId()+" "+student.getName()+" "+student.getAddress().getHomeAddress()+" "+student.getAddress().getSchoolAddress()); 4 return "success"; 5 }
以及两个实体类Student以及Address
Student.java
1 package org.zlc.entity; 2 3 public class Student { 4 private int id; 5 private String name; 6 private Address address; 7 public int getId() { 8 return id; 9 } 10 public void setId(int id) { 11 this.id = id; 12 } 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public Address getAddress() { 20 return address; 21 } 22 public void setAddress(Address address) { 23 this.address = address; 24 } 25 }
Address.java
1 package org.zlc.entity; 2 3 public class Address { 4 private String homeAddress; 5 private String SchoolAddress; 6 public String getHomeAddress() { 7 return homeAddress; 8 } 9 public void setHomeAddress(String homeAddress) { 10 this.homeAddress = homeAddress; 11 } 12 public String getSchoolAddress() { 13 return SchoolAddress; 14 } 15 public void setSchoolAddress(String schoolAddress) { 16 SchoolAddress = schoolAddress; 17 } 18 19 }
在前端输入后控制台会输出输入内容
但如果为中文则会输出乱码
解决办法:
在web.xml添加字符集拦截器
1 <!-- 字符集过滤器 --> 2 <filter> 3 <description>字符集过滤器</description> 4 <filter-name>characterEncodingFilter</filter-name> 5 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 6 <init-param> 7 <description>字符集编码</description> 8 <param-name>encoding</param-name> 9 <param-value>UTF-8</param-value> 10 </init-param> 11 <init-param> 12 <param-name>forceEncoding</param-name> 13 <param-value>true</param-value> 14 </init-param> 15 </filter> 16 17 <!-- 字符集拦截 --> 18 <filter-mapping> 19 <filter-name>characterEncodingFilter</filter-name> 20 <url-pattern>/*</url-pattern> 21 </filter-mapping>
中文不再乱码