代码:
@CrossOrigin
@RestController
@RequestMapping(“api”)
public class RestAPI {
@GetMapping(“/exception”)
public int exception() throws Exception{
throw new Exception(“中文乱码”);
}
}
现象:

解决步骤:
1.使用chrome的开发人员工具,发现如下图中红框部分县市,charset设置不当,应为utf-8

2.创建类继承HandlerExceptionResolver接口,在接口中进行charset的重新设置,代码如下
@Component
public class AExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
response.setCharacterEncoding(“utf-8”);
return null;
}
}
备注:@Component注解时必须的,这样,才能保证在启动时,扩展的AExceptionHandler类被成功加载
3.解决之后的现象

作者:掠燕翔云
本文介绍了解决Spring Boot REST API返回中文乱码的方法。通过调整字符集设置,并实现HandlerExceptionResolver接口来确保响应正确编码。具体步骤包括检查Chrome开发者工具中的字符集配置、修改response.setCharacterEncoding为utf-8,最终实现中文正常显示。

3111

被折叠的 条评论
为什么被折叠?



