前沿
Struts2中文乱码解决办法
**首先确定是哪里乱码,大致可分为这几种:
- 页面乱码
- action中接收参数乱码
- 数据库乱码
**
这里我只说action中的乱码问题
判断是不是后台乱码,可以system控制台输出一下看看就行了
解决办法
设置过滤器
package com.jjp.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.HttpServletRequestWrapper;
public class EncodingFilter implements Filter{
private String encoding;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(encoding==null||"".equals(encoding)){
encoding="utf-8";
}
//解决的post请求
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request){
@Override
public String getParameter(String name) {
//对于get请求特殊处理
if("get".equals(this.getMethod().toLowerCase())){
String value=super.getParameter(name);
try {
if(value!=null)
return new String(value.getBytes("iso-8859-1"),encoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
}
return super.getParameter(name);
}
}, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
encoding=config.getInitParameter("encode");
}
}
然后再web.xml中写配置信息
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.jjp.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
需要注意的是这个配置信息,必须放在所有的filter的最前面