Original link: http://blog.9cbs.net/flyxxxx/archive/2004/09/10/100319.aspx
Filter file: package filter; import java.io. *; Import javax.servlet. *; Import javax.servlet.http. *; Import java.net. *;
Public Class Characterencoding Implements Filter {Protected FilterConfig FilterConfig = NULL; Private String Encoding = NULL;
Public void destroy () {filterconfig = null; Encoding = null;
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; String s = req.getRequestURI (); String url = URLDecoder.decode (s, "UTF-8") ;/ When IE INTNET Options -> Advanced Options -> The URL is always selected in UTF-8. INT k = url.indexof ("?"); string file = (k == - 1? URL: url.substring (0, k)); file f = new file (filter f = new file (fileconfig.getServletContext (). getRealPath (file) ); If (f.exists () == false) {url = new string (S.GetBytes ("ISO-8859-1"), Encoding; // URL = URLDECoder when the UTF-8 transmits URL is not selected .decode (URL, Encoding); FilterConfig.getServletContext (). getRequestDispatcher (URL) .forward (req, response);}
Public void init (filterconfig filter "throws servletexception {this.filterconfig = filterconfig; encoding = filterconfig.getinitParameter (" encoding ");}
}
The above is used for JDK1.4. If you use JDK1.3, add the following method in the above code and change urlencoder.decode (...) to decode (...):
public static String decode (String s, String enc) throws UnsupportedEncodingException {boolean needToChange = false; StringBuffer sb = new StringBuffer (); int numChars = s.length (); int i = 0; if (enc.length () == 0) {throw new unsupportedEncodingexception ("Urldecoder: Empty String Enc Parameter);} While (i Sb.Append (Bytes, 0, POS, ENC));} catch (Numberformatexce E) {throw new illegalgumentException ("URLDECoder: Illegal Hex Characters in escape (%) Pattern -" E.GetMessage (); NEEDTOCHANGE = True; Break; default: sb.append (c); i ; Break;}} Return (NEEDTOCHANGE? SB.TOSTRING (): s); Also, join the web.xml file Characterencoding Filter.Characterencoding ENCODING GBK Characterencoding / *