在上次说到跨域中解决乱码问题,只是在拦截器中set编码格式,显然在接下来的项目中又遇到了新的问题:
在文件上传的过程中,和其一块过来的数据会发生中文乱码;在百度上扒拉了好久,才晓得是在文件上传的过程中,编码格式是不会随HTTP请求一块过来的,所以我修改了中间器,代码如下:
package com.xt.shop.base.interceptor;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xt.shop.until.http.HttpUtil;/** *@description TODO 跨域解决类 *@date 2017年11月30日 *@author geYang **/public class SimpleCORSFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } /** * 请求头注释: * 0: response.setContentType 设置响应格式; * 0: response.setCharacterEncoding("UTF-8"); 设置响应参数为UTF-8 * 1: Access-Control-Allow-Origin 可以请求的域; *为允许所有域请求 * 2: Access-Control-Allow-Methods 请求方式 * 3: Access-Control-Max-Age 请求数据缓存时间(单位秒) * 4: Access-Control-Allow-Credentials 保持跨域 AJAX时的 Cookie * 5: Access-Control-Allow-Headers 请求头: * (1): X-Requested-With 请求头用于在服务器端判断request来自AJAX请求还是传统请求; **/ @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // TODO 解决跨域错误 // 接收参数 HttpServletRequest request = (HttpServletRequest) req; System.out.println("请求编码=="+request.getCharacterEncoding()); //if( request.getCharacterEncoding() == null ){ request.setCharacterEncoding("UTF-8"); //} System.out.println("请求地址=="+request.getRequestURL()); System.out.println("请求参数"+ HttpUtil.getReceiveMap(request)); // 返回参数 HttpServletResponse response = (HttpServletResponse) resp; //保证输出到浏览器不会乱码,为JSON格式 response.setContentType("application/json;charset=utf-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "X-Requested-With"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Max-Age", "600"); chain.doFilter(request, response); } @Override public void destroy() { // TODO Auto-generated method stub } }
当请求编码为NULL时,我们给他SET进UTF-8,这样Spring在解析的时候就会正常了,测试已经通过了,因为乱码问题只会在文件上传的时候出现, 先前一直以为是AJAX传值序列化那块的问题(小白一枚),找了好久,才发现是后台接收出错(汗颜);