简体   繁体   中英

Spring controller exception handling for 404 statuses and url pattern

Is it possible to handle 404 status for particular url pattern? I would like display login page if someone go to 'localhost:8080/login/other' but there is no request mapping for 'login/other'. Controller class is as follow:

@RequestMapping("/login")
@Controller
public class UserManagerController {

    @RequestMapping({"/", ""})
    public String getLoginPage() {
        return "login.html";
    }

}

I cannot add '/login/**' because this match my static content and any request for js or css match that endpoint. Example html:

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
</head>
    ...
  <script src="/login/some.js"</script>
</html>

You can use something like this:

import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class GlobalErrorController implements ErrorController {

  @RequestMapping("/error")
  public String handleError(HttpServletRequest request, Model model) {
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
    model.addAttribute("errorMessage", exception);
    model.addAttribute("statusCode", statusCode);
    if (Objects.nonNull(statusCode)
        && HttpStatus.NOT_FOUND.value() == statusCode) {
      return "resource-not-found";// in your case you should use: return "redirect:/login";
    }
    return "exception";
  }

  @Override
  public String getErrorPath() {
    return "/error";
  }
}

That code opens the 'resource-not-found' page in case that user will open an invalid url, for instance localhost:8080/invalid-page

For your case you could use the method 'handleError()' to return "redirect:/login"; if statusCode is 404

In my project I thought that it will be more logical to open a 'resource-not-found' page and a button that will redirect the user to home page, you can look how it works here: https://macari-home-finance.herokuapp.com/login/invalid-url and here is my project https://github.com/ruslanMacari/HomeFinance

hope it will help you

I found solutions to redirect http 404 responses for defined url pattern using Filters and HttpServletResponseWrapper.

In spring boot define filter for pattern.

@Bean
    public FilterRegistrationBean<LoginFilter> loginFilter(){
        FilterRegistrationBean<LoginFilter> registrationBean = new FilterRegistrationBean<>();

        registrationBean.setFilter(new LoginFilter());
        registrationBean.addUrlPatterns("/login/*");

        return registrationBean;
    }

In filter instance create HttpServletResponseWrapper and override sendError's methods to redirect all 404 responses. Filters look as follow:

public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,
                                                FilterChain chain) throws IOException, ServletException {

        HttpServletResponseWrapper servletResponseWrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse) {
            @Override
            public void sendError(int sc, String msg) throws IOException {
                if (sc == 404) {
                    sendRedirect();
                } else {
                    super.sendError(sc, msg);
                }
            }

            @Override
            public void sendError(int sc) throws IOException {
                if (sc == 404) {
                    sendRedirect();
                } else {
                    super.sendError(sc);
                }
            }

            private void sendRedirect() throws IOException {
                ((HttpServletResponse)getResponse()).sendRedirect("/login");
            }

        };
        chain.doFilter(servletRequest, servletResponseWrapper);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM