-1

I'm exploring Servlet 3.0 features for programmatically adding servlets to the context and I can't completely get the differences between:

  1. createServlet(Class<T> clazz)
  2. addServlet(String servletName, Class<? extends Servlet> servletClass)

Considering that:

  • method (1) gives an instance of the servlet;
  • method (1) may throw an exception, whereas method (2) does not.

What's the use for (1)?
I'm using (2) in a ServletContextListener and everything seems to work without a problem.

watery
  • 5,026
  • 9
  • 52
  • 92

1 Answers1

0

The rationale for createServlet is stated in the Javadoc:

The returned Servlet instance may be further customized before it is registered with this ServletContext via a call to addServlet(String,Servlet). This method introspects the given clazz for the following annotations: ... In addition, this method supports resource injection if the given clazz represents a Managed Bean.

So the API allows you to do the following:

// create a servlet, process annotations and do injections
MyServlet myServlet = context.createServlet(MyServlet.class);

// further customization
myServlet.runSpecialInit(someArg);   

// register
context.addServlet("theName", myServlet);

Alternatively you could do the following

MyServlet myServlet = new MyServlet();
myServlet.runSpecialInit(someArg);
context.addServlet("theName", myServlet);

but contrary to the first snippet this will not evaluate annotations and do injections.

And you can think of addServlet(String servletName, Class<? extends Servlet> servletClass) as an abbreviation for

Servlet servlet = createServlet(servletClass);
addServlet(servletName, servlet);   
wero
  • 32,544
  • 3
  • 59
  • 84