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 ?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With