代码:

    @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

相关文章:

  • 2021-06-12
  • 2022-01-22
  • 2021-12-30
  • 2022-12-23
  • 2021-11-28
  • 2021-10-10
  • 2021-05-01
  • 2021-04-18
猜你喜欢
  • 2022-01-20
  • 2021-12-08
  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
  • 2021-08-25
  • 2022-12-23
相关资源
相似解决方案