2014-02-15 103 views
1

我得到了1個問題,無法解決。我得到一個POST請求,並從RequestMapping獲取一個變量,但編碼得到的都是錯誤的。@PathVariable編碼問題 - Spring MVC

請求URL: 127.0.0.1:8080/projeto/ws/cidade/Uberl%C3%A2ndia

控制器:

@RequestMapping (value = "/city/{name}", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE) 
     public ResponseEntity<?> doGetPath(@PathVariable("name") String name) { 
} 

返回值上@PathVariable(「名「): Uberl ndia

正確的回報:Uberlândia

任何人都可以幫我嗎?

+0

它是[這個問題] [1] [1]的重複:http://stackoverflow.com/questions/4470787/spring-rest-pathvariable-character-encoding –

+0

不是我的問題。這不行。 –

回答

2

這是由於控制器運行的JVM使用的字符編碼與用於編碼請求的編碼不同。

要查看此信息,請使用編碼的網址127.0.0.1:8080/projeto/ws/cidade/Uberl%C3%A2ndia並通過使用UTF-8的http://www.url-encode-decode.com/,結果爲Uberlândia

但是,如果解碼是用ISO-2022-CN完成的,則結果是Uberlândia

要解決這個問題,需要使用與編碼相同的方式對字符串進行解碼。

要以全局方式更改服務器使用的編碼,可以將JVM使用的編碼設置爲UTF-8,請參閱此answer。 CharacterEncodingFilter將確保HTTP請求的內容將用給定的編碼進行解碼。

另一種方法是讓客戶端發送請求以服務器期望的方式進行編碼。

但是爲了避免這些問題,您可能希望系統中的每個組件都配置爲使用UTF-8。

0

我的解決辦法是: 創建類:

public class UrlPathHelperFixed extends UrlPathHelper { 

    public UrlPathHelperFixed() { 
     super.setUrlDecode(false); 
    } 

    @Override 
    public void setUrlDecode(boolean urlDecode) { 
     if (urlDecode) { 
      throw new IllegalArgumentException("Handler does not support URL decoding."); 
     } 
    } 

    @Override 
    public String getServletPath(HttpServletRequest request) { 
     String servletPath = getOriginatingServletPath(request); 
     return servletPath; 
    } 


    @Override 
    public String getOriginatingServletPath(HttpServletRequest request) { 
     String servletPath = request.getRequestURI().substring(request.getContextPath().length()); 
     return servletPath; 
    } 
} 

改變彈簧mvc.xml到:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> 
     <property name="order" value="-1"></property> 
     <property name="urlPathHelper"> 
      <bean class="br.com.delivery.utils.UrlPathHelperFixed"/> 
     </property> 
    </bean> 

和配置的maven-compilter到:

<properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    </properties> 
... 
<artifactId>maven-compiler-plugin</artifactId> 
       <version>2.3.2</version> 
       <configuration> 
        <source>1.7</source> 
        <target>1.7</target> 
        <encoding>${project.build.sourceEncoding}</encoding> 
       </configuration> 

UriUtils.decode(nome, "UTF-8")