I can not make request encoding to work correctly. For encoding to work, i added filter to spring security:
@Bean
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(characterEncodingFilter(), CsrfFilter.class);
...
}
Add meta to my pages:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
...
Add UriEnconding to tomcat 8:
<Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8"
connectionTimeout="20000"
redirectPort="8443" />
But it is not responding to none of them. When i send a request and debug it, the result is wrong. For example when i send بای
as a part of request form, i recieve باÛ
as result. Is there any part of config i am missing?
When sending payload ajax request (with rest client and ofcource to another method) it workes correctly, but no luck with form data. My controller looks like this:
@RequestMapping(value = "/test1")
@ResponseBody
public String test1(@RequestBody String req) {
return req;
}
@RequestMapping(value = "/test2")
@ResponseBody
public String test2(@RequestParam("search") String req) {
return req;
}
different tries:
Content-Type=application/json
it correctly recieves the parameter.Content-Type=application/x-www-form-urlencoded
and get method, again everything works great.Content-Type=application/x-www-form-urlencoded
and POST method, it returns wrong encoded values.It seems the problem is with POST method only. any suggestions?
答案 0 :(得分:5)
在深入挖掘大量过滤器链并在其中移动字符编码后,终于发现了问题。另一个过滤器是在字符编码开始之前改变编码。
我只是从spring security手中获取过滤器并手动添加它作为bean来为我做过滤:
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
registrationBean.setFilter(characterEncodingFilter);
return registrationBean;
}
2天或搜索和尝试,只是一个简单的答案。找到答案很难的方法
<强> --- --- UPDATE 强>
如果您使用的是1.8+的spring boot,则根本不需要CharacterEncoding。它默认情况下处于完美位置,字符编码等于utf8。所以下次,只要设置属性,如果有的话! the properties to set are:
# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8 # the encoding of HTTP requests/responses
spring.http.encoding.enabled=true # enable http encoding support
spring.http.encoding.force=true # force the configured encoding
---更新2 ---
从Tomcat wiki开始:在Tomcat 8
从8.0.0开始(8.0.0-RC3,具体而言),元素的URIEncoding
属性的默认值取决于“strict servlet合规性“设置。 URIEncoding的默认值(严格合规关闭)现在为UTF-8
。如果启用了“严格servlet遵从性”,则默认值为ISO-8859-1
。
所以一般说来,没有必要在Tomcat Config中设置UriEncoding。