Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javaservlet/JSP自定义错误页_Java_Jsp_Servlets_Try Catch - Fatal编程技术网

Javaservlet/JSP自定义错误页

Javaservlet/JSP自定义错误页,java,jsp,servlets,try-catch,Java,Jsp,Servlets,Try Catch,我有一个自定义的错误页面设置,用于编程时的基本调试,由于某些原因,try捕获的值都无法通过。错误页面只是说:“空”。如果有人能帮上忙,我将非常感激 Servlet: package com.atrium.userServlets; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; i

我有一个自定义的错误页面设置,用于编程时的基本调试,由于某些原因,try捕获的值都无法通过。错误页面只是说:“空”。如果有人能帮上忙,我将非常感激

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(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>

发生错误。。。

${requestScope.errorMessage}

${requestScope.errorCause}

${requestScope.errorLocation}


您可以提供如下错误处理程序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();
    }
}
因此,如果出现任何异常,您只需要从所有其他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.");
    }
}

1.错误位置与位置不匹配。2.为什么jsp在web inf中?把它放在war文件夹中,直接指向它:“errorDisplay.jsp”我所有的jsp都存储在WEB-INF中,因为它确保用户不通过servlet就无法访问它们,用户必须通过servlet,否则动态函数将无法工作。不过我已经解决了不匹配的问题,谢谢。虽然这并不能解决任何问题。你在其他地方做过类似的事情吗?“错误原因”中的空格怎么办?@Infested我删除了空格,当你说类似的话时,你指的是哪一部分?在WEB-INF中访问JSP?是的,它是有效的。如果这是用于基本调试,那么不捕获异常并让它冒泡如何。。。容器应该显示带有堆栈跟踪的异常?这似乎没有什么区别,当JSP像这样设置时,它会在页面上输出“ErrorMessage”,就是这样。它应该输出什么。。当servlet中的其他地方发生错误时,或者当用户重定向到此页面并显示异常详细信息时,它似乎将errorCause和errorLocation传递null。
@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.");
    }
}