现在的位置: 首页 > 综合 > 正文

jsp form 表单或超链接传参数中文乱码问题小结

2018年01月31日 ⁄ 综合 ⁄ 共 2036字 ⁄ 字号 评论关闭

最近遇到一些form表单或超链接传参数,中文参数乱码的问题,现总结如下:

1、form表单,post方式

      解决方法:发送和接收方选用相同编码格式,如GBK

2、form表单,不设定方式

      解决方法:过滤器

       CharacterEncodingFilter.java      编码处理类

package filter;

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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;
	private FilterConfig filterConfig; 
	
	public void init(FilterConfig filterConfig) throws ServletException { 
		this.filterConfig = filterConfig; 
	} 
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) { 
		try { 
			String encoding=filterConfig.getInitParameter("encoding");//从WEB.xml配置文件中取出参数,这样我们可以通过配置修改编码格式. 
			request.setCharacterEncoding(encoding);//设置请求的编码格式 
			//System.out.println(encoding); 
			filterChain.doFilter(request, response);//关键 
		} catch (ServletException sx) { 
			filterConfig.getServletContext().log(sx.getMessage()); 
		} catch (IOException iox) { 
			filterConfig.getServletContext().log(iox.getMessage()); 
		} 
	} 
	
	public void destroy() { } 
	
	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { 
		super.doGet(arg0, arg1); 
	} 
	
	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { 
		super.doPost(arg0, arg1); 
	} 
}

        web.xml配置

         <filter>
		<filter-name>CharacterEncoding</filter-name>
		<filter-class>filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

3、如上述方法仍有问题,则检查tomcat下conf中的server.xml文件

     解决方法:

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="GBK" />
 

以上内容位个人见解,经过测试,仅供参考。

 

抱歉!评论已关闭.