1. 程式人生 > >解決get/post提交亂碼的一個filter

解決get/post提交亂碼的一個filter

閒來無事,寫了一個filter,用來解決get/post亂碼提交問題

package com.nrsc.utils;

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 EncodeFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws
IOException, ServletException { MyRequest myrequest = new MyRequest((HttpServletRequest) request); chain.doFilter(myrequest, response); } public void init(FilterConfig fConfig) throws ServletException { } } //注意一個java檔案裡只能有一個類用public修飾 class MyRequest extends HttpServletRequestWrapper { private
HttpServletRequest request; public MyRequest(HttpServletRequest request) { super(request); this.request = request; } @Override public String getParameter(String name) { try { String method = request.getMethod(); if ("GET".equalsIgnoreCase(method)) { // 獲取請求的引數 亂碼 String value = request.getParameter(name); value = new String(value.getBytes("iso-8859-1"), "utf-8"); return value; } else if ("POST".equalsIgnoreCase(method)) { request.setCharacterEncoding("utf-8"); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return super.getParameter(name); } }