使用spring-boot实现的rest接口抛出异常时,页面显示中文乱码解决

代码:

    @CrossOrigin
    @RestController
    @RequestMapping("api")
    public class RestAPI {    

        @GetMapping("/exception")
            public int exception() throws Exception{
                    throw new Exception("中文乱码");
            }
    }

现象:

    使用spring-boot实现的rest接口抛出异常时,页面显示中文乱码解决

解决步骤:

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

     使用spring-boot实现的rest接口抛出异常时,页面显示中文乱码解决

    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接口抛出异常时,页面显示中文乱码解决

转载于:https://my.oschina.net/u/943320/blog/782685