码迷,mamicode.com
首页 > 编程语言 > 详细

javaweb的Filter过滤器设置全站编码

时间:2017-08-03 21:55:56      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:wrap   out   pos   请求   logs   wrapper   方式   content   als   

  FIlter配置全站编码有一种方法是重写getParameter方法,也就是继承HttpServletRequestWrapper在重写getParameter方法,还有一种就是如下:

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 将requese进行强转
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// 得到参数提交方式
		String method = req.getMethod();
		// 分为Get和Post两种方式进行处理
		if(method.equalsIgnoreCase("post")) {
			System.out.println("采用的是Post请求方式...");
			// post	请求方法,直接可以进行设置
			req.setCharacterEncoding("utf-8");
			resp.setContentType("text/html;charset=utf-8");
		} else {
			System.out.println("采用的是Get请求方式...");
			// get 请求方法,对于请求的参数的进行改变设置字符集
			resp.setContentType("text/html;charset=utf-8");
			Enumeration<String> enumeration= req.getParameterNames();
			while(enumeration.hasMoreElements()) {
				String key = enumeration.nextElement();
				String[] values = req.getParameterValues(key);
				// 对值进行字符集的编码设置
				for(int i=0; i<values.length; i++) {
					values[i] = new String(values[i].getBytes("iso-8859-1"), "utf-8");
				}
			}
		}
		chain.doFilter(req, resp);
	}

  

  如果在FIlter中进行制定编码方式的编码,且代码无误的话,还是显示乱码,那么可能存在的问题是因为Tomcat的<Connector>标签缺少了URIEncoding的配置。

  配置如下:

  修改Tomcat下的/conf/server.xml配置文件,制定URIEncoding;

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

  就是加上:URIEncoding="UTF-8"

javaweb的Filter过滤器设置全站编码

标签:wrap   out   pos   请求   logs   wrapper   方式   content   als   

原文地址:http://www.cnblogs.com/geore/p/7281764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!