Error page

Java/Servlets/Error Exceptions

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Sender extends HttpServlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException < /* * if the servlet tries to access a resource and finds out that the * client is not authorized to access it - "401 Unauthorized" */ //response.sendError(401,"You are not authorized to view the requested // component"); /* * if the servlet tries to access a resource that is forbidden for this * client and there is no further information on it - "403 Forbidden" */ response.sendError(403); /* * if the servlet tries to access a resource that is not found given the * client"s provided URL - "404 Not Found" */ //response.sendError(404); >public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException

Generate errors

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ErrorGen extends HttpServlet

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException < //check the servlet exception Throwable throwable = (Throwable) request .getAttribute("javax.servlet.error.exception"); String servletName = (String) request .getAttribute("javax.servlet.error.servlet_name"); if (servletName == null) servletName = "Unknown"; String requestUri = (String) request .getAttribute("javax.servlet.error.request_uri"); if (requestUri == null) requestUri = "Unknown"; response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); if (throwable == null) 

The error information is not available

out.println("Please return to the "); > else 

Here is the error information

out .println("The servlet name associated with throwing the exception: " + servletName + "

"); out.println("The type of exception: " + throwable.getClass().getName() + "

"); out.println("The request URI: " + requestUri + "

"); out.println("The exception message: " + throwable.getMessage()); > out.println(""); out.println(""); out.close(); > public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException

Servlet throws Exceptions

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Thrower extends HttpServlet public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException < throw new java.io.IOException("IO thrown"); //response.sendError(403); >public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException

Источник

Servlet 3 Exception Handling example

In this tutorial we will tackle servlet 3 exception handling. When a servlet generates an error we can handle those exceptions on various ways, lets say a user tries a URL that does not map to a servlet the user typically gets a 404 page. With the error listing in our web.xml also known as deployment descriptor we can handle those exceptions.

Project structure

+--src | +--main | +--java | +--com | +--memorynotfound | |--ErrorServlet.java | |--ExampleServlet.java | |--resources | +--webapp | +--WEB-INF | |--web.xml pom.xml

Maven Dependency

  javax.servlet javax.servlet-api 3.1.0 provided  

Defining our Servlet that will produce an error

This servlet is used to throw an error tot test our configuration.

package com.memorynotfound; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet("/error") public class ExampleServlet extends HttpServlet < protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException < throw new UnsupportedOperationException("HTTP GET request is not allowed!"); >>

Servlet 3 Exception Handling

We will map this servlet in our servlet descriptor to handle all the exception. You can get information about the exception that occurred from the request attributes. Here is a list of possible attributes that are in the request when an exception occurred.

  • javax.servlet.error.exception will hold information about the exception thrown.
  • javax.servlet.error.status_code will hold the statuscode returned by the container.
  • javax.servlet.error.servlet_name will hold the servlet name in case the exception is thrown from within a servlet.
  • javax.servlet.error.request_uri will hold the request URI from where the error request originated.
  • Servlet Name:" + servletName + ""); out.write("
  • Exception Name:" + exception.getClass().getName() + ""); out.write("
  • Requested URI:" + requestUri + ""); out.write("
  • Exception Message:" + exception.getMessage() + ""); out.write("

Servlet 3 web.xml Configuration

We can define our servlet 3 exception handling servlet in the servlet descriptor.

  • Global: If none of the other error-code or exception-type definitions maps then this global location element will map to the exception handler.
  • Error Code: If a specific error occurres that maps to an error code then the error page will be forwarded to the registred servlet 3 exception handling error servlet.
  • Exception Type: This will maps the thrown exception with a exception handler.
   /error-handler   404 /error-handler   java.lang.UnsupportedOperationException /error-handler  

Demo

404 – Page Not Found

404 servlet 3 exception handling example

500 – Servlet That Generates an Error

500 servlet 3 exception handling example

References

Источник

[Solved] Tomcat Error HTTP Status 404 Not Found

tomcat-error-404

The error code is HTTP 404 (not found) and the description is:

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

This error means the server could not find the requested resource (JSP, HTML, images…) and returns HTTP status code 404. Most of the time, you can fix this error by correcting the URL. However, sometimes it’s not easy like that, making it is an annoying error.

Here I suggest some possible reasons and how to fix the error HTTP 404 in Java web development with Tomcat.

1. The URL is not handled by any Java servlets

You need to check URL mapping in your servlet classes to make sure the requested URL is actually handled by a servlet. For example:

@WebServlet("/view_book") public class ViewBookServlet extends HttpServlet

This servlet handles the URL /view_book . If the request URL is /view_books the server will raise HTTP 404 error. You can fix by either correcting the URL or correcting the URL mapping in the @WebServlet annotation.

In older Java web application, you have to check the web deployment descriptor file web.xml because a Java servlet can be mapped to URL via XML like this:

 ViewBookServlet /view_book 

2. Java servlet forwarding to a resource that does not exist

In this case, the requested URL is handled by a Java servlet, but code in the servlet forwards to a resource (JSP, HTML…) which does not exist, as shown in the following screenshot:

tomcat-error-404-forwarding

The code in the servlet class would look like this:

String registerForm = "frontend/registerform.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(registerForm); dispatcher.forward(request, response);

You can fix by correcting the forward path in the servlet, and make sure that the forwarded resource does actually exist in the given path.

3. URL is case-sensitive

Note that Tomcat treats URL as case-sensitive, for instance /Register is different than /register . So you need to check and use correct case for the letters in request URL.

Also pay attention to the webapp name in the URL, for instance http://localhost:8080/BookstoreWebsite/ is different than http://localhost:8080/BookStoreWebsite/

TIP: in Eclipse, you can right click on the project, then click Run As > Run on Server, the IDE will always use the correct name of the web application.

Finally, you should not let the user see the raw HTTP 404 error page rendered by the server. Instead, you should design your own user-friendly 404 error page – follow this tutorial: How to Handle Error for Java web applications.

You can also watch the video version below:

Other Java Servlet Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

[Solved] Tomcat Error HTTP Status 404 Not Found

tomcat-error-404

The error code is HTTP 404 (not found) and the description is:

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

This error means the server could not find the requested resource (JSP, HTML, images…) and returns HTTP status code 404. Most of the time, you can fix this error by correcting the URL. However, sometimes it’s not easy like that, making it is an annoying error.

Here I suggest some possible reasons and how to fix the error HTTP 404 in Java web development with Tomcat.

1. The URL is not handled by any Java servlets

You need to check URL mapping in your servlet classes to make sure the requested URL is actually handled by a servlet. For example:

@WebServlet("/view_book") public class ViewBookServlet extends HttpServlet

This servlet handles the URL /view_book . If the request URL is /view_books the server will raise HTTP 404 error. You can fix by either correcting the URL or correcting the URL mapping in the @WebServlet annotation.

In older Java web application, you have to check the web deployment descriptor file web.xml because a Java servlet can be mapped to URL via XML like this:

 ViewBookServlet /view_book 

2. Java servlet forwarding to a resource that does not exist

In this case, the requested URL is handled by a Java servlet, but code in the servlet forwards to a resource (JSP, HTML…) which does not exist, as shown in the following screenshot:

tomcat-error-404-forwarding

The code in the servlet class would look like this:

String registerForm = "frontend/registerform.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(registerForm); dispatcher.forward(request, response);

You can fix by correcting the forward path in the servlet, and make sure that the forwarded resource does actually exist in the given path.

3. URL is case-sensitive

Note that Tomcat treats URL as case-sensitive, for instance /Register is different than /register . So you need to check and use correct case for the letters in request URL.

Also pay attention to the webapp name in the URL, for instance http://localhost:8080/BookstoreWebsite/ is different than http://localhost:8080/BookStoreWebsite/

TIP: in Eclipse, you can right click on the project, then click Run As > Run on Server, the IDE will always use the correct name of the web application.

Finally, you should not let the user see the raw HTTP 404 error page rendered by the server. Instead, you should design your own user-friendly 404 error page – follow this tutorial: How to Handle Error for Java web applications.

You can also watch the video version below:

Other Java Servlet Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Читайте также:  Заголовок страницы
Оцените статью