request.getCharacterEncoding() 的返回值为什么会是null

来源:互联网 发布:蘑菇软件是什么 编辑:程序博客网 时间:2024/05/16 18:05

在webxml 中用spring提供的过滤器

1
2
3
4
5
6
7
8
9
10
<filter>
  <filter-name>encoding</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>utf-8</param-value>
  <param-name>forceEncoding</param-name>
  <param-value>true</param-value>
  </init-param>
 </filter>

以下是类的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class CharacterEncodingFilter extends OncePerRequestFilter {
 private String encoding;
 private boolean forceEncoding = false;
 public void setEncoding(String encoding) {
  this.encoding = encoding;
 }
 public void setForceEncoding(boolean forceEncoding) {
  this.forceEncoding = forceEncoding;
 }
 @Override
 protected void doFilterInternal(
   HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
   throws ServletException, IOException {
   //request.getCharacterEncoding() 返回值默认是null,但默认编码格式是ISO-8859-1,如果设置forceEncoding=false,假设存在上一级过滤器更改了request的编码,则使用request的编码
  if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
   request.setCharacterEncoding(this.encoding);
   if (this.forceEncoding) {
    response.setCharacterEncoding(this.encoding);
   }
  }
  filterChain.doFilter(request, response);
 }
0 0
原创粉丝点击