UTF-8 URL解码/编码 [英] UTF-8 URL Decode / Encode

查看:158
本文介绍了UTF-8 URL解码/编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指示我的URL发送类似的Ajax请求:

I instruct my URL to send an Ajax request like that:

url += '/' + something + '/' + id;
var response;
$.ajax({
    async : false,
    type: 'DELETE',
    url: url,
 ...

我的 removeId 是一个包含UTF-8字符的变量。我会处理Java端的变量如下:

My removeId is a variable that includes UTF-8 character. I will handle that variable at Java side like that:

@RequestMapping(value = "/something/{id}", method = RequestMethod.DELETE)
    public void myMethod(HttpServletResponse response, @PathVariable String id) {
    ...

然而,Java端的 id 变量与原始变量不同,因为UTF-8字符变为奇怪的东西。

However id variable at Java side is different from its original because UTF-8 characters changes to strange things.

如何从JavaScript端发送UTF-8字符并在Java端再次转换(使用REST的Spring 3,我的Web服务器是Tomcat 7)?

How can I send UTF-8 characters from JavaScript side and transform it again at my Java side (Spring 3 with REST, my web server is Tomcat 7)?

PS 1:即使我不使用 encodeUriComponent 我的网址似乎是自己编码的?

PS 1: Even I don't use encodeUriComponent it seems that my URL is encoding by itself?

PS 2:提出更清楚的问题:

i.e. my id variable is araç and sent URL is: localhost:8080/sdfasf/ara%C3%A7 

当我看到id变量具有该值时:

When I see that id variable has that value:

araç

而不是:

ara%C3%A7 

Spring(或Tomcat)会自动执行此操作吗?当控制器作为路径变量时,有没有办法自动解码它(我的意思是没有写任何东西,如:

Does Spring (or Tomcat) automatically do it? Is there any way to decode it automatically when it comes to controller as a path variable (I mean without writing anything as like:

URLDecoder.decode(id,"UTF-8");

它将自动转换)

推荐答案

您看到的id值似乎是使用iso-8859-1 charset而不是utf-8解码的。在java EE中未指定url的路径部分的编码,并且没有标准的api来设置它。对于查询参数可以使用 request.setCharacterEncoding 在访问任何参数之前让它们正确解码。 CharacterEncodingFilter 完全相同,但对路径参数没有影响。

The id value you see seems to be decoded using the iso-8859-1 charset instead of utf-8. The encoding of the path part of a url is not specified in java EE and there is no standard api to set it. For query parameters you can use request.setCharacterEncoding before accessing any parameters to have them decoded correctly. The CharacterEncodingFilter does exactly that but has no influence on path parameters.

要在Tomcat中使这个工作,你必须在 server.xml Connector 元素的 URIEncoding 属性c>到utf-8。

To make this work in Tomcat you have to set the URIEncoding attribute of the Connector element in its server.xml to "utf-8".

您可以在这个优秀的答案来回答类似的问题。

All you ever wanted to know about character encoding in a java webapp can be found in this excellent answer to a similar question.

这篇关于UTF-8 URL解码/编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆