1

What I want to do is that when user enters url which leads nowhere, I mean there is no resources by this url than special mapping should work.

For example, I have next controller:

@Controller
public class LoginController {

    @RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET)
    public ModelAndView welcome() {
        return new ModelAndView("mainPage");
    }
}

This mapping works when when user enters {contextPath}/ or {contextPath}/login Now i want to map all other urls, I do like this:

@Controller
public class LoginController {

    @RequestMapping(value = {"/", "/login"}, method = RequestMethod.GET)
    public ModelAndView welcome() {
        return new ModelAndView("mainPage");
    }

    @RequestMapping(value = {"/**"}, method = RequestMethod.GET)
    public ModelAndView notFound() {
        return new ModelAndView("customized404Page");
    }
}

Now when user enters invalid path for example {contextPath}/sdfsdf customized404Page is shown to him

But last mapping is more general and and it works always and that is why first mapping doesn`t work.

Question: How to map all invalid urls? Or maybe there is some simplier way to to this in Spring?

2 Answers 2

1

The easiest way to have a customized 404 Page is to configure them in the web.xml

<error-page>
  <error-code>404</error-code>
  <location>/error404.jsp</location>
</error-page>

When a simple jsp is not enough, because you need a full fledged Spring controller, then you can map the location to the controller`s mapping:

@Controller
public class HttpErrorController {

    @RequestMapping(value="/error404")
    public String error404() {
        ...
        return "error404.jsp";
    }
}

<error-page>
  <error-code>404</error-code>
  <location>/error404</location>
</error-page>
Sign up to request clarification or add additional context in comments.

Comments

0

You can use session filter to achieve this.

Check this link. http://www.journaldev.com/1933/java-servlet-filter-example-tutorial

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.