Struts2拦截器解决乱码问题
2011-12-14 08:45
302 查看
之前使用struts1的时候是通过写filter来处理乱码,把写的filter搬到struts2,配置了WEB.XML发生没有效果,请求根本就没有通过filter。原因Struts2在web.html配置了处理action请求的filter:
通过这个sturts filter后,在这个struts filter之前或之后配置都是发现处理乱码的filter不起作用,所以编写拦截器还是个不错的解决乱码的方式。
1、编写自定义 EncodingIntereptor拦截器
2、Struts.xml配置
下注册拦截器:
3、使用拦截器,可将其设为默认的拦截器
4、页面编码和页面字符编码跟设为"UTF-8"。如果页面是其它编码,将拦截器中重编码部分改一下即可。
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
通过这个sturts filter后,在这个struts filter之前或之后配置都是发现处理乱码的filter不起作用,所以编写拦截器还是个不错的解决乱码的方式。
1、编写自定义 EncodingIntereptor拦截器
import java.io.UnsupportedEncodingException; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.StrutsStatics; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class EncodingInterceptor extends AbstractInterceptor { /** * Struts2编码拦截器 */ @Override public String intercept(ActionInvocation arg0) throws Exception { // TODO Auto-generated method stub ActionContext actionContext = arg0.getInvocationContext(); HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST); System.out.println("Encoding Intercept..."); /** * 此方法体对GET 和 POST方法均可 */ if( request.getMethod().compareToIgnoreCase("post")>=0){ try { request.setCharacterEncoding("GBK"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ Iterator iter=request.getParameterMap().values().iterator(); while(iter.hasNext()) { String[] parames=(String[])iter.next(); for (int i = 0; i < parames.length; i++) { try { parames[i]=new String(parames[i].getBytes("iso8859-1"),"GBK");//此处GBK与页面编码一样 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } return arg0.invoke(); } }
2、Struts.xml配置
下注册拦截器:
<package> <interceptors> <interceptor name="Encoding" class="com.disaster.util.EncodingInterceptor"></interceptor> <interceptor-stack name="Encode"> <interceptor-ref name="Encoding"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref><!-- 必须引入这个,否则request不会再往下传--> </interceptor-stack> </interceptors>
3、使用拦截器,可将其设为默认的拦截器
<default-interceptor-ref name="Encode"></default-interceptor-ref>
4、页面编码和页面字符编码跟设为"UTF-8"。如果页面是其它编码,将拦截器中重编码部分改一下即可。
相关文章推荐
- Struts2拦截器解决乱码问题
- struts2拦截器解决乱码问题
- Struts2拦截器解决乱码问题
- struts2用拦截器解决中文乱码问题
- 解决struts2使用拦截器后参数无效问题
- 解决Struts2拦截器的对于参数传递无效问题
- 总算是把Struts2的乱码问题解决了!!!
- Struts2中解决中文乱码问题
- struts2文件下载中文乱码问题彻底解决
- struts2 解决中文乱码的问题
- struts2 + ajax 中文乱码问题解决
- struts2文件上传下载及乱码问题解决
- Struts2 获得前台提交数据 乱码问题的解决
- Struts2 .apk 文件下载及解决中文文件名乱码问题(转)
- 解决struts2的中文乱码问题
- Struts2 中文乱码问题解决
- struts2解决中文乱码问题
- Struts2中文乱码问题解决的几种方法供参考
- struts2 action 跳action 传递中文乱码问题解决
- Struts2中解决POST请求和GET请求中的中文乱码问题