SpringMVC 乱码问题
2021-04-13 12:26
标签:cep java html parameter vat 问题 for style wrapper 一、正常乱码过滤器 web.xml 注意:对get不大友好 二、通用乱码过滤器 web.xml添加 通用乱码过滤器 SpringMVC 乱码问题 标签:cep java html parameter vat 问题 for style wrapper 原文地址:https://www.cnblogs.com/wt7018/p/13343115.htmlfilter>
filter-name>encodingfilter-name>
filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
init-param>
param-name>encodingparam-name>
param-value>utf-8param-value>
init-param>
filter>
filter-mapping>
filter-name>encodingfilter-name>
url-pattern>/*url-pattern>
filter-mapping>
filter>
filter-name>encodingfilter-name>
filter-class>ustc.wzh.filter.GenericEncodingFilterfilter-class>
init-param>
param-name>encodingparam-name>
param-value>utf-8param-value>
init-param>
filter>
filter-mapping>
filter-name>encodingfilter-name>
url-pattern>/*url-pattern>
filter-mapping>
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* 解决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
上一篇:Vscode C++配置