我有一个自定义错误页面设置,用于基本调试,而我编程时由于某些原因,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>
答案 0 :(得分:0)
对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>
答案 1 :(得分:0)
您可以提供这样的错误处理程序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.");
}
}