Note: Some servlet questions may also be answered in the TomcatFaq or the JspFaq
Discuss servlets in the Servlets Forum
ServletNotRunning404 : Why am I getting 404, the requested resource is not available?
RedirectForward : What is the difference between sendRedirect and forward?
ParametersAndAttributes : What is the difference between parameters and attributes?
Model1Model2MVC : What is MVC? What is the difference between Model 1 and Model 2?
CompilingServlets : How do I compile a servlet?
NoCacheHeaders : How do I prevent the browser from caching my dynamic content?
FileUpload : How do I upload a file in a servlet app?
IllegalStateException : The most common cause of this exception and an easy rule of thumb for preventing it.
ServletFilters : information, articles and useful filters
DeclaringListeners : Declaring lifecycle listeners in web.xml
InvokerServlet : how to access a servlet using its fully qualified class name instead of mapping it in web.xml (hint: it's a bad idea to do this)
TypesOfPaths: what are the various types of paths one might see or use in web applications?
RelativeLinks: How to build robust server-relative links in Servlet and JSP applications
SpecificationUrls : Where to find Servlet, JSP and HTTP specifications
What are the differences between the various Servlet API versions? (link)
What are some Java hosting companies? (link)
In the interface javax.servlet.RequestDispatcher, what is the difference between the forward(ServletRequest, ServletResponse) and include(ServletRequest, ServletResponse) methods? (link)
What is the difference between the init() and init(ServletConfig) methods? (link)
Why do servlets have an init method? Can't we make use of the servlet constructor for initialization? When should I call the destroy method? What happens if i call destroy() from init()? (link)
What is the difference between the getRequestDispatcher(String) and getNamedDispatcher(String) methods in the ServletContext Class? (link)
How can I filter the j_security_check URL used for FORM authentication? (link)
What is the difference between GenericServlet and HttpServlet? (link)
Why do we override the doGet and/or doPost methods instead of the service method? (link)
How can I use servlets with protocols other than HTTP, e.g. FTP? (link)
How do I implement security for my web application? (link)
Article on how to enable GZIP compression on Resin, Tomcat and Apache httpd
Article on creating an ImageServlet to serve multimedia content from your servlet-based web application.
Article on creating thread-safe servlets.
What are the differences between the various Servlet API versions?
What's new in Servlet API 2.1: http://www.servlets.com/soapbox/servlet21.html
What's new in Servlet API 2.2: http://www.servlets.com/soapbox/servlet22.html
What's new in Servlet API 2.3: http://www.servlets.com/soapbox/servlet23.html
What's new in Servlet API 2.4: http://www.javaworld.com/jw-03-2003/jw-0328-servlet.html
What's new in Servlet API 3.1: Article
What are some java hosting companies?
This list is not an endorsement of any kind. It simply points to companies that have been mentioned by someone at some point. Feel free to add your own favorite. A list of Java PaaS providers can be found here.
In the interface javax.servlet.RequestDispatcher, what is the difference between the forward(ServletRequest, ServletResponse) and include(ServletRequest, ServletResponse) methods?
Forward will transfer the control to the target resource (servlet or JSP), without returning the control to the caller.
Include will transfer the control to the target resource (servlet or JSP), but then returning the control to the caller after the execution.
What is the difference between the init() and init(ServletConfig) methods?
Code from GenericServlet in javax.servlet package:
If we look at the above code we can understand that the init() method with no args is called from within the init(ServletConfig) method.
If we override the init(ServletConfig) method that takes a ServletConfig then super.init(config) should be the first statement inside that overridden method.
Because the container creates a ServletConfig instance and passes that instance to the init method of the GenericServlet where that config instance is assigned to the local private copy of that class. (private transient ServletConfig;)
Code from GenericServlet in javax.servlet package:
If we override the init(ServletConfig) method that takes a ServletConfig and didn't specify the super.init(config) then the local copy of the ServletConfig instance will not be initialized and if you try to use the getInitParameter(String) method of the ServletConfig interface (which has not been initialized to some value in the GenericServlet class) a NullPointerException will be the result.
This is a very good example of encapsulation as the instance variable (private transient ServletConfig config;) is kept private and the getter methods are used to get that particular instance.
Why do servlets have an init method? Can't we make use of the servlet constructor for initialization?
You can't make use of the constructor because the container calls it and therefore you can't pass any parameters to the constructor. Also at the point the constructor is called the class is not really a Servlet because it doesn't have a reference to the ServletConfig, which provides all the initialisation parameters etc.
Because the servlet container manages the servlet lifecycle, one should never call the constructor, the init and destroy methods.
Why can't a container call constructor having parameters?
As it is the container that manages a servlets lifecycle, you must define a generic way of working for all servlets. You can't use the constructor because otherwise you would have to modify the container to tell him to instantiate this particular servlet.
What happens if i call destroy() from init()?
Read through this thread
What is the difference between the getRequestDispatcher(String) and getNamedDispatcher(String) methods in the ServletContext Class?
Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
getNamedDispatcher(String) method takes the name of the Servlet as parameter which is declared via Deployment descriptor.
Example: Deployment Descriptor
RequestDispatcher dispatch = request.getNamedDispatcher(?FirstServlet?);dispatch.forward(request, response);
Note: A servlet instance can determine its name using servletConfig.getServletName(); This method returns the name of the class that implements the Servlet interface or extends the HttpServlet class.
Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
RequestDispatcher dispatch = request.getRequestDispatcher("/tes");
Here "/tes" represents the url-pattern element value of the servlet class.
It represents the path of the servlet class. Since both the base as well as target servlet are in the same package structure by just specifying the url-pattern element value we will be able to access the target servlet.
We shouldn't specify the entire path like
String str = "/WEB-INF/classes/com/example/posr/Test"
RequestDispatcher dispatch = request.getRequestDispatcher(str);
To forward a request to a JSP page we use
RequestDispatcher dispatch = request.getRequestDispatcher("/TestJspOne.jsp");
Here "/TestJspOne.jsp" the slash denotes the Jsp page is at the root of the application.
How can I filter the j_security_check URL used for FORM authentication?
If you want a standards-compliant solution, have a look at SecurityFilter.
What is the difference between GenericServlet and HttpServlet?
The differences can be seen here: JavaDoc:javax.servlet.http.HttpServlet
The methods particular to HttpServlet are listed first.
Then, the methods inherited from GenericServlet are listed.
Why do we override the doGet and/or doPost methods instead of the service method?
The only thing the service method does is examining the HTTP method, and based on that, dispatch the request to the various doXYZ methods.
While most servlets perform the same action when invoked through GET and through POST, there are circumstances when a servlet might react differently, or possibly disallow one of the methods altogether. (As an aside, the HTTP specification is quite clear about the fact that GET and POST should be used for different purposes, so servlets that use them interchangeably do not quite conform to standards.)
There is one situation in which it is necessary to override service: HTTP 1.1 allows new HTTP methods to be defined, so-called HTTP extensions. One widely used standard that does this is WebDAV. To recognize the new methods and dispatch accordingly, the service method needs to be overridden.
How can I use servlets with protocols other than HTTP, e.g. FTP?
The javadocs for javax.servlet.Servlet and GenericServlet make it sound as if protocols other than HTTP can be used simply by extending GenericServlet, and implementing the methods that deal with the protocol, much like HttpServlet does for HTTP. That is not the case. The protocol needs to be supported by the servlet engine (which does all the network handling for the servlet), and no servlet engine exists that supports anything other than HTTP(S). Adding a different protocol would be a big project, especially since other protocols don't have the same request/response nature of HTTP. If you find yourself contemplating such a project, post your requirements to the Servlet forum, and a better solution will probably be suggested.
For JSPs, the specification says "Most JSP pages use the HTTP protocol, but other protocols are allowed by this specification.". Since a non-HTTP JSP implementation would depend on a non-HTTP servlet implementation, that too is just a theoretical possibility.
(Note that all of this has nothing to do with a servlet's ability to be a client for other protocols. E.g., by using the JavaMail or Jakarta Commons Net APIs a servlet can access SMTP and FTP servers without problems.)
How do I implement security for my web application ?
If all you need are named users, passwords and roles, then the web-tier authentication defined in the servlet specification may be sufficient. Check out Part X - Security of the JEE Tutorial, particularly the chapter on Getting Started Securing Web Applications for an introduction.
In your web.xml you need to set up three section (the servlet specification explains in detail what goes into each of these): security-constraint, where you set up which URL patterns are protected, login-config, where you define the method of login (often BASIC or FORM), and security-role, where you define the roles you use in your web app
(Tomcat only: You'll also need to set up a Realm where you store your users, passwords and roles; the relevant documentation part of the Tomcat docs: Realm How-To and Realm Configuration. Common options are MemoryRealm, which stores information in a file (often conf/tomcat-users.xml) or JDBCRealm, which accesses a database. The Realm to use is specified in the conf/server.xml file, in a <Realm> and a <Resource> element. Search for "UserDatabase" in your existing server.xml and you'll find the spots you need to adapt. Other servlet container use different mechanisms; check the documentation of the one you're using.)
Once you've set this up, you can use the getRemoteUser, getUserPrincipal, getAuthType and isUserInRole methods of HttpServletRequest to find out which user is logged in, and whether that user is authenticated for a particular role.
The use of HTTPS/SSL can be required by adding the following to the web.xml file:
CategoryFaq JspFaq TomcatFaq