Java Coder
How do I throw a 404 error from within a java servlet?
1 Answer(s)      8 months ago
Posted in : Servlet Interview Questions

How you can write code in Servlet for throwing the httpd error 404?

How to add the configuration for handling the not found error in the web.xml file?

Thanks

Advertisement
View Answers

July 7, 2014 at 12:28 PM


Hi,

Add the following code in the web.xml file:

<error-page>
  <error-code>404</error-code>
  <location>/WEB-INF/views/notfound.jsp</location>
</error-page>

and in the servlet you can use the following code:

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

Check more Servlet tutorials.

Thanks