1. 程式人生 > >Filter解決全域性亂碼(get提交方式)

Filter解決全域性亂碼(get提交方式)

package cn.hsm.web.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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 {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(“utf-8”);
// 在傳遞request之前對request.getParameter方法進行增強
/**
* 裝飾者模式(包裝)
*
* 1.增強類與被增強的類要實現統一介面 2.在增強類中傳入被增強的類 3.需要增強的方法重寫 不需要增強的方法呼叫被增強物件
*/
// 被增強物件
HttpServletRequest req = (HttpServletRequest) request;
// 增強物件
EnhanceRequest enhanceRequest = new EnhanceRequest(req);
chain.doFilter(enhanceRequest, response);
}

public void destroy() {
}

public void init(FilterConfig fConfig) throws ServletException {
	// TODO Auto-generated method stub
}

}

class EnhanceRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;

public EnhanceRequest(HttpServletRequest request) {
	super(request);
	this.request = request;
}

@Override
public String getParameter(String name) {
	String string = request.getParameter(name);
	try {
		string = new String(string.getBytes("iso8859-1"), "UTF-8");
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return string;
}

}