日期:2014-05-16  浏览次数:20308 次

jsp servlet乱码解决总结
演示情况:
1.index.jsp 向 result.jsp post 参数

出现乱码

解决:(假定两页面均是utf-8编码)
方法1.在result.jsp页面内加入
request.setCharacterEncoding("utf-8");  


方法2.加filter

  	<filter>
		<filter-name>EncodingFilter</filter-name>
		<filter-class>leko.macleo.filter.EncodingFilter</filter-class>
		<init-param>                                                              
   			<param-name>languageconfig</param-name>
   			<param-value>utf-8</param-value> 
  		</init-param>  
	</filter>
	<filter-mapping>
		<filter-name>EncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


package leko.macleo.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class EncodingFilter implements Filter {

	private FilterConfig filterConfig;  
	private String enconfig;  
	/**
	 * Constructor of the object.
	 */
	public EncodingFilter() {
		super();
	}

	

	// Handle the passed-in FilterConfig	
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		
		//获得,web.xml文件中配置languageconfig 的值,我在web.xml文件中配置了languageconfig 的值为:utf-8;  
		this.enconfig=this.filterConfig.getInitParameter("languageconfig");  
		System.out.println("过滤器初始化成功!");  
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain filterChain)

	{
		try {
			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) res;
			HttpSession session = request.getSession();
			
			if (this.enconfig!=null) {  
				   request.setCharacterEncoding(this.enconfig);  
				   response.setCharacterEncoding(this.enconfig);  
				   System.out.println("过滤器处理中:"+this.enconfig);  
				  }  
				  //处理权交给下一个过滤器;  
			// 这里放到达目的地前(进入)处理代码
			
			filterChain.doFilter(req, res);

			// 这里放到达目的地(离开)的处理代码

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		// Just puts "destroy" string in log
		// Put your code here
		this.filterConfig=null;  
		  this.enconfig=null;  
		  System.out.println("过滤器销毁成功!");  
		//System.out.println("过滤器销毁成功!");  
	}

}




相比两方法,方法2虽然麻烦..但是相对方便..



Servlet 字符乱码解决
http://blog.csdn.net/songylwq/article/details/5771893
http://blog.csdn.net/cn_gaowei/article/details/6673539
http://www.cnitblog.com/jmbkeyes/articles/21479.html
用filter标本兼治了。。。