• @ReponseStatus


    @ResponseStatus

        @ResponseBody
       	//方法正常执行但是状态码变成400
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @RequestMapping("/test1")
        public String testRes() {
            return "你好 世界";
        }
    

    且不会跳转到4xx页面

    	//如果加了reason属性reason就一定会发出异常(sendError), 而异常的statusCode就是400
    	@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "请求不可用")
        @RequestMapping("/test3")
        public String testSuccess() {
            return "success";
        }
    
        //如果方法内部异常,状态码不会被改变
    	@ResponseBody
        @ResponseStatus(HttpStatus.CONTINUE)//100
        @RequestMapping("/test4")
        public void testStatusCode() {
            throw new RuntimeException();
        }
    

    与@ExceptionHandler一起使用, 抛出异常, 但是无法将map的值传递出去, 即使重写了org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes

        @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "请求不可用")
        @ExceptionHandler(UserNotExistException.class)
        private ModelAndView handleUserNotExistException1(UserNotExistException e) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("customer", "用户名不存在");
            map.put("msg",e.getMessage());
            return new ModelAndView("forward:/error", map);
    

    可以通过指定javax.servlet.error.status_code将值传递到request中

            @ExceptionHandler(UserNotExistException.class)
            private ModelAndView handleUserNotExistException2(UserNotExistException e, HttpServletRequest request) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("customer", "用户名不存在");
                request.setAttribute("javax.servlet.error.status_code", HttpStatus.INTERNAL_SERVER_ERROR);
                return new ModelAndView("forward:/error", map);
            }
    
    
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
            Object map = webRequest.getAttribute("customer", RequestAttributes.SCOPE_REQUEST);
            //保留原有的attr
            Map<String, Object> superAttr = super.getErrorAttributes(webRequest, includeStackTrace);
            superAttr.put("map", map);
            superAttr.put("info", "这是一条信息");
            return superAttr;
        }
    

    如果将@ResponseStatus加在异常类上(不管有没有reason), 在抛出异常时被@ExceptionHandler捕获时, 方法还是会send对应statusCode的erro,
    效果与在@Exception上加@ResponseStatus一样

  • 相关阅读:
    OpenGL中glVertex、显示列表(glCallList)、顶点数组(Vertex array)、VBO及VAO区别
    OpenGL FrameBufferCopy相关Api比较(glCopyPixels,glReadPixels,glCopyTexImage2D,glFramebufferTexture2D)
    OpenGL渲染流程
    GPU大百科全书索引(有助于理解openGL工作流程)
    二进制配置文件为什么比json等配置文件效率高
    游戏开发中的矩阵初探
    Objective-C 30分钟入门教程
    cocos2dx骨骼动画Armature源码分析(三)
    cocos2dx骨骼动画Armature源码分析(二)
    linux中df和du查看磁盘大小不一致解决方法(转载)
  • 原文地址:https://www.cnblogs.com/kikochz/p/12815314.html
Copyright © 2020-2023  润新知