繁体   English   中英

Java Servlet / JSP自定义错误页面

[英]Java Servlet/JSP Custom Error Page

我在编程时有一个用于基本调试的自定义错误页面设置,由于某种原因,try catch的值都无法通过。 错误页面仅显示:“ Null null null”。 如果有人可以提供帮助,我将非常感激。

Servlet:

package com.atrium.userServlets;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.atrium.DAOs.UserDAO;
import com.atrium.userBeans.UserRegistrationBean;

@WebServlet("/Register")
public class UserRegistrationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UserRegistrationServlet() {

        super();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            HttpSession session = request.getSession(false);

            if (session == null) {

                response.sendRedirect(this.getServletContext() + "/Authenticate");
                return;

            }

            request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

        }

        catch(Throwable exception) {

            String errorMessage = exception.getMessage();
            Throwable errorCause = exception.getCause();
            String errorLocation = this.getServletName();

            request.setAttribute("ErrorMessage", errorMessage);
            request.setAttribute("ErrorCause", errorCause);
            request.setAttribute("ErrorLocation", errorLocation);

            request.getRequestDispatcher("/WEB-INF/errorDisplay.jsp").forward(request, response);

        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {       

            String ErrorMessage = "";

            //Check user name is supplied

            if (request.getParameter("Username") == null || request.getParameter("Username") == "") {

                ErrorMessage = "You must enter a username!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check user name for maximum length

            if (request.getParameter("Username").length() > 16) {

                ErrorMessage = "The username you entered was too long! Only 16 characters are allowed.";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check password is supplied

            if (request.getParameter("Password") == null || request.getParameter("Password") == "") {

                ErrorMessage = "You must enter a password!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check verify password is supplied

            if (request.getParameter("vPassword") == null || request.getParameter("vPassword") == "") {

                ErrorMessage = "You must enter your password twice!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check password is equal to verify password

            if (((String)request.getParameter("Password")).equals((String)request.getParameter("vPassword"))) {}
            else {

                ErrorMessage = "The passwords you entered do not match!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check password for complexity

            /*--------------------------------------------------------
            (?=.*[0-9]) a digit must occur at least once
            (?=.*[a-z]) a lower case letter must occur at least once
            (?=.*[A-Z]) an upper case letter must occur at least once
            (?=[\\S]+$) no whitespace allowed in the entire string
            .{6,16} at least 6 to 16 characters 
            ---------------------------------------------------------*/

            Pattern passwordPattern = Pattern.compile("((?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=[\\S]+$).{6,16})");

            Matcher passwordMatcher = passwordPattern.matcher(request.getParameter("Password"));

            if (passwordMatcher.find() == false) {

                ErrorMessage = "The password you entered does not abide by the strength rules!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check email is supplied

            if (request.getParameter("Email") == null || request.getParameter("Username") == "") {

                ErrorMessage = "You must enter an email!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check verify email is supplied

            if (request.getParameter("vEmail") == null || request.getParameter("vEmail") == "") {

                ErrorMessage = "You must enter your email twice!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Check email is equal to verify email

            if (((String)request.getParameter("Email")).equals((String)request.getParameter("vEmail"))) {}
            else {

                ErrorMessage = "The emails you entered did not match!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            //Validate email - *@*

            Pattern emailPattern = Pattern.compile(".+@.+\\.[a-z]+", Pattern.CASE_INSENSITIVE);

            Matcher emailMatcher = emailPattern.matcher(request.getParameter("Email"));

            if (emailMatcher.find() == false) {

                ErrorMessage = "The email you entered is not valid!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

            UserRegistrationBean user = new UserRegistrationBean();
            user.setUsername(request.getParameter("Username"));
            user.setPassword(request.getParameter("Password"));
            user.setEmail(request.getParameter("Email"));

            user = UserDAO.register(user);

            if (user.getExists() == true) {

                ErrorMessage = "The user name you entered has already been registered!";

                request.setAttribute("ErrorMessage", ErrorMessage);

                request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);

                return;

            }

        }

        catch(Throwable exception) {

            String errorMessage = exception.getMessage();
            Throwable errorCause = exception.getCause();
            String errorLocation = this.getServletName();

            request.setAttribute("ErrorMessage", errorMessage);
            request.setAttribute("ErrorCause", errorCause);
            request.setAttribute("ErrorLocation", errorLocation);

            request.getRequestDispatcher("/WEB-INF/errorDisplay.jsp").forward(request, response);

        }

    }

}

JSP错误页面:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Exception Details</title>

</head>

<body>

    <% final String errorMessage = (String)request.getAttribute("ErrorMessage"); %>
    <% final Throwable errorCause = (Throwable)request.getAttribute("ErrorCause"); %>
    <% final String errorLocation = (String)request.getAttribute("ErrorLocation"); %>

    <h1>An Error Occurred...</h1>

    <p>



        <%= errorMessage %><br><br>

        <%= errorCause %><br><br>



    <%= errorLocation %>

</p>

对您的catch块进行以下更改:

catch(Throwable errorMessage) {

            request.setAttribute("errorMessage", (String)errorMessage.getMessage());
            request.setAttribute("errorCause", errorMessage.getCause());
            request.setAttribute("errorLocation", (String)this.getServletName());

        request.getRequestDispatcher("/WEB-INF/errorDisplay.jsp").forward(request, response);

    }

在您的jsp页面上尝试以下操作:

<body>
    <h1>An Error Occurred...</h1>

    <p>



        ${requestScope.errorMessage}<br><br>

        ${requestScope.errorCause}<br><br>

        ${requestScope.errorLocation}

    </p>

</body>

您可以提供一个错误处理程序servlet,如下所示:

@WebServlet("/error")
public class ErrorHandler extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /***** This Method Is Called By The Servlet Container To Process A 'GET' Request *****/
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        handleRequest(request, response);
    }

    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        /***** Analyze The Servlet Exception *****/        
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");

        if (servletName == null) {
            servletName = "Unknown";
        }

        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        if (requestUri == null) {
            requestUri = "Unknown";
        }

        /***** Set Response Content Type *****/
        response.setContentType("text/html");

        /***** Print The Response *****/
        PrintWriter out = response.getWriter();
        String title = "Error/Exception Information";       
        String docType = "<!DOCTYPE html>\n";
        out.println(docType 
                + "<html>\n" + "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>" + title + "</title></head>\n" + "<body>");

        if (throwable == null && statusCode == null) {
            out.println("<h3>Error Information Is Missing</h3>");           
        } else if (statusCode != 500) {
            out.write("<h3>Error Details</h3>");
            out.write("<ul><li><strong>Status Code</strong>?= "+ statusCode + "</li>");
            out.write("<li><strong>Requested URI</strong>?= "+ requestUri + "</li></ul>");
        } else {
            out.println("<h3>Exception Details</h3>");
            out.println("<ul><li><strong>Servlet Name</strong>?= " + servletName + "</li>");
            out.println("<li><strong>Exception Name</strong>?= " + throwable.getClass( ).getName( ) + "</li>");
            out.println("<li><strong>Requested URI</strong>?= " + requestUri + "</li>");
            out.println("<li><strong>Exception Message</strong>?= " + throwable.getMessage( ) + "</li></ul>");
        }

        out.println("<div> </div>Click <a id=\"homeUrl\" href=\"index.jsp\">home</a>");
        out.println("</body>\n</html>");
        out.close();
    }
}

然后将其注册以处理web.xml的错误情况,例如:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
   <display-name>Error/Exception Information</display-name>

   <!-- Error Code Related Error Pages -->
   <error-page>
      <error-code>404</error-code>
      <location>/error</location>
   </error-page>
   <error-page>
      <error-code>403</error-code>
      <location>/error</location>
   </error-page>
   <!-- Exception Type Related Error Pages -->
   <error-page>
      <exception-type>javax.servlet.ServletException</exception-type>
      <location>/error</location>
   </error-page>
   <error-page>
      <exception-type>java.io.IOException</exception-type>
      <location>/error</location>
   </error-page>
</web-app>

因此,您只需要从所有其他servlet抛出异常,以防发生任何异常,它将由我们定义的该错误servlet自动处理。因此,从您的servlet抛出异常:

@WebServlet("/myExceptionServlet")
public class MyExceptionServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        throw new ServletException("HTTP GET Method Is Not Supported.");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM