Added error handling policies for javax-servlets module
This commit is contained in:
parent
a54c9e0c9e
commit
3d602e6398
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.*;
|
||||
import javax.servlet.http.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
import static javax.servlet.RequestDispatcher.*;
|
||||
|
||||
@WebServlet(urlPatterns = "/errorHandler")
|
||||
public class ErrorHandlerServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
resp.setContentType("text/html; charset=utf-8");
|
||||
try (PrintWriter writer = resp.getWriter()) {
|
||||
writer.write("<html><head><title>Error description</title></head><body>");
|
||||
writer.write("<h2>Error description</h2>");
|
||||
writer.write("<ul>");
|
||||
Arrays.asList(ERROR_STATUS_CODE, ERROR_EXCEPTION_TYPE, ERROR_MESSAGE)
|
||||
.forEach(e ->
|
||||
writer.write("<li>" + e + ":" + req.getAttribute(e) + " </li>")
|
||||
);
|
||||
writer.write("</ul>");
|
||||
writer.write("</html></body>");
|
||||
}
|
||||
|
||||
Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION);
|
||||
if (IllegalArgumentException.class.isInstance(exception)) {
|
||||
getServletContext().log("Error on an application argument", exception);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.*;
|
||||
import javax.servlet.http.*;
|
||||
|
||||
@WebServlet(urlPatterns = "/randomError")
|
||||
public class RandomErrorServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
|
||||
throw new IllegalStateException("Random error");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
|
||||
version="3.1">
|
||||
|
||||
<error-page>
|
||||
<error-code>404</error-code>
|
||||
<location>/error-404.html</location> <!-- /src/main/webapp/error-404.html-->
|
||||
</error-page>
|
||||
|
||||
<error-page>
|
||||
<exception-type>java.lang.Exception</exception-type>
|
||||
<location>/errorHandler</location>
|
||||
</error-page>
|
||||
</web-app>
|
|
@ -0,0 +1,14 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Error page</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h2>Error: Page not found</h2>
|
||||
|
||||
<a href="./">Go back home</a>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -1,3 +0,0 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy)
|
Loading…
Reference in New Issue