Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an URL which led to error (404) from error-page controller in spring MVC

Say, i have a Spring MVC application with the following web.xml entry:

<error-page>
    <error-code>404</error-code>
    <location>/error/404</location>
</error-page>

and following error-page controller:

@RequestMapping({"","/"})
@Controller
public class RootController {

    @RequestMapping("error/{errorId}")
    public String errorPage(@PathVariable Integer errorId, Model model) {
        model.addAttribute("errorId",errorId);

        return "root/error.tile";
    }
}

Now user requested non-existent URL /user/show/iamnotauser which triggered error page controller. How do i get this non-existent '/user/show/iamnotauser' URL from errorPage() method of RootController to put it into model and display on error page ?

like image 911
Alexander Tumin Avatar asked Dec 16 '12 11:12

Alexander Tumin


People also ask

How does Spring MVC handle 404 error?

The 404 error code is configured properly, but it will caused the “. htm” extension handling conflict between the “servlet container” and Spring's “DispatcherServlet“. To solve it, try change the 404. htm to other file extension, for example 404.

How do I redirect an error page in Spring boot?

In Spring Boot 1.4. x you can add a custom error page: If you want to display a custom HTML error page for a given status code, you add a file to an /error folder. Error pages can either be static HTML (i.e. added under any of the static resource folders) or built using templates.

How do you throw a 404 error?

Just throw HttpException: throw new HttpException(404, "Page you requested is not found"); ASP.NET run-time will catch the exception and will redirect to the custom 404.


1 Answers

The trick is request attribute javax.servlet.forward.request_uri, it contains the original requested uri.

@RequestMapping("error/{errorId}")
public ModelAndView resourceNotFound(@PathVariable Integer errorId,
                                                   HttpServletRequest request) {
    //request.getAttribute("javax.servlet.forward.request_uri");
    String origialUri = (String) request.getAttribute(
                                               RequestDispatcher.FORWARD_REQUEST_URI);

    return new ModelAndView("root/error.jspx", "originalUri", origialUri);
}

If you still use Servlet API 2.5, then the constant RequestDispatcher.FORWARD_REQUEST_URI does not exist, but you can use request.getAttribute("javax.servlet.forward.request_uri"). or upgrad to javax.servlet:javax.servlet-api:3.0.1

like image 119
Ralph Avatar answered Oct 12 '22 01:10

Ralph