struts1.x中的乱码问题
?最近学习struts1.2.9的时候,遇到了中文乱码问题,网上查找了一些文档,主要的有两种解决方式:一是添加过滤器,二是重写 RequestProcessor。现将过滤器的方式共享出来,算是struts学习中有关中文乱码的一个小的总结吧说明:jsp页面编码是utf-8,开发环境编码是gbk
??
?? 自定义首先,定义一个过滤器 SetCharacerEncodingFilter
?
package com.cvicse.utils;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;public class SetCharacterEncodingFilter3 implements Filter {protected String encoding = null;protected FilterConfig filterConfig = null;/* * (non-Javadoc) * * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */public void init(FilterConfig filterConfig) throws ServletException {this.filterConfig = filterConfig;this.encoding = filterConfig.getInitParameter("encoding");}/* * (non-Javadoc) * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {ProcessEncoding req = new ProcessEncoding((HttpServletRequest) request,this.encoding);chain.doFilter(req, response);}/* * (non-Javadoc) * * @see javax.servlet.Filter#destroy() */public void destroy() {this.encoding = null;this.filterConfig = null;}}
?
?
??
然后,再定义一个代理请求ProcessEncoding.java,此类处理数据的编码方式的转换
?
package com.cvicse.utils;//此类处理数据的编码方式的转换import java.io.UnsupportedEncodingException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;public class ProcessEncoding extends HttpServletRequestWrapper {private String encoding;public ProcessEncoding(HttpServletRequest request, String encoding) {super(request);this.encoding = encoding;}/* * (non-Javadoc) * * @see javax.servlet.ServletRequestWrapper#getParameterValues(java.lang.String) */@Overridepublic String[] getParameterValues(String name) {String strs[] = super.getParameterValues(name);for (int i = 0; i < strs.length; i++) {strs[i] = this.encodingConversion(strs[i]);}return strs;}/* * 对接收到的字符进行编码转化 */private String encodingConversion(String input) {String output = "";try {output = new String(input.getBytes("ISO-8859-1"), this.encoding);} catch (UnsupportedEncodingException e) {e.printStackTrace();}return output;}}
??
?
最后配置这个过滤器到web.xml中
?
<filter><filter-name>SetCharacterEncoding</filter-name><filter-class>com.cvicse.utils.SetCharacterEncodingFilter3</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param> </filter><filter-mapping><filter-name>SetCharacterEncoding</filter-name><url-pattern>/*</url-pattern></filter-mapping>
??
?
1 楼 lxs575208196 2012-08-18 和你做法一样 还是没转过来,非要这样写:String department = new String(request.getParameter("department").getBytes("ISO8859-1"),"UTF-8");