abiieez
abiieez

Reputation: 3189

How to customize 404 error page handling in Tomcat and Spring?

What I have currently in my web.xml (Tomcat 7)

<error-page>
    <error-code>404</error-code>
    <location>/member/errors/404.html</location>
</error-page>

My HTTPErrorController

@RequestMapping(value = "/errors/404.html")
    public String handle404(HttpServletRequest request,Exception e) {
        logger.error(e.getMessage());
        return "www.example.com/member/dashboard";
}

This works fine for now, however I'd like to customize it with the following scenario:

  1. If anonymous user access non-existent page www.example.com/home2 it should be redirected to the www.example.com/home
  2. If authorized user access non-existent page www.example.com/member/dashboard2 it should be redirected to the www.example.com/member/dashboard

How can I achieve that ?

Upvotes: 0

Views: 382

Answers (1)

knalli
knalli

Reputation: 1993

I would suggest you are using Spring Security for authentication? In that case, you can use this information and redirect based in the logged in state.

For example

@RequestMapping(value = "/errors/404.html")
public String handle404(HttpServletRequest request, Principal principal, Exception e) {
    if (principal != null) {
        return "www.example.com/member/dashboard";
    } else {
        return "www.example.com/home";
    }
}

Alternatively, you have an own business session bean holding the user and ask the injected bean in the controller.

And finally you can instrument Spring Security tooling itself, either with custom annotation @Secured applied on the methods or by user's role (given the roles for anonymous or authenticated access) applied of your app's specific urls in the security configuration.

Like always, the best practice depends on the use case.

Update 1:

@RequestMapping(value = "/errors/404.html")
public String handle404(HttpServletRequest request, Principal principal, Exception e) {
    if (principal != null && request.getRequestURI().startsWith("/member")) {
        return "www.example.com/member/dashboard";
    } else {
        return "www.example.com/home";
    }
}

Upvotes: 1

Related Questions