使不支持中文URL的JSP服务器支持中文URL(如Tomcat)

来源:互联网 发布:淘宝怎么提升流量 编辑:程序博客网 时间:2024/05/22 10:58

原文链接: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
 /*

原创粉丝点击