SpringMVC-乱码问题

1.在index.jsp界面加一个表单,让他请求一个控制器传递数据

<form action="/t4/encoding" method="post">
    <input type="text" name="name">
    <input type="submit">
</form>

2.控制器接收到数据,再通过Model传到另一个页面上

@Controller
public class Encoding {
    
    

    @RequestMapping("/t4/encoding")
    public String test(Model model, String name){
    
    
        model.addAttribute("msg",name); //获取表单提交的值
        return "test"; //跳转到test页面显示输入的值
    }
}

输入字母数字都没问题,输入汉字会出现乱码。

解决:
1.使用springmvc自带的过滤器,只需在web.xml配置一下即可

    <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>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

2.自定义过滤器。然后在web.xml配置

/**
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {
    
    

   @Override
   public void destroy() {
    
    
  }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    
       //处理response的字符编码
       HttpServletResponse myResponse=(HttpServletResponse) response;
       myResponse.setContentType("text/html;charset=UTF-8");

       // 转型为与协议相关对象
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
       // 对request包装增强
       HttpServletRequest myrequest = new MyRequest(httpServletRequest);
       chain.doFilter(myrequest, response);
  }

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
    
    
  }

}

//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {
    
    

   private HttpServletRequest request;
   //是否编码的标记
   private boolean hasEncode;
   //定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
   public MyRequest(HttpServletRequest request) {
    
    
       super(request);// super必须写
       this.request = request;
  }

   // 对需要增强方法 进行覆盖
   @Override
   public Map getParameterMap() {
    
    
       // 先获得请求方式
       String method = request.getMethod();
       if (method.equalsIgnoreCase("post")) {
    
    
           // post请求
           try {
    
    
               // 处理post乱码
               request.setCharacterEncoding("utf-8");
               return request.getParameterMap();
          } catch (UnsupportedEncodingException e) {
    
    
               e.printStackTrace();
          }
      } else if (method.equalsIgnoreCase("get")) {
    
    
           // get请求
           Map<String, String[]> parameterMap = request.getParameterMap();
           if (!hasEncode) {
    
     // 确保get手动编码逻辑只运行一次
               for (String parameterName : parameterMap.keySet()) {
    
    
                   String[] values = parameterMap.get(parameterName);
                   if (values != null) {
    
    
                       for (int i = 0; i < values.length; i++) {
    
    
                           try {
    
    
                               // 处理get乱码
                               values[i] = new String(values[i]
                                      .getBytes("ISO-8859-1"), "utf-8");
                          } catch (UnsupportedEncodingException e) {
    
    
                               e.printStackTrace();
                          }
                      }
                  }
              }
               hasEncode = true;
          }
           return parameterMap;
      }
       return super.getParameterMap();
  }

   //取一个值
   @Override
   public String getParameter(String name) {
    
    
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       if (values == null) {
    
    
           return null;
      }
       return values[0]; // 取回参数的第一个值
  }

   //取所有值
   @Override
   public String[] getParameterValues(String name) {
    
    
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       return values;
  }
}

猜你喜欢

转载自blog.csdn.net/qq_42665745/article/details/112971384
今日推荐