Showing posts with label 404 error handling. Show all posts
Showing posts with label 404 error handling. Show all posts

Saturday, October 11, 2014

HANDLING CUSTOM ERROR PAGES IN TOMCAT WITH SPRING MVC

Download full source code from here
web.xml
<error-page>
    <location>/error.jsp</location>
</error-page>
Create a file named 'error.jsp' under 'WEB-INF' with following contents. This jsp file will redirect to error404 action under error controller.
<!DOCTYPE html>
<%@taglib prefix="UiTabLib" uri="UiTabLib" %>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="REFRESH" content="0;url=<UiTabLib:contextPath/>error/error404.htm?<UiTabLib:logError 

request="${requestScope}"/>">
    </head>
    <body>
        &nbsp;
    </body>
</html>
ErrorController.java
package com.pkm.maven.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class ErrorController extends MultiActionController {
    public ModelAndView error404(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        String statusCode = request.getParameter("status_code");
        String exception = request.getParameter("exception");
        String requestUri = request.getParameter("request_uri");
        if (requestUri == null) {
            requestUri = "Unknown";
        }
  
        ModelAndView view = new ModelAndView("error/error404");
        view.addObject("statusCode", statusCode);
        view.addObject("exception", exception);
        view.addObject("requestUri", requestUri);
        
        return view; 
    }
}
Create a file named 'error404.jsp' under 'WEB-INF/jsp/error/' folder with following content:
<div>Request URI: ${requestUri}</div>
<div>Status Code: ${statusCode}</div>
<div>Exception: ${exception}</div>