点评:Vm中一个超链接URL需要拼接中文作为Get请求的参数如果直接拼接,传到后台Action的参数对象中后取出会是乱码,需要编码后再拼接到URL上,接下来将和大家分享一下解决方法
Vm中一个超链接URL需要拼接中文作为Get请求的参数。如果直接拼接,传到后台Action的参数对象中后取出会是乱码,需要编码后再拼接到URL上。
ntyHTML5中文学习网 - HTML5先行者学习网解决方法是在Action中添加一个成员变量,保存编码后的中文参数。在vm页面渲染时取出这个变量值,再拼接超链接。
ntyHTML5中文学习网 - HTML5先行者学习网ntyHTML5中文学习网 - HTML5先行者学习网在这里碰到的问题是:调用java.net.URLEncoder的encode()方法时,如果没有显示指定字符集参数,那么URLEncoder会使用默认字符集。这个默认字符集在Eclipse里跑main()方法和在Tomcat里跑Web应用,得到的结果不一样,所以影响了编码的结果。
ntyHTML5中文学习网 - HTML5先行者学习网 ntyHTML5中文学习网 - HTML5先行者学习网
/** ntyHTML5中文学习网 - HTML5先行者学习网
* Translates a string into <code>x-www-form-urlencoded</code> ntyHTML5中文学习网 - HTML5先行者学习网
* format. This method uses the platform'sdefault encoding ntyHTML5中文学习网 - HTML5先行者学习网
* as the encoding scheme to obtain thebytes for unsafe characters. ntyHTML5中文学习网 - HTML5先行者学习网
* ntyHTML5中文学习网 - HTML5先行者学习网
* @param s <code>String</code> to betranslated. ntyHTML5中文学习网 - HTML5先行者学习网
* @deprecated The resulting string mayvary depending on the platform's ntyHTML5中文学习网 - HTML5先行者学习网
* default encoding. Instead, use theencode(String,String) ntyHTML5中文学习网 - HTML5先行者学习网
* method to specify the encoding. ntyHTML5中文学习网 - HTML5先行者学习网
* @return the translated <code>String</code>. ntyHTML5中文学习网 - HTML5先行者学习网
*/ ntyHTML5中文学习网 - HTML5先行者学习网
@Deprecated ntyHTML5中文学习网 - HTML5先行者学习网
public static String encode(String s) { ntyHTML5中文学习网 - HTML5先行者学习网
String str = null; ntyHTML5中文学习网 - HTML5先行者学习网
try { ntyHTML5中文学习网 - HTML5先行者学习网
str = encode(s, dfltEncName); ntyHTML5中文学习网 - HTML5先行者学习网
} catch(UnsupportedEncodingException e) { ntyHTML5中文学习网 - HTML5先行者学习网
// The system should always have theplatform default ntyHTML5中文学习网 - HTML5先行者学习网
} ntyHTML5中文学习网 - HTML5先行者学习网
return str; ntyHTML5中文学习网 - HTML5先行者学习网
} ntyHTML5中文学习网 - HTML5先行者学习网
ntyHTML5中文学习网 - HTML5先行者学习网方法的注释中也说明了不建议使用的原因是,这个encode(String)方法依赖于平台字符集。