M2E67 M2E67 - 1 month ago 18
reST (reStructuredText) Question

Spring MVC Encode non-English parameters

I use spring MVC to get parameter by @PathVariable as follow:

@GetMapping("/users/{username}")
public Boolean getUser(@PathVariable("username") String username)
{
// do some works
}


when my input paramater is none english(such as arabic), I could not get correct value of parameter and username parameter contain invalid ASCII code. in addition, I am sure that the client send request url in UTF-8 format.

I test spring character encoding filter to solve but it, but it is not work.

<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


I test my code with @RequestsParam and HttpServletRequest, but all of them return invalid characters, also, I used URLEncoder.encode and URLDecoder.decode but could solve problem.

Answer

I solve my problem by using ISO_8859_1 char set by using this code:

username = new String(username.getBytes(CharSets.ISO_8859_1));

but, really I don't know what is reason ? I expect to use UTF-8 encoding to get correct value of parameter, but it doesn't work.