Java servlet initialization exceptions

How to throw exceptions for the init() method for servlets

As you can see the compiler is forcing me to use try/catch for instantiating the SecurityController. In my case however I believe it should stop instantiating the Servlet and throw an exception in general if the security controller can’t be instantiated. Any suggestions/explanations to this?

3 Answers 3

init

public void init() throws ServletException

.

Throws:

ServletException — if an exception occurs that interrupts the servlet’s normal operation

Look there, you’re supposed to rethrow it as ServletException . Conform chapter 2.3.2.1 of the Servlet API specification, the servlet will not be placed in service:

2.3.2.1 Error Conditions on Initialization

During initialization, the servlet instance can throw an UnavailableException or a ServletException . In this case, the servlet must not be placed into active service and must be released by the servlet container. The destroy method is not called as it is considered unsuccessful initialization.

.

Thus, just do what the docs state (this is the normal process, by the way, you should as being a Java beginner understand/realize that very good):

@Override public void init() throws ServletException < try < securityController = SecurityControllerFactory.getInstance().create(); >catch (Exception e) < throw new ServletException("Error creating security controller", e); >maxFileSize = getBytes(10); maxMemSize = getBytes(2); > 

Please note that I removed the unnecessary super.init() call. The javadoc isn’t telling anywhere that you’re required to do that for init() , only for init(ServletConfig) .

Unrelated to the concrete problem, having an overly generic catch on Exception is considered poor practice. You certainly don’t want to cover RuntimeException s with your overly generic catch on Exception as that may unintentionally hide away programmer’s mistakes/bugs.

You should try to be as specific as possible in your catch , try to catch as specific as possible the exception(s) being declared in throws of those methods. For example:

 try < securityController = SecurityControllerFactory.getInstance().create(); >catch (SecurityControllerCreationException e)

Another cause could also be that the methods in question are so badly designed that they are by themselves declared as throws Exception . You should in turn fix that part as well.

Источник

The Java EE 5 Tutorial

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container
    1. Loads the servlet class.
    2. Creates an instance of the servlet class.
    3. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.

    If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy method. Finalization is discussed in Finalizing a Servlet.

    Handling Servlet Life-Cycle Events

    You can monitor and react to events in a servlet’s life cycle by defining listener objects whose methods get invoked when life-cycle events occur. To use these listener objects you must define and specify the listener class.

    Defining the Listener Class

    You define a listener class as an implementation of a listener interface. Table 4-2 lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event. For example, the methods in the HttpSessionListener interface are passed an HttpSessionEvent, which contains an HttpSession.

    Table 4-2 Servlet Life-Cycle Events

    Listener Interface and Event Class

    Initialization and destruction

    Attribute added, removed, or replaced

    Creation, invalidation, activation, passivation, and timeout

    javax.servlet.http.HttpSessionListener, javax.servlet.http.HttpSessionActivationListener, and

    Attribute added, removed, or replaced

    A servlet request has started being processed by web components

    Attribute added, removed, or replaced

    The tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/listeners/ContextListener class creates and removes the database access and counter objects used in the Duke’s Bookstore application. The methods retrieve the web context object from ServletContextEvent and then store (and remove) the objects as servlet context attributes.

    import database.BookDBAO; import javax.servlet.*; import util.Counter; import javax.ejb.*; import javax.persistence.*; public final class ContextListener implements ServletContextListener < private ServletContext context = null; @PersistenceUnit EntityManagerFactory emf; public void contextInitialized(ServletContextEvent event) < context = event.getServletContext(); try < BookDBAO bookDB = new BookDBAO(emf); context.setAttribute("bookDB", bookDB); >catch (Exception ex) < System.out.println( "Couldn’t create database: " + ex.getMessage()); >Counter counter = new Counter(); context.setAttribute("hitCounter", counter); counter = new Counter(); context.setAttribute("orderCounter", counter); > public void contextDestroyed(ServletContextEvent event) < context = event.getServletContext(); BookDBAO bookDB = context.getAttribute("bookDB"); bookDB.remove(); context.removeAttribute("bookDB"); context.removeAttribute("hitCounter"); context.removeAttribute("orderCounter"); >>
    Specifying Event Listener Classes

    You specify an event listener class using the listener element of the deployment descriptor. Review The Example Servlets for information on how to specify the ContextListener listener class.

    You can specify an event listener using the deployment descriptor editor of NetBeans IDE by doing the following:

    1. Expand your application’s project node.
    2. Expand the project’s Web Pages and WEB-INF nodes.
    3. Double-click web.xml.
    4. Click General at the top of the web.xml editor.
    5. Expand the Web Application Listeners node.
    6. Click Add.
    7. In the Add Listener dialog, click Browse to locate the listener class.
    8. Click OK.

    Handling Servlet Errors

    Any number of exceptions can occur when a servlet executes. When an exception occurs, the web container generates a default page containing the message

    A Servlet Exception Has Occurred

    But you can also specify that the container should return a specific error page for a given exception. Review the deployment descriptor file included with the example to learn how to map the exceptions exception.BookNotFound, exception.BooksNotFound, and exception.OrderException returned by the Duke’s Bookstore application to errorpage.html.

    See Mapping Errors to Error Screens for instructions on how to specify error pages using NetBeans IDE.

    Copyright © 2010, Oracle and/or its affiliates. All rights reserved. Legal Notices

    Источник

    Servlet.init exception

    Am developing MVC Spring Application have Maven nature. Everything seems OK, but recently I got this error :

    Servlet.init() for servlet dispatcher threw exception 
    exception javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:619) root cause org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.nortal.vspa.controller.HelloWorldController] for bean with name '/welcome.htm' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.nortal.vspa.controller.HelloWorldController org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1250) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576) org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1319) org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:885) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127) javax.servlet.GenericServlet.init(GenericServlet.java:212) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:619) 
       dispatcher org.springframework.web.servlet.DispatcherServlet 1  dispatcher *.htm  redirect.jsp  

    Источник

    Читайте также:  Command line for java version
Оцените статью