Skip to content

Commit e8dc2be

Browse files
committed
Added ErrorController, edited web.xml and added error pages code, added errorPage.jsp
1 parent 7918324 commit e8dc2be

3 files changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.baeldung.spring.controller;
2+
3+
import javax.servlet.http.HttpServletRequest;
4+
5+
import org.springframework.stereotype.Controller;
6+
import org.springframework.web.bind.annotation.RequestMapping;
7+
import org.springframework.web.bind.annotation.RequestMethod;
8+
import org.springframework.web.servlet.ModelAndView;
9+
10+
@Controller
11+
public class ErrorController {
12+
13+
@RequestMapping(value = "500Error" , method = RequestMethod.GET)
14+
public void throwRuntimeException(){
15+
throw new NullPointerException("Throwing a null pointer exception");
16+
}
17+
18+
19+
@RequestMapping(value = "errors" , method = RequestMethod.GET)
20+
public ModelAndView renderErrorPages(HttpServletRequest httpRequest){
21+
ModelAndView errorPage = new ModelAndView("errorPage");
22+
String errorMsg = "";
23+
int httpErrorCode = getErrorCode(httpRequest);
24+
25+
switch( httpErrorCode ){
26+
case 400:{
27+
errorMsg = "Http Error Code : 400 . Bad Request";
28+
break;
29+
}
30+
case 401:{
31+
errorMsg = "Http Error Code : 401. Unauthorized";
32+
break;
33+
}
34+
case 404:{
35+
errorMsg = "Http Error Code : 404. Resource not found";
36+
break;
37+
}
38+
//Handle other 4xx error codes.
39+
case 500:{
40+
errorMsg = "Http Error Code : 500. Internal Server Error";
41+
break;
42+
}
43+
//Handle other 5xx error codes.
44+
}
45+
errorPage.addObject("errorMsg", errorMsg);
46+
return errorPage;
47+
}
48+
49+
private int getErrorCode(HttpServletRequest httpRequest){
50+
return (Integer) httpRequest.getAttribute("javax.servlet.error.status_code");
51+
}
52+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
2+
<%@ page session="false" %>
3+
<html>
4+
<head>
5+
<title>Home</title>
6+
</head>
7+
<body>
8+
<h1>
9+
${errorMsg}
10+
</h1>
11+
12+
</body>
13+
</html>

‎spring-mvc-xml/src/main/webapp/WEB-INF/web.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,9 @@
4343
<welcome-file>index.jsp</welcome-file>
4444
</welcome-file-list>
4545

46+
<error-page>
47+
<location>
48+
/errors
49+
</location>
50+
</error-page>
4651
</web-app>

0 commit comments

Comments
 (0)