在spring项目中,当请求方式为post时,可能在获取数据之后会有乱码的情况,其中一种解决方法就是在拿到请求参数之前设置编码格式为utf-8,如下
request.setCharacterEncoding("utf-8");
String strId = request.getParameter("id");
String strName = request.getParameter("name");
String strSex = request.getParameter("sex");
但是当有多个处理器方法的时候每个方法中都要设置编码格式就显得过于繁琐,所以推荐第二种解决方案:使用过滤器只要在web.xml中对过滤器进行声明注册就可以了
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
forceRequestEncoding
true
forceResponseEncoding
true
characterEncodingFilter
/*
另外,我们可以看一下CharacterEncodingFilter的实现方法的实现就知道为什么要设置后边的encoding,forceRequestEncoding,forceResponseEncoding这三个参数了,因为这三个参数是这个方法中的是三个私有属性
public class CharacterEncodingFilter extends OncePerRequestFilter {
@Nullable
private String encoding;
private boolean forceRequestEncoding;
private boolean forceResponseEncoding;
public CharacterEncodingFilter() {
this.forceRequestEncoding = false;
this.forceResponseEncoding = false;
}
public CharacterEncodingFilter(String encoding) {
this(encoding, false);
}
public CharacterEncodingFilter(String encoding, boolean forceEncoding) {
this(encoding, forceEncoding, forceEncoding);
}
public CharacterEncodingFilter(String encoding, boolean forceRequestEncoding, boolean forceResponseEncoding) {
this.forceRequestEncoding = false;
this.forceResponseEncoding = false;
Assert.hasLength(encoding, "Encoding must not be empty");
this.encoding = encoding;
this.forceRequestEncoding = forceRequestEncoding;
this.forceResponseEncoding = forceResponseEncoding;
}
总结
到此这篇关于springmvc项目中使用过滤器来解决请求方式为post时出现乱码的问题的文章就介绍到这了,更多相关springmvc post请求乱码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!