本人编写的请求编码过滤器,用于解决Request参数乱码问题,通过在web.xml中配置此Filter可以一劳永逸得解决乱码问题。
用法非常简单,在web.xml中配置好这个Filter,使用时无需添加额外代码,按照正常方法取得参数即可。
包括:
<%=request.getParam("text")%>
${param.text}
....
等等,任何取得请求参数的方法。
web.xml中得配置,如下配置即可。
要注意的是其中得编码一项要和response的编码一致。
例如Jsp中,文件头设置了:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
那么web.xml中的编码一项就应该修改为GBK
设置中的FilterGetMethod参数将指明是否对Get方法进行编码转换。
这项设置主要是针对Server.xml中的Conector元素的属性“URIEncoding”,
该属性可以修改Get方法的编码,但是有时候我们并不能取得修改server.xml文件的权限,
这时候就可以使用本过滤器的该项功能,将FilterGetMethod的值写为true。
否则将不对Get方法做转换处理。
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
- <display-name>demo</display-name>
- <filter>
- <description>请求编码过滤器</description>
- <display-name>Request Encoding Filter</display-name>
- <filter-name>Request Encoding Filter</filter-name>
- <filter-class>zerofire.servlet.encoding.RequestEncodingFilter</filter-class>
- <init-param>
- <description>是否忽略编码设置</description>
- <param-name>ignore</param-name>
- <param-value>false</param-value>
- </init-param>
- <init-param>
- <description>是否处理Get方法</description>
- <param-name>FilterGetMethod</param-name>
- <param-value>false</param-value>
- </init-param>
- <init-param>
- <description>设置编码</description>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>Request Encoding Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
源码RequestEncodingFilter:
- package zerofire.servlet.encoding;
- import java.io.IOException;
- import java.util.Enumeration;
- 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;
- /**
- * 请求编码过滤器,过滤所有请求,将请求参数字符串转换为指定编码,避免乱码出现
- * 使用方法:
- * 在web.xml中配置此Filter过滤所有路径,使用时无需任何额外代码,直接取参数即可
- * 支持Post方法和Get方法得请求。
- *
- * @author Zero
- * @version 1.2
- * @since 2003, 2008
- *
- */
- public class RequestEncodingFilter implements Filter {
- protected FilterConfig config;
- protected String encoding;
- protected boolean ignore;
- protected boolean filterGetMethod;
- public RequestEncodingFilter() {
- config = null;
- encoding = null; // 编码,默认为UTF-8
- ignore = false; // 可选,默认为不忽略
- filterGetMethod = false; // 是否处理Get方法
- }
- @Override
- public void destroy() {
- config = null;
- encoding = null;
- }
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- config = filterConfig;
- Enumeration names = config.getInitParameterNames();
- while(names.hasMoreElements()) {
- String name = names.nextElement().toString();
- if (name.trim().toLowerCase().equals("encoding")) {
- encoding = filterConfig.getInitParameter(name);
- if (encoding == null || encoding.trim().length() == 0) {
- encoding = "utf-8";
- }
- }
- if (name.trim().toLowerCase().equals("ignore")) {
- String s = config.getInitParameter(name);
- if (s == null) s = "";
- s = s.trim().toLowerCase();
- ignore = (s.equals("true") || s.equals("yes") || s.equals("ignore"));
- }
- if (name.trim().toLowerCase().equals("filtergetmethod")) {
- String s = config.getInitParameter(name);
- if (s == null) s = "";
- s = s.trim().toLowerCase();
- filterGetMethod = (s.equals("true") || s.equals("yes"));
- }
- }
- }
- @Override
- public void doFilter(ServletRequest req, ServletResponse resp,
- FilterChain chain) throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) req;
- if (!ignore) {
- request.setCharacterEncoding(encoding);
- // 对于GET方法需要对QueryString重新编码
- if (filterGetMethod
- && "GET".equalsIgnoreCase(request.getMethod())
- && (request.getQueryString() != null)) {
- req = new RequestEncodingWrapper(request, encoding);
- }
- }
- chain.doFilter(req, resp);
- }
- }
RequestEncodingWrapper
- package zerofire.servlet.encoding;
- import java.io.UnsupportedEncodingException;
- import java.util.Iterator;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletRequestWrapper;
- /**
- * 供RequestEncodingFilter使用。
- * 作用是转换一个HttpServletRequest,转换其取得参数的函数,避免出现乱码
- * @author Zero
- *
- */
- public class RequestEncodingWrapper extends HttpServletRequestWrapper {
- private String encoding;
- /**
- * @param request
- */
- public RequestEncodingWrapper(HttpServletRequest request) {
- this(request, "utf-8");
- }
- public RequestEncodingWrapper(HttpServletRequest request, String enc) {
- super(request);
- encoding = enc;
- }
- private static String getEncodedString(String value, String enc)
- throws UnsupportedEncodingException {
- return new String(value.getBytes("ISO-8859-1"), enc);
- }
- @Override
- public String getParameter(String key) {
- String ret = super.getParameter(key);
- if (ret != null) {
- try {
- ret = getEncodedString(ret, encoding);
- } catch (UnsupportedEncodingException ex) {
- ex.printStackTrace();
- }
- }
- return ret;
- }
- @SuppressWarnings("unchecked")
- @Override
- public Map getParameterMap() {
- Map map = super.getParameterMap();
- if (map != null) {
- Iterator it = map.keySet().iterator();
- while (it.hasNext()) {
- Object obj = map.get(it.next());
- if (obj != null) {
- try {
- obj = getEncodedString((String) obj, encoding);
- } catch (UnsupportedEncodingException ex) {
- ex.printStackTrace();
- }
- } // if (obj != null)
- } // while (it.hasNext)
- } // if (map != null)
- return map;
- }
- @Override
- public String[] getParameterValues(String key) {
- String[] ret = super.getParameterValues(key);
- if (ret != null) {
- for (int i = 0; i < ret.length; i++) {
- try {
- ret[i] = getEncodedString(ret[i], encoding);
- } catch (UnsupportedEncodingException ex) {
- ex.printStackTrace();
- }
- }
- }
- return ret;
- }
- }