关闭

黑马day14 过滤器之解决所有乱码

标签: 过滤器
609人阅读 评论(0) 收藏 举报
分类:

关于乱码的产生以及如何解决乱码请看我的博客字节乱码字符乱码,表单提交get&post乱码

这里主要使用一个过滤器可以解决上述的所有乱码:

1.过滤乱码的过滤器:

package cn.itheima.filter;
import java.io.IOException;
import java.util.Map;
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.HttpServletRequestWrapper;

public class EncodingFilter implements Filter {
	private FilterConfig config = null;
	private String encode = null;
	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html;charset="+encode); //--解决响应乱码
		chain.doFilter(new MyHttpServletRequest((HttpServletRequest) request), response);//--包装改造request中和获取请求参数相关的方法解决请求参数乱码
	}
	
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
		encode = config.getInitParameter("encode") == null
							?"utf-8"
									:config.getInitParameter("encode");
	}
	class MyHttpServletRequest extends HttpServletRequestWrapper{
		private HttpServletRequest request = null;
		private boolean isNotEncode = true;
		public MyHttpServletRequest(HttpServletRequest request) {
			super(request);
			this.request = request;
		}
		
		@Override
		public Map getParameterMap() {
			try{
				if(request.getMethod().equalsIgnoreCase("POST")){//--如果是post提交,一行代码解决post提交请求参数乱码
					request.setCharacterEncoding(encode);
					return request.getParameterMap();
				}else if(request.getMethod().equalsIgnoreCase("GET")){//--如果是get提交,则应该手动编解码解决乱码
					Map<String,String[]> map = request.getParameterMap();//获取有乱码的map
					if(isNotEncode){//只能在第一次解决乱码
						for(Map.Entry<String, String[]> entry : map.entrySet()){//遍历map,解决所有值的乱码
							String [] vs = entry.getValue();
							for(int i=0;i<vs.length;i++){
								vs[i] = new String(vs[i].getBytes("iso8859-1"),encode);
							}
						}
						isNotEncode = false;//设置为false,第二次就不会再进这个代码块了
					}
					return map;
				}else{
					return request.getParameterMap();
				}
			}catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		
		@Override
		public String[] getParameterValues(String name) {
			return (String[]) getParameterMap().get(name);
		}
		
		@Override
		public String getParameter(String name) {
			return getParameterValues(name) == null ? null : getParameterValues(name)[0];
		}
		
		
	}
}
2.web.xml的配置:

<filter>
  	<filter-name>EncodingFilter</filter-name>
  	<filter-class>cn.itheima.filter.EncodingFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>EncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
3.jsp测试乱码:分别包括get和post提交

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
	<meta http-equiv=" pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <body>
  <h1>post提交</h1>
    <form action="${pageContext.request.contextPath }/servlet/FilterDemo1" method="post">
    	姓名:<input type="text"  name="name"/><br>
    	地址:<input type="text"  name="addr"/><br>
    	<input type="submit" value="提交"/><br>
    </form>
    <h1>get提交</h1>
    <form action="${pageContext.request.contextPath }/servlet/FilterDemo1" method="get">
    	姓名:<input type="text"  name="name"/><br>
    	地址:<input type="text"  name="addr"/><br>
    	<input type="submit" value="提交"/><br>
    </form>
  </body>
</html>
4.jsp提交后转向的页面:

package cn.itheima.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FilterDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().write("你好!过滤器!我没有乱码!");
		String name = request.getParameter("name");
		String addr = request.getParameter("addr");
		System.out.println(name);
		System.out.println(addr);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
结果分析:







0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:181206次
    • 积分:4203
    • 等级:
    • 排名:第8046名
    • 原创:242篇
    • 转载:4篇
    • 译文:0篇
    • 评论:36条
    友情链接