中文亂碼處理
1.問題拋出
當表單提交的資料為中文時,會出現亂碼:
(1)Monster.java:
package com.li.web.datavalid.entity;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
/**
* @author 李
* @version 1.0
*/
public class Monster {
@NotNull(message = "id不能為空")
private Integer id;
@Email
@NotEmpty(message = "郵件不能為空")
private String email;
@Range(min = 1, max = 100)
@NotNull(message = "年齡age不能為空")
private Integer age;
@NotEmpty
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@NotNull(message = "生日不能為空")
private Date birthday;
@NumberFormat(pattern = "###,###.##")
@NotNull(message = "工資不能為空")
private Float salary;
public Monster() {
}
public Monster(Integer id, String email, Integer age, String name, Date birthday, Float salary) {
this.id = id;
this.email = email;
this.age = age;
this.name = name;
this.birthday = birthday;
this.salary = salary;
}
public Integer getId() {
return id;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Monster{" +
"id=" + id +
", email='" + email + '\'' +
", age=" + age +
", name='" + name + '\'' +
", birthday=" + birthday +
", salary=" + salary +
'}';
}
}
(2)MonsterHandler.java
package com.li.web.datavalid;
import com.li.web.datavalid.entity.Monster;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
/**
* @author 李
* @version 1.0
*/
@Controller
@Scope(value = "https://www.cnblogs.com/liyuelian/p/prototype")
public class MonsterHandler {
@RequestMapping(value = "https://www.cnblogs.com/save", method = RequestMethod.POST)
public String save(@Valid Monster monster, Errors errors, Map<String, Object> map) {
System.out.println("----monster----" + monster);
//為了查看驗證的情況,輸出map和errors
System.out.println("=======map=======");
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("key=" + entry.getKey() +
" value="https://www.cnblogs.com/liyuelian/p/+ entry.getValue());
System.out.println("--------");
}
System.out.println("=======errors=======");
if (errors.hasErrors()) {//判斷是否有錯誤
List<ObjectError> allErrors = errors.getAllErrors();
for (ObjectError error : allErrors) {
System.out.println("error=" + error);
}
return "datavalid/monster_addUI";
}
return "datavalid/success";
}
}
(3)前端表單提交的資訊:
后端輸出:
2.解決方案1-自定義過濾器
分析:
我們知道在Javaweb中,三大組件的加載順序為:監聽器-->過濾器-->Servlet,
由于前端控制器 DispatcherServlet 本質上是一個Servlet,因此可以在過濾器中首先將 Request 的編碼設為 utf-8,前端控制器反射目標方法時就不會出現中文亂碼問題了,
(1)Monster.java 不變
(2)MonsterHandler.java 不變
(3)在web.xml 檔案中配置過濾器
<!--配置處理中文亂碼的過濾器
攔截所有請求,處理編碼-->
<filter>
<filter-name>myCharacterFilter</filter-name>
<filter-class>com.li.web.filter.MyCharacterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myCharacterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
(4)MyCharacterFilter.java
package com.li.web.filter;
import javax.servlet.*;
import java.io.IOException;
/**
* @author 李
* @version 1.0
* 撰寫過濾器處理中文亂碼問題
*/
public class MyCharacterFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
//加入對編碼的處理
servletRequest.setCharacterEncoding("utf-8");
//放行請求
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {}
}
(5)啟動 tomcat,提交表單資料如下:
后臺輸出:
3.解決方案2-Spring提供的過濾器處理中文
除了自定義過濾器可以解決,Spring 專門提供了一個過濾器進行編碼處理,并且更加簡便,因為 Spring 提供的過濾器實作了在init-param標簽直接讀取編碼格式,不用在過濾器中頻繁改動編碼,
(1)修改 web.xml 檔案,換成 spring 提供的過濾器,處理中文亂碼問題
<!--使用spring提供的過濾器處理中文-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<!--這里大小寫都支持-->
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
(2)其他檔案不變
(3)測驗,提交的表單資料如下:
后臺輸出如下:
同樣解決中文亂碼問題,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/543967.html
標籤:Java
下一篇:SpringMVC
