Web jsp开发学习——终极解决jsp中request和response中文乱码的问题(加个过滤器)...

Web jsp开发学习——终极解决jsp中request和response中文乱码的问题(加个过滤器)

中文乱码真的很烦人的。而且每次都要写,可麻烦了,而且有时候写了还不一定管用,所以我们可以试试过滤器

1.每个jsp头上当然要写上utf8啦

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

2.然后添加一个过滤器

在过滤器的doFilter里写上

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        /*
         * 设置request、response的编码
         */
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

3.别忘了在web.xml里配置

  <filter>
    <filter-name>CharFilter</filter-name>
    <filter-class>com.xx17.cys.filter.CharacterFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CharFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

大功告成!!!

 舒服!!!

原文地址:https://www.cnblogs.com/caiyishuai/p/13270764.html