url中文问题解决方法

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

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) {
   //以UTF-8发送URL 未被选中时
   url = new String(s.getBytes("ISO-8859-1"), encoding);
   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
/*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值