首页 > JSP > JSP实现URL中文编码

JSP实现URL中文编码

2010年8月8日 admin 发表评论 阅读评论

URL中传中文字符是件头疼事,本身URL不支持中文字符,但有些情况下又不得不传中文字当参数,若直接把中文字加上去,获取后势必会是乱码,这该怎么办呢?幸好JAVA提供一个URL中字符编码转换的API–URLEncoder,下面给段使用范例:

public class Common{

public static String encode(String s) {

try {

return URLEncoder.encode(s,JspRunConfig.CHARSET);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return s;

}

public static String decode(String s) {

try {

return URLDecoder.decode(s,JspRunConfig.CHARSET);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return s;

}

}

使用时,如果不做任何处理就直接传递,中文也许没有问题(但不保证),但空格肯定会有问题,到接收页面无法识别。
解决办法1:Common.encode(sContent,”utf-8″); 然后再传递。比如url是”accept.jsp?content=”+sContent;

读取时,使用

String sc = request.getParameter(“content”);

sc = new String(sc.getBytes(“iso-8859-1″),”utf-8″);

相关日志

分类: JSP 标签: , ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.
Easy AdSense by Unreal