Spring MVC REST Handing Bad Url (404) by returning JSON

前端 未结 4 802
醉梦人生
醉梦人生 2021-01-30 23:56

I am developing a REST service using SpringMVC, where I have @RequestMapping at class and method level.

This application is currently configured to return error-page js

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 00:40

    After digging around DispatcherServlet and HttpServletBean.init() in SpringFramework I see that its possible in Spring 4.

    org.springframework.web.servlet.DispatcherServlet

    /** Throw a NoHandlerFoundException if no Handler was found to process this request? **/
    private boolean throwExceptionIfNoHandlerFound = false;
    
    protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (pageNotFoundLogger.isWarnEnabled()) {
            String requestUri = urlPathHelper.getRequestUri(request);
            pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + requestUri +
                    "] in DispatcherServlet with name '" + getServletName() + "'");
        }
        if(throwExceptionIfNoHandlerFound) {
            ServletServerHttpRequest req = new ServletServerHttpRequest(request);
            throw new NoHandlerFoundException(req.getMethod().name(),
                    req.getServletRequest().getRequestURI(),req.getHeaders());
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    

    throwExceptionIfNoHandlerFound is false by default and we should enable that in web.xml

    
        appServlet
        org.springframework.web.servlet.DispatcherServlet
            
                throwExceptionIfNoHandlerFound
                true
            
        1
        true
    
    

    And then you can catch it in a class annotated with @ControllerAdvice using this method.

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value=HttpStatus.NOT_FOUND)
    @ResponseBody
    public ResponseEntity requestHandlingNoHandlerFound(HttpServletRequest req, NoHandlerFoundException ex) {
        Locale locale = LocaleContextHolder.getLocale();
        String errorMessage = messageSource.getMessage("error.bad.url", null, locale);
    
        String errorURL = req.getRequestURL().toString();
    
        ErrorInfo errorInfo = new ErrorInfo(errorURL, errorMessage);
        return new ResponseEntity(errorInfo.toJson(), HttpStatus.BAD_REQUEST);
    }
    

    Which allows me to return JSON response for bad URLs for which no mapping exist, instead of redirecting to a JSP page :)

    {"message":"URL does not exist","url":"http://localhost:8080/service/patientssd"}
    

提交回复
热议问题