原文連結:http://blog.csdn.net/flyxxxxx/archive/2004/09/10/100319.aspx
過濾器檔案:
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");//當IE中Intertnet選項->進階選項->總是以UTF-8發送URL 被選中時。
int k=url.indexOf("?");
String file=(k==-1?url:url.substring(0,k));
File f = new File(filterConfig.getServletContext().getRealPath(file));
if (f.exists() == false) {
url = new String(s.getBytes("ISO-8859-1"), encoding);//以UTF-8發送URL 未被選中時
url = URLDecoder.decode(url, encoding);
}
filterConfig.getServletContext().getRequestDispatcher(url).forward(req,
response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
encoding = filterConfig.getInitParameter("encoding");
}
}
以上用於JDK1.4,如果用的是JDK1.3,請在上面代碼中加入以下方法,並將URLEncoder.decode(...)改成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 < numChars) {
char c = s.charAt(i);
switch (c) {
case '+':
sb.append(' ');
i++;
needToChange = true;
break;
case '%':
try {
byte[] bytes = new byte[ (numChars - i) / 3];
int pos = 0;
while ( ( (i + 2) < numChars) &&
(c == '%')) {
bytes[pos++] =
(byte) Integer.parseInt(s.substring(i + 1, i + 3),
16);
i += 3;
if (i < numChars) {
c = s.charAt(i);
}
}
if ( (i < numChars) && (c == '%')) {
throw new IllegalArgumentException(
"URLDecoder: Incomplete trailing escape (%) pattern");
}
sb.append(new String(bytes, 0, pos, enc));
}
catch (NumberFormatException e) {
throw new IllegalArgumentException(
"URLDecoder: Illegal hex characters in escape (%) pattern - "
+ e.getMessage());
}
needToChange = true;
break;
default:
sb.append(c);
i++;
break;
}
}
return (needToChange ? sb.toString() : s);
}
另外,還要在web.xml檔案加入
CharacterEncoding
filter.CharacterEncoding
encoding
GBK
CharacterEncoding
/*