SpringMVC-07-解决乱码问题
2021-03-26 12:29
标签:value coding atom xtend pre ret ini post loaded 自定义过滤器 JavaWeb中的普通过滤器 对POST请求的乱码解决不了 SpringMVC的过滤器 在web.xml中配置编码格式
filter>
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>
有些极端情况下,这个过滤器对get的支持不好,解决办法如下:
-
1、配置tomcat的编码
-
2、使用通用过滤器
通用过滤器
/**
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {
?
public void init(FilterConfig filterConfig) throws ServletException {
}
?
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);
?
}
?
public void destroy() {
}
}
?
//自定义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请求
MapString, 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();
}
下一篇:标准C++02
文章标题:SpringMVC-07-解决乱码问题
文章链接:http://soscw.com/index.php/essay/68149.html