gpt4 book ai didi

java - Spring字符编码

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:40 25 4
gpt4 key购买 nike

我正在尝试向 Controller 发送西里尔字母符号。当我通过 AJAX 和 GET 方法传递参数时发送到 Controller 时,我收到 ISO-8859-1

在我的jsp顶部:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

我尝试创建自定义过滤器,但它不起作用,响应中的传入编码始终为 ISO-8859-1

@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {

//INIT method

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpServletResponse servletResponse = (HttpServletResponse) response;

String requestEncoding = servletRequest.getCharacterEncoding();

if (requestEncoding == null) {
servletRequest.setCharacterEncoding(ENCODING);
}

String responseEncoding = servletResponse.getCharacterEncoding();

// if (responseEncoding == null) {
// servletResponse.setCharacterEncoding(ENCODING);
// }
servletResponse.setCharacterEncoding(ENCODING);

chain.doFilter(servletRequest, servletResponse);
}

//DESTROY method

我尝试过配置 MessageConverters

 @Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

//Other configuration

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", Charset.forName("UTF-8"))));
converters.add(stringConverter);

}
}

和Spring CharacterEncodingFilter

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ApplicationConfig.class};
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}

@Override
protected Filter[] getServletFilters() {

CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] { characterEncodingFilter};
}
}

但这并没有帮助,AJAX请求

    $(window).load(function(){

$("#firstUser").keyup(function(){
var value = $(this).val();
console.log(value);

var searchRequest = $.ajax({
type: "GET",
url: "calc/name",
encoding: "UTF-8",
data: {
'userName' : value
},
dataType: "text",
success: function(msg){

}
});

})
});

最佳答案

我修好了。我只是安装其他tomcat版本。 Tomcat7 出现问题,Tomcat8 一切正常。

PS:两个版本中都配置了 Tomcat/conf 中的 server.xml

PSS:我还将 HttpMessageConverters 配置删除到 WebConfig 中。这不会影响编码。

关于java - Spring字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com