Java Servlet/JSP自定义错误页面 [英] Java Servlet/JSP Custom Error Page

查看:78
本文介绍了Java Servlet/JSP自定义错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom error page setup for basic debugging whilst I'm programming and for some reason none of the values from the try catches get through. The error page just says: "Null null null". If anyone can help with this I'd be very grateful.

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>

推荐答案

您可以提供这样的错误处理程序servlet:

You can provide an error handler servlet like this :

@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中的错误情况:

Then register it to handle the error cases in web.xml like :

<?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抛出异常:

So you just need to throw the exception from all other servlets in case of any exception and it will be handled automatically by this error servlet that we have defined.So, throw the exception from your servlet like :

@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.");
    }
}

这篇关于Java Servlet/JSP自定义错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆