spring mvc @ResponseStatus 注解 注释返回中文乱码的问题
前言
前文中讲到,使用@ResponseStatus注解,可以修饰一个异常类,在发生异常的时候返回指定的错误码和消息,在返回的 reason中包含中文的时候,就会出现中文乱码的问题
现象
reason中包含中文的时候,前端返回为乱码
/**
* 自定义异常类
*
* @author Administrator
*
*/
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "没有权限")
public class TestException extends RuntimeException {
private static final long serialVersionUID = 5759027883028274330L;
}
调用代码
/**
* 测试抛出异常乱码
*
* @return
*/
@RequestMapping(value = "/say", produces = "text/html;charset=UTF-8")
@ResponseBody
String say2() {
throw new TestException();
}
访问 http://localhost:8080/say2 返回乱码

原因
通过查看spring mvc 源码发现,解析这个 注解的类为 ResponseStatusExceptionResolver 主要是在resolveResponseStatus 中解析并 调用 response sendError 方法来想客户端发送 html 格式的异常消息,产生乱码的原因是因为编码格式不匹配,而这里明显没有 调用 response.setCharacterEncoding 方法。
public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver implements MessageSourceAware {
private MessageSource messageSource;
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
{
ResponseStatus responseStatus = (ResponseStatus)AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
if (responseStatus != null);
try {
return resolveResponseStatus(responseStatus, request, response, handler, ex);
}
catch (Exception resolveEx) {
this.logger.warn("Handling of @ResponseStatus resulted in Exception", resolveEx);
break label81:
if (ex.getCause() instanceof Exception) {
ex = (Exception)ex.getCause();
return doResolveException(request, response, handler, ex); }
}
label81: return null;
}
protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) throws Exception {
int statusCode = responseStatus.code().value();
String reason = responseStatus.reason();
if (this.messageSource != null) {
reason = this.messageSource.getMessage(reason, null, reason, LocaleContextHolder.getLocale());
}
if (!(StringUtils.hasLength(reason))) {
response.sendError(statusCode);
} else {
response.sendError(statusCode, reason);
}
return new ModelAndView();
}
}
spring 是通过 CharacterEncodingFilter来设置 request 和 response 的编码格式的,查看代码如下,走到这一步,就要查看 spirng boot 是在哪里定义这个过滤器的
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
查看代码,是在 HttpEncodingAutoConfiguration 这个配置类中设置的,代码如下 ,这里就用到一个属性类 HttpEncodingProperties 查看代码,调用的是 shouldForce 方法,所以只需一个设置,就可以让他强制设置编码格式 spring.http.encoding.force=true
public class HttpEncodingAutoConfiguration {
private final HttpEncodingProperties properties;
public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean({ CharacterEncodingFilter.class })
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(HttpEncodingProperties.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(HttpEncodingProperties.Type.RESPONSE));
return filter;
}
@Bean
public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
return new LocaleCharsetMappingsCustomizer(this.properties);
}
private static class LocaleCharsetMappingsCustomizer implements EmbeddedServletContainerCustomizer, Ordered {
private final HttpEncodingProperties properties;
LocaleCharsetMappingsCustomizer(HttpEncodingProperties properties) {
this.properties = properties;
}
public void customize(ConfigurableEmbeddedServletContainer container) {
if (this.properties.getMapping() != null)
container.setLocaleCharsetMappings(this.properties.getMapping());
}
public int getOrder() {
return 0;
}
}
}
boolean shouldForce(Type type) {
Boolean force = (type == Type.REQUEST) ? this.forceRequest : this.forceResponse;
if (force == null) {
force = this.force;
}
if (force == null) {
force = Boolean.valueOf(type == Type.REQUEST);
}
return force.booleanValue();
}
解决办法

spring.http.encoding.force=true
结果
再次访问刷新,显示正常。

spring mvc @ResponseStatus 注解 注释返回中文乱码的问题的更多相关文章
- spring mvc 文件下载 get请求解决中文乱码问题
方案简写,自己或有些基础的可以看懂,因为没时间写的那么详细 方案1 spring mvc解决get请求中文乱码问题, 在tamcat中server.xml文件 URIEncoding="UT ...
- Spring MVC 结合Velocity视图出现中文乱码的解决方案
编码问题一直是个很令人头疼的事,这几天搭了一个Spring MVC+VTL的web框架,发现中文乱码了,这里记录一种解决乱码的方案. 开发环境为eclipse,首先,检查Window->pref ...
- Spring MVC的Post请求参数中文乱码的原因&处理
一.项目配置: Spring 4.4.1-RELEASE Jetty 9.3.5 JDK 1.8 Servlet 3.1.0 web.xml文件中没有配置编解码Filter 二.实际遇到的问题:客户端 ...
- spring ajax以及页面返回中文乱码问题解决
在spring配置文件中添加 <!--返回中文乱码--> <mvc:annotation-driven > <!-- 消息转换器 --> <mvc:messa ...
- ajax提交 返回中文乱码问题
接口返回数据相关 使用@ResponseBody后返回NUll 说明:刚把后台运行起来,兴高采烈的测试接口数据,结果无论如何都是返回null, 最终通过各种百度,发现原来是没有引入关键的Jar包. 解 ...
- Springboot @ResponseBody返回中文乱码
最近我在把Spring 项目改造Springboot,遇到一个问题@ResponseBody返回中文乱码,因为response返回的content-type一直是application/json;ch ...
- springmvc配置一:ajax请求防止返回中文乱码配置说明
Spring3.0 MVC @ResponseBody 的作用是把返回值直接写到HTTP response body里. Spring使用AnnotationMethodHandlerAdapter的 ...
- 解决SpringMVC的@ResponseBody返回中文乱码
SpringMVC的@ResponseBody返回中文乱码的原因是SpringMVC默认处理的字符集是ISO-8859-1,在Spring的org.springframework.http.conve ...
- SpringMVC @ResponseBody返回中文乱码
SpringMVC的@ResponseBody返回中文乱码的原因是SpringMVC默认处理的字符集是ISO-8859-1, 在Spring的org.springframework.http.conv ...
随机推荐
- 在PHP中连接数据库时获取最后的一个ID
在SQL中获取最后的一个id 只需要加上where条件对id进行排序就可以了 但是在PHP中 有一种最新的方法 使用mysql_insert_id();就可以获得最大的id .
- .net图片压缩
1.png很难进行压缩,一般压缩时间较长. 2.jpg图片压缩方法: #region 图片压缩[之压缩jpg] public static void JpgImgZip(Image img,strin ...
- GIT+云盘作 做 文档管理工具
GIT+云盘作 做 文档管理工具 在工作中, 会遇到公司的文档 和 自己家里的 文档进行同步的问题, 通常我们使用U盘作为传输节制, 但是不是非常好,文档的改动都不能发现, 导致回家同步的时候, 出各 ...
- oracle琐碎笔记
Oracle知识点 ps:由于是自己看的所以笔记比较乱,大家谅解 Commit rollback Sql核心语句之select Selct中要用到以下语句 From语句 Where语句 Group b ...
- IOS UI 第四篇:基本UI
ViewController 应用 再第一个XIB页面创建另一个XIB页面,并且通过按钮调用它 - (IBAction)GoSecond:(id)sender { secondVie ...
- script —— 终端里的记录器
当 你在终端或者控制台工作时,你可能想要记录在终端中所做的一切.这些记录可以用来当作史料,保存终端所发生的一切.比如说,你和一些Linux管理员们同 时管理着相同的机器,或者你让某人远程登陆到了你的服 ...
- iOS基础 - UIButton - UIImageView
封装思想:将相同的重复东西保存到方法里,不同的东西用参数代替.不相同的东西交给方法调用者,相同东西自己搞定. 一.UIButton和UIImageView的区别 1.显示图片 1> UIImag ...
- asp.net 加入验证码
验证码生成页面代码(清理掉没用的html) using System; using System.Collections.Generic; using System.Linq; using Syste ...
- [网络编程]VS2010+OpenSSL安装与初步了解
OpenSSL简介 功能作用:SSL(Secure Socket Layer)是netscape公司提出的主要用于web的安全通信标准,分为2.0版和3.0版.TLS(Transport Layer ...
- window.open()详解及浏览器兼容性问题
一.基本语法:window.open(pageURL,name,parameters)其中:pageURL 为子窗口路径name 为子窗口名字parameters 为窗口参数(各参数用逗号分隔) 二 ...