A server 500 exception occurred. If it is handled by default, it will catch the exception and jump to the Tomcat default exception page, as shown in the figure below.
No matter which website is the same, so Tomcat also allows custom styles to meet custom needs. That is, configure it in the web.xml file:
<error-page> <error-code>500</error-code> <location>/error.jsp</location> </error-page>
First, let’s talk about the logic that comes with it. If an error occurs during execution of a JSP page, the JSP engine will automatically generate an exception object. If the JSP page specifies another JSP page as an error handler, the JSP engine will put this exception object into the request object and pass it to the error handler. If you have the impression of writing Servlets, this is the same idea as javax.servlet.forward.request_uri, which turns to the template JSP, retains the original request path instead of the path of the JSP page. In the error handler, because the value of the isErrorPage property of the page compilation directive is set to true, the JSP engine will automatically declare an exception object, which is obtained from the HTTP parameters contained in the request object.
The exception information contained in the request object is very rich, as shown below:
You can use the Java statement request.getAttribute("javax.servlet.error.status_code") or you can use EL expressions in the JSP page, such as ${requestScope["javax.servlet.error.status_code"]}.
Although this custom error page is simple, JSP itself has good encapsulation results. I have also seen a lot of other people's resources, but after careful study, there are also a lot of "learning" so I want to "grind this wheel" again - first of all, the location is a jsp page, or a servlet, but if the servlet may not be started, just use a simple JSP page. We define internal class methods through JSP pages to achieve the separation of pages and logic (no need to write servlets). The remaining ideas are as follows:
Complete the ErrorHandler class in JSP. Another page calls this ErrorHandler class. It can not only accept errors from the JSP page, but also accept errors passed by the servlet controller. It extracts as much information as possible and writes all the contents to the memory first, and then outputs the error information from two output streams to the page and file. At the same time, when adding a few simple sentences, you can also write a copy of the information on the web page to the database or text to return HTML/JSON/XML
The implementation code is as follows:
/** * Exception handling class*/ class ErrorHandler { // All contents are written to memory first, and then output from two output streams to the page and file respectively. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); private PrintStream printStream = new PrintStream(byteArrayOutputStream); /** * Collect error information* @param request * @param exception * @param out */ public ErrorHandler(HttpServletRequest request, Throwable exception, JspWriter out) { setRequest(request); setException(exception); if(out != null) { try { out.print(byteArrayOutputStream); // Output to web page} catch (IOException e) { e.printStackTrace(); } } log(request); if(byteArrayOutputStream != null) try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } if(printStream != null) printStream.close(); } /** * * @param request */ private void setRequest(HttpServletRequest request) { printStream.println(); printStream.println("User account: " + request.getSession().getAttribute("userName")); printStream.println("Accessed path: " + getInfo(request, "javax.servlet.forward.request_uri", String.class)); printStream.println("Error page address: " + getInfo(request, "javax.servlet.error.request_uri", String.class)); printStream.println("Error code: " + getInfo(request, "javax.servlet.error.status_code", int.class)); printStream.println("Exception type: " + getInfo(request, "javax.servlet.error.exception_type", Class.class)); printStream.println("Exception information: " + getInfo(request, "javax.servlet.error.message", String.class)); printStream.println("Exception servlet: " + getInfo(request, "javax.servlet.error.servlet_name", String.class)); printStream.println(); // The other two objects getInfo(request, "javax.servlet.jspException", Throwable.class); getInfo(request, "javax.servlet.forward.jspException", Throwable.class); getInfo(request, "javax.servlet.forward.jspException", Throwable.class); Map<String, String[]> map = request.getParameterMap(); for (String key : map.keySet()) { printStream.println("Parameter in the request includes: "); printStream.println(key + "=" + request.getParameter(key)); printStream.println(); } for (Cookie cookie : request.getCookies()){ // cookie.getValue() printStream.println("Cookies in the request include: "); printStream.println(cookie.getName() + "=" + cookie.getValue()); printStream.println(); } } /** * * @param exception */ private void setException(Throwable exception) { if (exception != null) { printStream.println("Exception information"); printStream.println(exception.getClass() + " : " + exception.getMessage()); printStream.println(); printStream.println("StackInformation"); exception.printStackTrace(printStream); printStream.println(); } } /** * * @param request */ private void log(HttpServletRequest request) { File dir = new File(request.getSession().getServletContext().getRealPath("/errorLog")); if (!dir.exists()) { dir.mkdir(); } String timeStamp = new java.text.SimpleDateFormat("yyyyMMddhhmmssS").format(new Date()); File file = new File(dir.getAbsolutePath() + File.separatorChar + "error-" + timeStamp + ".txt"); // try(FileOutputStream fileOutputStream = new FileOutputStream(file); // PrintStream ps = new PrintStream(fileOutputStream)){// Write to file // ps.print(byteArrayOutputStream); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e){ // e.printStackTrace(); // } } /** * * @param request * @param key * @param type * @return */ @SuppressWarnings("unchecked") private <T> T getInfo(HttpServletRequest request, String key, Class<T> type){ Object obj = request.getAttribute(key); return obj == null ? null : (T) obj; } } This will enable exception control. The following defines web.xml to let the tomcat error lead to the page error.jsp we just specified
<!-- 404 There is no error in the page --> <error-page> <error-code>404</error-code> <location>/WEB-INF/jsp/common/default/error.jsp</location> </error-page> <!-- // --> <!-- 500 Server internal error--> <error-page> <error-code>500</error-code> <location>/WEB-INF/jsp/common/default/error.jsp</location> </error-page> <!-- // -->
We arrange a default page as follows
The source code is as follows:
<%@page pageEncoding="UTF-8" isErrorPage="true"%> <%@ include file="/WEB-INF/jsp/common/ClassicJSP/util.jsp"%> <!DOCTYPE html> <html> <head> <title>Error page</title> <style> body { max-width: 600px; min-width: 320px; margin: 0 auto; padding-top: 2%; } textarea { width: 100%; min-height: 300px; } h1 { text-align: right; color: lightgray; } div { margin-top: 1%; } </style> </head> <body> <h1>Sorry! </h1> <div style="padding:2% 0;text-indent:2em;">Dear users: We are committed to providing better services, but human calculations are not as good as God's calculations. Some errors have occurred, and I hope they are within the control scope... If the problem occurs repeatedly, please feedback to the system administrator. </div> <textarea><% new ErrorHandler(request, exception, out); %></textarea> <div> <center> <a href="${pageContext.request.contextPath}">Back to home page</a> | <a href="javascript:history.go(-1);">Previous page</a> </center> </div> </body> </html>The above is all about this article, I hope it will be helpful to everyone's learning.