这几天在做一个网站,用struts2框架作为展现层,与web端的页面做交互,其间就遇到了一个问题,困了我好久,我前端用ajax异步调用了一个action方法,链接中还有参数(中文的),在action中request接受之后参数全部为乱码,这个JSP包括struts2中该设置编码的地方我都设为了UTF-8,结果还是出现了这个问题。网上查了好久,左改改又改改,终于解决了这个问题,解决方案如下:
1.提交参数时要用POST方式
2.struts.properties文件中加入:struts.locale=zh_CN, struts.i18n.encoding=UTF-8
3.tomcat的server.xml文件中对应的8080端口号的文件中加入useBodyEncodingForURI="true" , URIEncoding="UTF-8"
4.对接收的参数进行字符编码转换:new String(request.getParameter("参数名").getBytes("ISO-8859-1"), "UTF-8");
这个方法最给力,我的就是这样解决的,如果还没有解决,那就用EncodeFilter吧!代码如下:
package com.yun.action; 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; public class EncodeFilter implements Filter{ protected String encoding=null; protected FilterConfig filterConfig=null; protected boolean ignore=true; public void destroy() { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String requestedWith = request.getHeader("x-requested-with"); String type = request.getContentType(); if (requestedWith != null && "XMLHttpRequest".equals(requestedWith) && null != type && ("application/x-www-form-urlencoded".equals(type)||"application/x-www-form-urlencoded; charset=UTF-8".equals(type))) { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); request.getParameterMap(); } filterChain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
然后配置文件中加入:
<filter> <filter-name>encoding</filter-name> <filter-class>com.yun.action.EncodeFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
这样的话基本上乱码问题都可以解决了,如果可以帮到你,帮着顶顶啊!