Filter.java
上传用户:zhc3n3
上传日期:2022-07-30
资源大小:2750k
文件大小:2k
- package com.t11.filer;
- 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.http.HttpServletRequest;
- import javax.servlet.http.HttpServletRequestWrapper;
- public class Filter implements javax.servlet.Filter {
- private String encoding = "GB2312";
- public void destroy() {
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain arg2) throws IOException, ServletException {
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- HttpServletRequestWrapper requestWrapper = new EncodingWrapper(
- httpRequest);
- response.setContentType("text/html;charset=UTF-8");
- arg2.doFilter(requestWrapper, response);
- }
- public void init(FilterConfig arg0) throws ServletException {
- String testValue = arg0.getInitParameter("test");
- if (testValue != null) {
- this.encoding = testValue;
- }
- }
- private class EncodingWrapper extends HttpServletRequestWrapper {
- private HttpServletRequest request = null;
- public EncodingWrapper(HttpServletRequest request) {
- super(request);
- this.request = request;
- }
- public String getParameter(String name) {
- String value = null;
- // 请求中的乱码
- value = request.getParameter(name);
- // 转换后的好码
- value = this.encoding(value);
- return value;
- }
- public String[] getParameterValues(String name) {
- String[] values = null;
- values = request.getParameterValues(name);
- if (values != null) {
- for (int i = 0; i < values.length; i++) {
- values[i] = this.encoding(values[i]);
- }
- }
- return values;
- }
- private String encoding(String value) {
- if (value != null) {
- try {
- byte[] bytes = null;
- String method = request.getMethod();
- if ("post".equalsIgnoreCase(method)) {
- bytes = value.getBytes("ISO-8859-1");
- } else {
- bytes = value.getBytes();
- }
- value = new String(bytes, "UTF-8");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return value;
- }
- }
- }