Upload
harsan
View
48
Download
1
Embed Size (px)
DESCRIPTION
Servletsss
Citation preview
MYJAVAHUB.BLOGSPOT.COM
Servlet concepts :
1. What's the difference between applets and servlets?
A: There are many fundamental differences between Applet and Servlet classes, the Java
API documentation for the two types will show you they have little in common.
Applets are essentially graphical user interface (GUI) applications that run on the
client side in a network environment, typically embedded in an HTML page.
Applets are normally based on Abstract Windowing Toolkit components to maintain
backward-compatibility with the widest range of browsers' Java implementations. The
application classes are downloaded to the client and run in a Java Virtual Machine
provided by the browser, in a restrictive security environment called a "sandbox".
Servlets are used to dynamically generate HTTP responses and return HTML content
to Web browsers on the server side.
Servlets are often used to validate and process HTML form submissions and control a
series of user interactions in what is known as a Web application. Servest can be used
to control all aspects of the request and response exchange between a Web browser
and the server, called a servlet container.
2. Do we open servlet classes directly instead of HTML?
A: Servlets are used to deliver HTML to Web browsers, but they are not like static HTML
documents. When you set up a servlet in a Web application it has a URL like a static HTML
document, so you can link to it, bookmark it or send the URL by email, just as you would
with an standard Web page. The main difference is that the HTML sent to the Web browser
is composed dynamically by the servlet and its contents can be customized based on the
details of the request sent by the Web browser.
When you open a servlet URL the browser does not display content of the servlet class, but a
dynamic HTML document created by the servlet. The servlet class is written as a standard
Java class that extends the HttpServlet class. In its most basic form, the HTML output can be
created by a series of print() statements on a PrintWriter. The method that handles simple
Web requests is called doGet(), as below.
public final void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter output = response.getWriter();
output.println("<html>");
output.println(" <head>");
output.println(" <title>");
// Other HTML output
output.flush();
output.close();
}
3. What part of the Java platform do servlets and JSP belong to?
A: The servlet and JSP APIs are a standard extension to the core Java API and runtime
system. Their package names are prefixed javax to indicate they are standard extensions, but
that means that they rely upon a code implementation provided by a specific vendor.
MYJAVAHUB.BLOGSPOT.COM
For example, the Apache Tomcat project supplies its own implementation of the servlet and
JSP API that is integrated with the servlet container. Developers must compile their code
using the vendor's servlet package implementation by including it in the compiler's
classpath. The servlet container includes the same package classes in its runtime system and
feeds concrete instances of the servlet interface types to the servlet's lifecycle methods.
4. How does the JVM execute a servlet compared with a regular Java class?
A: Servlets are standard Java classes and are executed by the Java Virtual Machine in
exactly the same way as any other. However, the environment or context in which servlets
are executed is different. A servlet is not invoked directly through a main() method, the class
is loaded and run by a servlet container.
When you run a servlet container, it reads its configuration, identifies the servlet classes to
make available, and uses the Java classloader system to load and run the servlets. When the
servlets are first brought into service, the servlet container calls the servlet's init() method
and passes the ServletConfig object as an argument. Whenever a request is made to the
servlet, the container creates a new thread in which to handle it.
5. How can I tell when a servlet is instantiated?
A: A servlet must be instantiated before it is brought into service by the servlet container, so
one way to check is to make a request to the servlet and check the response. If you need to
check indirectly, you can override the init(ServletConfig) method and add
log(String)statements to it. This method is called after the servlet container has instantiated
the servlet before it is brought into service.
Servlet programming
6. How can I write a servlet using Javascript?
A: Java servlets is a server side technology that delivers dynamic content to Web browsers
and other clients. Javascript is also delivered by a Web server, but the code is only
interpreted and executed after it has been downloaded by the Web browser. This means that
it is not possible to write servlet code in Javascript.
It is possible to include Javascript in the output of servlets and Java Server Pages, just like
standard Web pages. It is also possible to dynamically generate Javascript using a servlet
and use it as the source for a script tag, though this is only advisable in rare cases.
7. Can I use a normal class to handle my requests?
A: Servlets are normal Java classes, they compile and run just like any other class. All that is
required is that servlets implement the javax.servlet.Servlet interface. Usually, they extend a
protocol-specific class such as javax.servlet.http.HttpServlet.
… full answer hidden, click for full answers
Premium members click below for full answer
Can I use a normal class to handle my requests?
8. Can I include normal Java classes in servlets?
MYJAVAHUB.BLOGSPOT.COM
A: Any Java class can be used in a Web application, provided you make the classes available
to the servlet container at runtime. The Java API classes can be used directly by adding
import statements to your servlet class. Other supporting classes can also be imported, but
these classes must be added to the classes or lib directory of your application.
If you need to configure the supporting classes, this can be done with standard servlet
configuration features using the ServletConfig and ServletContext objects available to
theinit(ServletConfig) method.
9. Can I use a constructor in my servlet?
A: A servlet is a normal Java class, so when there are no custom constructors, there is an
implicit default constructor with no arguments. Servlet containers typically use
theClass.newInstance() method to load servlets, so you must be careful to add an explicit
default constructor if you add non-default constructors.
… full answer hidden, click for full answers
Premium members click below for full answer
Can I use a constructor in my servlet?
10. What happens if I add a main method to my servlet?
A: It is possible to write a main method for a servlet, but it will not be called by the servlet
container, it is not part of the servlet lifecycle process. If you invoke your servlet through
themain method using the java command it will behave exactly like a standard Java class, it
cannot operate as a Web application in its own right and cannot be addressed using HTTP
requests. Servlets must run in a servlet container to deliver Web applications as intended.
Servlet start up
11. Can one JSP or Servlet extend another Servlet or JSP
A: It is possible and necessary for servlets to extend other classes, they are standard Java
classes in most respects. Most servlets extend the abstract HttpServlet class included in a
servlet container's API implementation. This abstract class implements the generic
Servletinterface with HTTP-specific methods and provides a minimal basis to extend and
create your own servlet classes. If you need to develop complex behaviour across a set of
servlets you can extend this hierarchy to create numerous servlet subclasses.
The automatic source code generation and compilation scheme used to create JSP servlets
means that extension of the JSP servlet class is more complex and should generally be
avoided.
12. How do I compile a servlet?
A: To compile a servlet, you will need to have the Java Servlet API classes in your
classpath. Most Java servlet containers come with a copy, it may be called servlet.jar or
something similar. The basic classes are in the packages javax.servlet and javax.servlet.http.
… full answer hidden, click for full answers
Premium members click below for full answer
How do I compile a servlet?
MYJAVAHUB.BLOGSPOT.COM
13. Why won't my servlet compile?
A: All those "cannot find symbol" error messages mean that you do not have the Java servlet
JARfile on your compiler's classpath, so it cannot find the servlet class files. The servlet JAR
file is normally distributed with your servlet container. For Apache Tomcat it is a file
named{CATALINA_HOME}/common/lib/servlet-api.jar. Add this to your compiler
classpath as follows.
… full answer hidden, click for full answers
Premium members click below for full answer
Why won't my servlet compile?
14. Where is the servlet stored and where does it run?
A: When you create a servlet, the code must be installed in a servlet container which
operates as an HTTP server application. In the a development environment the servlet
container is often installed on a developer's own workstation, or a hardware server in the
local network where it can be accessed privately for testing. In a production environment the
servlet container is usually installed on a server that is accessible from the Internet, but the
Java software arrangement is basically the same.
Servlet code is compiled to Java class byte code which is physically located on the server
hardware with the servlet container. The servlet operates as an extension of the servlet
container and its code is executed on the server. Web browsers operate as clients which
connect to the servlet container, issue HTTP requests and receive HTTP responses from the
servlet container, mostly in the form of HTML pages and other Web content. The servlet
code is not downloaded or executed by the Web browser at all, it only receives standard
Web content and renders it accordingly.
15. What are the basic steps to run a servlet?
A: The key steps in creating and running a servlet are outlined below in the simplest form.
There are different techniques that can be used to complete these stages, described in other
FAQ answers.
1. Write and compile your servlet, e.g. ExampleServlet.class
2. Create a Web application directory structure under the webapp directory of your servlet
container (or use an existing one), e.g.
3. {webapps-dir}/example
4. {webapps-dir}/example/WEB-INF
5. {webapps-dir}/example/WEB-INF/classes
6. Place your servlet class file in the WEB-INF/classes directory for your application, e.g.
7. {webapps-dir}/example/WEB-INF/classes/ExampleServlet.class
8. Create a WEB-INF/web.xml file for your application (or edit an existing one) and
addservlet and servlet-mapping elements for your servlet, e.g.
9. {webapps-dir}/example/WEB-INF/web.xml
10. Start the servlet container.
MYJAVAHUB.BLOGSPOT.COM
16. What is the difference between JAR and WAR files?
A: There is no difference between the binary form of JAR and WAR files, they both use zip
compression provided by the jar tool. You can create a WAR file by navigating to the root
directory of your Web application and typing the jar command, as below.
… full answer hidden, click for full answers
Premium members click below for full answer
What is the difference between JAR and WAR files?
17. Can I access a servlet from a stand alone client?
A: It is certainly possible to access a servlet that is hosted in a servlet container. Any
HTTPclient should be able to connect to a properly configured servlet container and make
requests to a servlet. However, servlets do not run in their own right, they are not server
applications.
18. How can I write a servlet client for testing?
A: Marty Hall provides the source code for a basic HTTP client in his book Core Servlets
and Java Server Pages. The source code for chapter 3 is available online. Look for
WebClient.java and supporting classes. This application allows you to manually input the
host, request path, HTTP header values and view the headers returned by a Web application.
19. What is URL-rewriting?
A: URL-rewriting is a way of maintaining a session between an HTTP client and a servlet
container which does not use cookies. Rather than exchange a session ID in a cookie, the
servlet container includes it in the hyperlink URLs it generates for servlets and JSP.
… full answer hidden, click for full answers
Premium members click below for full answer
What is URL-rewriting?
20. How can I redirect a request to another URL?
A: The standard servlet method to redirect one HTTP request to another is
theHttpServletResponse sendRedirect(String) method. The String argument is the URL for
the address you want to direct people to.
String otherURL = "http://example.com/otherPage.jsp";
response.sendRedirect(otherURL);
When you call this method it will issue an HTTP redirect request to the browser, commit the
servlet response and end the HTTP exchange. The browser should automatically create a
new HTTP request for the given URL that will be entirely separate from the original request.
HTTP redirection is different from the RequestDispatcher forward() method, which sends
the forwarded content in the original HTTP response stream.
21. What's the difference between forward, include and redirection?
MYJAVAHUB.BLOGSPOT.COM
A: The RequestDispatcher forward() and include() methods are mechanisms that are internal
to a servlet container and do not affect the public URL of a Web resource. When you call the
forward() method on a RequestDispatcher with a JSP path, the servlet container returns the
JSP content on the original servlet's URL; this effectively becomes the response of the
servlet itself.
… full answer hidden, click for full answers
22. What is the servlet lifecycle?
A: The servlet lifecycle is a standard sequence of callback events that a servlet container will
apply to a servlet to bring it into service and control its shut down. When a servlet is first
brought into service, the servlet container will call its init(ServletConfig) method with a
servlet configuration object based on its web.xml entry. When the servlet container takes a
servlet out of service, it calls the servlet's destroy() method. Between initialisation and
destruction, the servlet is in its normal service phase and can handle standard service
methods.
… full answer hidden, click to get full answers
Premium members click below for full answer
What is the servlet lifecycle?
23. Can we overload methods in the servlet lifecycle?
A: Yes, you can overload any servlet lifecycle method, but your overloaded method will not
be called directly by the servlet container in preference over the standard lifecycle methods.
You would need to include a call to your overloaded method in the body of one of the
standard lifecycle methods. You could create a custom doGet() method to conditionally
handle the outcome of the standard doGet() method call, as in the simple example below.
… full answer hidden, click to get full answers
Premium members click below for full answer
Can we overload methods in the servlet lifecycle?
24. Can't I use a constructor instead of init(ServletConfig)?
A: It is possible to have a custom constructor for a servlet, so long as you also add a default
constructor with no arguments, but constructors are not called in the standard servlet
lifecycle. Servlets are usually instantiated by the servlet container using the
Class.newInstance() method, with no arguments. At this point, the servlet has no reference to
its configuration or the general servlet context, so it cannot do any useful start-up activity.
These configuration references are only available through the init(ServletConfig) method.
25. Why is it necessary to call super.init(config)?
A: Servlet programmers are expected to call the super.init(ServletConfig) in the
init(ServletConfig) method so that the abstract superclass implementation of the method in
MYJAVAHUB.BLOGSPOT.COM
GenericServlet stores the servlet configuration object. When the configuration object is
stored in this way, the servlet methods getInitParameter(String) and
getInitParameterNames() can be called instead of calling the equivalent methods on the
configuration object.
26. Should I get my database connection in the init() method?
A: The init(ServletConfig) method is only called once when a servlet is brought into service
by the servlet container, not for each new servlet thread. If you create a single database
connection in the init(ServletConfig) method and use it to all handle servlet requests, you
must ensure all operations are synchronized or you will get unpredictable results. You must
also ensure the connection is closed when the servlet is taken out of service by overriding the
servlet's destroy() method.
Generally it is better to use the init(ServletConfig) method to register the database driver and
get a reference to the DriverManager, a DataSource or database connection pool. Then use
the connection provider to get a connection for each request within a try/catch block. This
way you can handle the case where the connection fails, and ensure that all connections are
closed in any case. The close() method of a pooled Connection instance just returns it to the
pool.
27. How do I get configuration parameters for a servlet?
A: To pass variable values to a servlet, you should add an initialization parameter to your
servlet configuration, see the answer to the question What's the difference between
ServletConfig and ServletContext?
… full answer hidden, click to get full answers
Premium members click below for full answer
How do I get configuration parameters for a servlet?
28. What's the difference between ServletConfig and ServletContext?
A: The ServletContext object represents the context for the whole Web application in which
a servlet is deployed, and contains initialisation parameters that are shared amongst all
servlets in the application. The ServletConfig object represents the configuration for a single
specific servlet.
… full answer hidden, click to get full answers
Premium members click below for full answer
What's the difference between ServletConfig and ServletContext?
29. How can I load a Properties file for my servlet?
A: There are standard methods for identifying and loading this type of static property set into
servlets via the ServletContext object. The primary method is getResourceAsStream(String
path), which opens an InputStream to the path given in the argument. The path must begin
MYJAVAHUB.BLOGSPOT.COM
with a forward slash, /, and is relative to the context root, so for instance you might use the
path:
/WEB-INF/servlet.properties
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I load a Properties file for my servlet?
The destroy() method
30. What happens if destroy() is not called?
A: The destroy() method and other servlet lifecycle methods are called by the servlet
container, so it would be a serious error if the servlet container did not call the destroy()
method as it takes a servlet out of service. Normally your application code should not call
servlet lifecycle methods. It is not advisable for your application code to call the destroy()
method directly, it would be confusing and potentially destructive, so it is not a problem if
your application does not call the method at all.
31. Is it possible to overload the destroy() method?
A: Any Java method may be overloaded, but the overloaded version will not be called
directly by a servlet container's lifecycle methods. The servlet container expects all servlets
to have a standard no argument destroy() method, so your servlet is safe to use destroy
methods with other signatures.
public void destroy(final String arg) {
// Overloaded method body
}
32. Can I call destroy() from the service() method?
A: The destroy() method has a special significance in the servlet lifecycle when it is called
by the servlet container, but is a normal method in all other respects. If you have a typical
destroy() method that does servlet clean-up work before the servlet is taken out of service, it
is difficult to imagine why you would want to call it from the service() method, though it is
possible. Normally, you should handle service requests by overriding the relevant doGet() or
doPost() method.
33. What happens if I call destroy() from init()?
A: The destroy() method is usually called by the servlet container immediately before it
takes a servlet out of service. It is typically used to clean-up any resource references, save
temporary data and suchlike. If the destroy() method is called from the init(ServletConfig)
method, whatever statements are contained in the method will be executed and the method
MYJAVAHUB.BLOGSPOT.COM
will return, it will not affect the lifecycle status of the servlet from the container's point of
view. If the init(ServletConfig) method returns without exception, the servlet container will
put the servlet into service regardless.
If an exception is thrown in your init(ServletConfig) method, it may be appropriate to use
the destroy() method to help handle the case. If so, you should still throw a ServletException
to ensure the servlet is not put into service in this state.
34. So if I call destroy() it won't kill the servlet?
A: The destroy() method is designed to be called by the servlet container as it takes the
servlet out of service and is intended to allow the servlet to save state and release any
resources it may be holding. The destroy() method does not stop the servlet, the statements it
contains are executed like any other method and there is no “special” behaviour triggered
beyond that. The servlet container is responsible for actually destroying the servlet.
In principle it can be safe to call the destroy() method from your servlet application, it
depends what statements are in the destroy() method. For clarity, it would be better to put
whatever statements you want to execute in a separate prepare() or reset() method. The
destroy() method could also call those methods as part of its shut-down behaviour.
35. Can I catch an exception and give my own error message?
A: Yes, you can catch servlet errors and give custom error pages for them, but if there are
exceptional conditions you can anticipate, it would be better for your application to address
these directly and try to avoid them in the first place.
… full answer hidden, click to get full answers
Premium members click below for full answer
Can I catch an exception and give my own error message?
36. How do I include files in my servlet?
A: To achieve an include scheme in a servlet, use javax.servlet.RequestDispatcher,
which takes the path of the target document in its constructor. A RequestDispatcher
can be obtained from the ServletContext object (via ServletConfig) in your servlet's init
method, or from ServletRequest or HttpServletRequest in doGet or doPost.
37. Can I call the doPost() method from a hyperlink?
A: Following a hyperlink in a Web document normally creates an HTTP GET request to the
given URL, not a POST request. Post requests are normally produced by the submission of
an HTML form whose method attribute is post. In this case any values given in the form's
input elements are passed as request parameters to the URL specified in the form's action
attribute.
… full answer hidden, click to get full answers
MYJAVAHUB.BLOGSPOT.COM
Premium members click below for full answer
Can I call the doPost() method from a hyperlink?
38. How can I display system properties in a servlet?
A: You can obtain the operating system, operating system version and Java version for a
servlet container through standard Java system properties. There is a wide range of standard
properties that can be obtained from the static System class method getProperty(String),
using the following keys:
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String javaVersion = System.getProperty("java.version");
These system properties are common to all Java runtime systems including servlets.
39. Should I use a static variable or Hashtable to store a list of strings?
A: The difficulty you are facing is that Web browsers see your servlet output as a single
HTTP response stream, which is either an HTML document or an image or some other
content item. It is not possible to encode the CAPTCHA image content inline into the
HTML markup, the HTML img element requires a reference to an image at a separate URL
source. The typical request sequence for a CAPTCHA form page would be:
Request CAPTCHA form page (servlet)
Download CAPTCHA form page HTML with image reference
Request CAPTCHA image (servlet)
Download CAPTCHA image as part of the main page load
Submit CAPTCHA form with image reference and human input (servlet)
Servlet checks CAPTCHA image content with human input and sends response
Download HTML success or error page output accordingly
It is critical the HTML page, form and image reference must not indicate the “decoded”
contents of the CAPTCHA image. But the servlet that checks the CAPTCHA must know the
decoded contents and the human input. To link the separate CAPTCHA form, image and
form submission requests, add a server-side session variable to carry the decoded value.
When the CAPTCHA image servlet generates the “encoded” text it should store the decoded
value in the session variable so the CAPTCHA check servlet can read the session and know
what the value should be.
40. How can I feed a CAPTCHA image into the servlet page output?
A: The static modifier for a variable is different from the object type of the variable. If you
want all servlet instances to be able to read and write data to a field, it should be static.
Depending on the nature of the application, it may also be necessary to synchronize access to
the variable.
MYJAVAHUB.BLOGSPOT.COM
If you want to store a simple list of strings, a java.util.List type variable would be most
appropriate. A Vector is a List type and its implementation is synchronized.
private static final List stringList = new Vector();
Using request information
41. How can I enable users to upload a file?
A: A file upload servlet should control what type of files are permitted, to process the byte
stream and decide where the content is stored. As you can imagine, allowing anybody to
upload any file to your Web server is a significant security hazard, so you must be very
careful to ensure that you restrict who has access, what they upload, and that the public do
not have arbitrary access to the file via the Internet.
The Apache commons file upload package would be a good place to start.
42. How do I limit the file upload size?
A: This example code is for the Apache commons file upload package.
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);
43. How do I get the uploaded file name?
A: As with many things to do with Java I/O, the commons file upload library treats HTTP
file upload as a byte stream, not necessarily as a file. The file upload API represents each
uploaded file as a FileItem object, but this is not related to a standard Java File object.
However, you can request a DiskFileItem subclass, which may physically store the uploaded
content as a temporary file on the server.
Each FileItem has a getName() method that returns the original file name on the user's file
system, and a write(File) method to store the contents via a standard Java File object.
MYJAVAHUB.BLOGSPOT.COM
Various factory configuration options let you set the maximum file size for the upload, the
temporary file directory and other settings, as in the profile avatar upload example below.
… full answer hidden, click to get full answers
Premium members click below for full answer
How do I get the uploaded file name?
44. How do I upload and process a file then email it?
A: The Java Mail API provides an interface with the Simple Mail Transport Protocol
(SMTP), POP3 and other email services and is included with the Apache Tomcat servlet
container and others. The Java Mail API enables you to develop sophisticated email enabled
applications, but it operates as a client or intermediary to existing system email services, not
as an email server in its own right.
45. Can I get the client IP and MAC address?
A: The ServletRequest type has a getRemoteAddr() method that returns the Internet Protocol
(IP) address of the client that made the request. The address is returned as a String, so must
be parsed further if you want to extract numeric references from it. In JSP you can access
this method it directly through the request variable, as below.
… full answer hidden, click to get full answers
Premium members click below for full answer
Can I get the client IP and MAC address?
46. How do I get the server port number for redirected requests?
A: If your servlet container is listening on port 8080 then the HttpServletRequest
getServerPort() method will return the int 8080.
Process parameters
47. How can I check what parameters are available in the request?
A: There are two main approaches to checking request parameters: either look up named
parameters you expect to be present, or iterate through all parameters. It is always possible
there is more than one value for each named parameter, so look up values using the
getParameterValues(String) method, which takes the name of the parameter as an argument
and returns a string array. You need to decide what should happen if there is more than one
value, this example takes the first value in the array.
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I check what parameters are available in the request?
MYJAVAHUB.BLOGSPOT.COM
48. How do I get parameter values from a form submission?
A: The simple form below invites people to input their name.
<form
action="http://www.codestyle.org/servlets/EchoRequest">
<input
type="text"
name="name" />
<input
type="submit" />
</form>
To handle this submission, extend HttpServlet and provide a doPost(HttpServletRequest,
HttpServletResponse) method, as below.
… full answer hidden, click to get full answers
Premium members click below for full answer
How do I get parameter values from a form submission?
49. The & in the parameter value truncates the string!
A: To pass non-ASCII characters in servlet parameters without them being interpreted as
part of the URL structure, you must encode the characters as hexadecimal (base 16) values
prefixed by the percent symbol, %. This is known as URL-encoding and is normally done
automatically by Web browsers when you submit a form. For instance, ampersand is ASCII
character number 38, which is %26 expressed as a hexadecimal. See the table below for
other conversion values.
… full answer hidden, click to get full answers
Premium members click below for full answer
The & in the parameter value truncates the string!
50. How can I tell which submit button was activated?
A: In design terms, it is not a good idea for your application to have different outcomes from
equivalent actions unless the consequences are quite clear to the person using the form. This
is especially important for people with impaired vision, or those using screen readers.
Nontheless, the example below shows how to markup your submit buttons to distinguish
which was activated.
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I tell which submit button was activated?
MYJAVAHUB.BLOGSPOT.COM
51. Which link was followed to request my servlet?
A: You should not rely upon the HTTP referer (sic) header to be sent to your servlet because
some Web browsers (and other client types) do not send them for privacy reasons.
… full answer hidden, click to get full answers
Premium members click below for full answer
Which link was followed to request my servlet?
Integration methods
52. How can I make the servlet output open in Microsoft Excel?
A: The binary file format of Microsoft Excel documents is extremely complex. If you want
to reproduce this format in detail and with precision you should read OpenOffice.org's
Documentation of the Microsoft Excel File Format.
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I make the servlet output open in Microsoft Excel?
53. How can I show my HTML markup as plain text?
A: To display HTML output in plain text format, you must set the HTTP Content-Type
header to text/plain, as below:
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I show my HTML markup as plain text?
54. How can I fix the Javascript in my servlet?
A: It can be very tricky inserting inline Javascript in servlet output because of the level of
quoted output escaping that can be necessary. If you miss or fail to correctly escape a literal
quote, your Javascript will not parse correctly. For simplicity, it would be preferable to use
an external Javascript file.
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I fix the Javascript in my servlet?
55. How do I include CSS in my servlet?
MYJAVAHUB.BLOGSPOT.COM
A: It is best to use an external style sheet reference, so that you can edit your servlet and
CSS rules independently.
… full answer hidden, click to get full answers
Premium members click below for full answer
How do I include CSS in my servlet?
56. How can I pass user input through my spelling checker?
A: create an instance of your SpellChecker class in the doGet() or doPost() method of your
servlet and pass the relevant parameter to it as a string, as in the code sample below ...
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I pass user input through my spelling checker?
57. How do I send data from an applet to a servlet?
A: The applet sandbox security environment only permits connections with the host from
which the applet was loaded. If you attempt a connection with a different host, the applet
will throw a SecurityException and fail. This can also cause problems when you are testing
an applet loaded from the local file system, which has no host.
full answer hidden, click to get full answers
58. What types of Servlet are there?
A: In the Java servlet API there are several sub-interfaces and implementations of the Servlet
interface. The GenericServlet class has general purpose implementations of servlet methods
that are common to all, including getInitParameter(String), init(ServletConfig) and
log(String). GenericServlet is abstract and leaves the key method service(ServletRequest,
ServletResponse) abstract for sub-class implementation.
… full answer hidden, click here for all answers
Premium members click below for full answer
What types of Servlet are there?
59. What is the class structure of servlets?
A: The class structure of servlets is fundamentally the same as any other Java class, however
they must fulfil the Servlet and GenericServlet interface. These interfaces define a set of so-
called lifecycle methods, a service method and various supporting methods for getting
servlet configuration parameters and for logging.
MYJAVAHUB.BLOGSPOT.COM
The lifecycle methods init(ServletConfig) and destroy() are called when the servlet container
first puts the servlet into service and ultimately removes it. The basic
service(ServletRequest, ServletResponse) method is called whenever a servlet request is
received by the servlet container.
… full answer hidden, click here for all answers
Premium members click below for full answer
What is the class structure of servlets?
60. Why is HttpServlet declared abstract?
A: The HttpServlet class is declared abstract because the default implementations of the
main service methods do nothing and must be overridden. This is a convenience
implementation of the Servlet interface, which means that developers do not need to
implement all service methods. If your servlet is required to handle doGet() requests for
example, there is no need to write a doPost() method too.
61. What's the problem if HttpServlet was concrete?
A: HttpServlet would be viable as a concrete class because it has no abstract methods, but it
would be pointless because the default implementations of the service methods doGet(),
doPost() etc. simply report that the relevant HTTP request methods are not supported. The
HttpServlet class is part of a public Application Programming Interface (API), so the
abstract modifier is a useful signal to programmers that the class has no practical use in itself
and is intended to be extended to create HTTP servlets. In this case the abstract modifier is a
design compromise that provides the default implementation of un-supported methods with a
minimal safeguard to suggest these methods should be overridden.
62. What's the difference between GenericServlet and HttpServlet?
A: The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP
protocol-specific methods. Java application developers normally extend the HttpServlet
because it implements all the HTTP features necessary to create a Web application.
The GenericServlet does not include protocol-specific methods for handling request
parameters, cookies, sessions and setting response headers. The HttpServlet subclass passes
generic service method requests to the relevant doGet() or doPost method. In principle, the
GenericServlet could be extended to implement other protocols, such as an FtpServlet for
example.
63. Who creates the servlet request object?
A: The servlet container creates an instance of the interface type HttpServletRequest to
represent the details of a single HTTP request, which is passed to a servlet's service method
MYJAVAHUB.BLOGSPOT.COM
(with an instance of HttpServletResponse). The implementation classes for the
HttpServletRequest and HttpServletResponse objects are provided by the servlet container
and may include proprietary code to support the vendor's overall container implementation.
From a programmer's point of view you should not need to concern yourself with the
vendor-specific features of these objects, only those provided by the servlet API.
64. Why are there separate ServletRequest and HttpServletRequest types?
A: ServletRequest and HttpServletRequest are interfaces, not a classes. Servlet containers
must provide their own implementations of these types, which are passed to servlets' doGet
and doPost methods.
… full answer hidden, click here for all answers
Premium members click below for full answer
Why are there separate ServletRequest and HttpServletRequest types?
65. What's the difference between a servlet session and a servlet context?
A: A servlet session is a very different thing from a servlet context. An HttpSession is a
mechanism used to simulate and maintain a continuous user session between a Web browser
and Web application, largely managed by the servlet container. The HTTP protocol is
stateless, it is essentially a request-response scheme, so servlet sessions are maintained by
passing a unique HTTP cookie value for each request, or by dynamically including an
identifier in servlet URLs, known as URL-rewriting.
A ServletContext object represents the overall configuration of the servlet container and has
several methods to get configuration parameters, exchange data amongst servlets, forward
requests and load resources. The servlet context is usually obtained indirectly through the
ServletConfig object, passed to a servlet's init(ServletConfig) method, or from the servlet
getServletConfig() method.
66. What's the use of the servlet wrapper classes?
A: The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed
to make it easy for developers to create custom implementations of the servlet request and
response types. The classes are constructed with the standard HttpServletRequest and
HttpServletResponse instances respectively and their default behaviour is to pass all method
calls directly to the underlying objects.
… full answer hidden, click here for all answers
Premium members click below for full answer
What's the use of the servlet wrapper classes?
67. What's the difference between getAttribute() and getParameter()?
MYJAVAHUB.BLOGSPOT.COM
A: The servlet request getParameter(String) method gets the value of the named request
parameter and returns it as a String. The most visible example of HTTP request parameters
are those you see appended to a search engine URL after you submit a query, e.g.
http://www.google.com/search?q=getParameter().
In this case a call to request.getParameter("q") would return the String getParameter().
This example shows the results of an HTTP GET request passed by an HTML form, the
parameter name q is the name of the text input field. Request parameters may also be
included in an HTTP POST submission too, but in this case they are not displayed as part of
the URL on the form action handler.
The servlet request getAttribute(String) method is used to retrieve Java Object properties
that may be added to the servlet request by the servlet container or Web application
developer. Developers can add Java objects to a request with the request.setAttribute(String,
Object) method. Attributes should be named like Java package names to ensure they don't
clash. Servlet request attributes are most often used with RequestDispatcher methods to pass
object references through the forward() and include() methods, as below.
… full answer hidden, click here for all answers
Premium members click below for full answer
What's the difference between getAttribute() and getParameter()?
68. I have overridden the service method, what next?
A: For most common servlet implementations you should not override the service method,
only the doGet or doPost methods. The servlet container provides its own abstract
implementation of the HttpServlet class and its service method forwards requests to the
doGet or doPost methods as appropriate.
69. HttpServletRequest is an interface, how do I get an instance?
A: The HttpServletRequest interface is implemented by the servlet container. The container
instantiates and passes servlet request and response objects to the servlet's service method,
which calls doGet or doPost in turn.
70. Which is faster, doPost() or doGet()?
A: Neither doPost() or doGet() methods are intrinsically faster than each other. The speed
with which a servlet container responds to such requests is partly a matter of how much data
is submitted with the request and the statements your servlet methods contain.
HTTP post forms are often designed to submit longer free-form text content, but this is not
necessarily the case. If any servlet request handler does a great deal of data retrieval,
MYJAVAHUB.BLOGSPOT.COM
network communication and processing it will take longer to execute, regardless of the
submission method.
71. What's the difference between doGet() and doPost()?
A: The doGet() and doPost() methods are designed to handle HTTP GET and POST type
requests respectively. When a GET request is submitted to a servlet container, it calls the
doGet method of the servlet that handles the request via the service method.
The doGet() and doPost() methods both take the same arguments and will handle the servlet
response in an equivalent manner, so for convenience a doPost() request can be passed to a
doGet() method and vice-versa. However, bear in mind several properties of the servlet
request object will be different for POST requests; it will not include a query string, and its
getMethod() method will return "post".
72. Must doPost() call doGet()?
A: There is no requirement for doGet() to call doPost() or vice versa. As a convenience some
servlets are set up so their doPost() method calls doGet() because they are intended to handle
GET and POST requests identically. If both methods called each other you would create an
endless loop that would quickly throw an exception.
73. Does the servlet request contain the source of the Web page?
A: The HttpServletRequest object contains all the key information for the HTTP request, not
the source of the requested Web resource. Normally, JSP pages are compiled into servlets
and processed automatically by the servlet container, so there is no need to write any
additional processor code yourself. If you need to dynamically configure the servlet
response, you should use JSP script elements or JSP tags in the body of the document and let
the servlet container handle the processing.
If you really want to process the source of a static HTML document or suchlike, you can use
the getResourceAsStream(String path) method of the ServletContext object to get an
InputStream of the file.
… full answer hidden, click here for all answers
Premium members click below for full answer
Does the servlet request contain the source of the Web page?
74. Why are there two different getRequestDispatcher() methods?
A: There is very little difference between the ServletContext and ServletRequest versions of
this method, the RequestDispatcher you get operates in exactly the same way. However, the
ServletRequest method also allows you to use a path argument that is relative to the
MYJAVAHUB.BLOGSPOT.COM
"current" resource, starting with "./Example.jsp" or "../Example.jsp". The ServletContext
getRequestDispatcher method should only be used for paths relative to the application root,
starting with "/Example.jsp".
It generally avoids ambiguity and possible confusion to use a path relative to the application
root.
75. Why do I get a compilation error with getRequestDispatcher(String)?
A: This error means the compiler does not recognise this method signature in the context
that you are calling it. The getRequestDispatcher method is not an HttpServlet method, it can
only be called on a ServletRequest, HttpServletRequest or ServletContext object. For
instance, you could use...
… full answer hidden, click here for all answers
Premium members click below for full answer
Why do I get a compilation error with getRequestDispatcher(String)?
76. What's the difference between the include() and forward() methods?
A: The RequestDispatcher include() method inserts the contents of the specified resource
directly in the flow of the servlet response, as if it were part of the calling servlet. If you
include a servlet or JSP document, the included resource must not attempt to change the
response status code or HTTP headers, any such request will be ignored. The include()
method is often used to include common "boilerplate" text or template markup that may be
included by many servlets.
The RequestDispatcher forward() method is used to show a different resource in place of the
servlet that was originally called. The forwarded resource may be another servlet, JSP or
static HTML document, but the response is issued under the same URL that was originally
requested. In other words, it is not the same as a redirection. The forward() method is often
used where a servlet is taking a controller role; processing some input and deciding the
outcome by returning a particular response page.
77. What is the use of sessions in servlets?
A: The servlet HttpSession interface is used to simulate the concept that a person's visit to a
Web site is one continuous series of interactions. This is often the case, but the HTTP
protocol is basically a request-response mechanism with no necessary connection between
one request and the next.
… full answer hidden, click to get full answers
Premium members click below for full answer
What is the use of sessions in servlets?
MYJAVAHUB.BLOGSPOT.COM
78. Are sessions created on the server side?
A: A servlet session is created and stored on the server side. The servlet container keeps
track of all the sessions it manages and fulfills servlet API requests to get HttpSessions,
manipulate object data stored with them and trigger event callbacks.
To the maintain the session, Web clients must pass back a valid session identifier as a cookie
header value or dynamically generated URL parameter. In this sense, the session is also
stored by the client, but only as a token reference.
79. Can I create a session with GenericServlet?
A: There are no protocol-specific features in GenericServlet, which is an implementation of
the basic, general purpose Servlet interface. Servlet-based sessions are designed only for
interactions using the HTTP protocol, which has two key features necessary for a servlet
container to simulate continuous user sessions: cookies and URL-based navigation, which
supports URL-rewriting. The servlet API therefore places the HttpSession interface in the
javax.servlet.http package, and session references are only available through classes in this
package.
80. How can I assemble data from multiple input forms?
A: First, it is best to use a single servlet to handle each form submission. A single servlet for
all input would be too complicated. Give each servlet responsibility to validate a single form
input, and pass the error cases on to JSP documents that explain the problem and allow users
to amend the input.
… full answer hidden, click to get full answers
Premium members click below for full answer
How can I assemble data from multiple input forms?
81. How do I clean up object references when a session ends?
A: In normal service conditions a servlet session may expire when the application user
exceeds the maximum inactive time interval for the session, or the application calls the
session's invalidate() method in response to a "log out" type request. In both cases, the
session ID reference is invalidated so any further requests for the session will return null,
then all the object references associated with the session are unbound and made available for
garbage collection (if no other references remain).
… full answer hidden, click to get full answers
Premium members click below for full answer
How do I clean up object references when a session ends?
82. How can I recover an expired session?
MYJAVAHUB.BLOGSPOT.COM
A: If a session has expired, it means a browser has made a new request that carries a session
identifier, such as a cookie entry, for which the servlet container has no record. Servlet
containers usually discard sessions after a standard time-out period, so they do not have to
maintain sessions indefinitely. If the session has expired on the server side, there is no way
to re-construct it, because no reference remains.
It is possible to request sessions live longer using the HttpSession
setMaxInactiveInterval(int) method. Many servlet containers also support persistent
sessions, which are stored between separate invocations of the container, but configuration
details vary.
83. How can I change the session ID of the page?
A: The servlet session represents a relationship between the servlet container and the end
user's browser over a number of request-response cycles, it is not bound to a particular page.
Generally, you should not attempt to change users' session ID values because it is very likely
to result in the loss of the session or with people acquiring other users' data. The session ID
value should be managed by the servlet container.
84. What are persistent cookies and pre-session cookies?
A: Cookies are relatively simple information stores that may be maintained by a Web
browser using data sent in the response header from a Web server. There is no obligation for
a Web browser to accept the cookie or maintain the information it is sent. Some people
disable cookies in their browser settings and you should design your application with this
possibility in mind.
… full answer hidden, click to get full answers
Premium members click below for full answer
What are persistent cookies and pre-session cookies?
85. How do I disable a cookie?
A: The storage of cookies is controlled by their maximum age property. A positive value
means the cookie should be stored for the given number of milliseconds from the present
time. A negative value means the cookie should not be stored and will expire when the
browser is shut down. To delete an existing cookie, call setMaxAge(0) before issuing the
servlet response. Use the code below to delete all cookies for the current site, for example:
… full answer hidden, click to get full answers
Premium members click below for full answer
How do I disable a cookie?
86. How can I pass values between JSPs without using sessions?
MYJAVAHUB.BLOGSPOT.COM
A: There are four main alternatives to full session-based transfer of data values, two of them
use features of the session tracking API: cookies and URL-rewriting, detailed below.
… full answer hidden, click to get full answers
87. My custom error page doesn't show!
A: There are many things that could be wrong with your configuration. What happens when
you force the error, which error page is issued? What does the error log tell you? Is the new
configuration being deployed properly, to replace the previous one?
Check the webapps directory for the deployed web.xml file. Does it include your custom
error configuration? Check the work directories under the Tomcat installation to see the
which compiled JSP servlets are present. Perhaps there is a compilation error with your
custom error page?
88. I get a servlet 404 error at /examples/WEB-INF/classes/HelloWorld!
A: It appears you have deployed your servlet to the correct location, but you have probably
not configured the servlet in the web.xml file for your application and you are requesting the
wrong URL for the servlet. You should add web.xml entries like those below, restart and
request the URL http://localhost:8080/examples/HelloWorld.
… full answer hidden, click for full answers
Premium members click below for full answer
I get a servlet 404 error at /examples/WEB-INF/classes/HelloWorld!
89. My servlet's if and else code is executed!
A: The code sample you have given is correct. Where you have the if / else conditions the
servlet should execute the contents of the relevant statement block, between the curly braces,
and not the other. It seems most likely that this working version of the controller servlet has
not successfully been deployed to the servlet container and you are actually testing an earlier
version of the servlet.
When you are working with servlets it helps to have a standard deployment process that
ensures that the latest version of your code is successfully compiled and deployed before you
test. Ideally you should write unit tests to check the logic of your application too. Apache
Ant is a Java build and deployment application that works with JUnit to test your application
code.
MYJAVAHUB.BLOGSPOT.COM
90. My servlet cannot locate my XSLT file!
A: On Windows systems, the path to files referenced in servlet classes should be given in
full, including the drive letter and the path separator backslashes escaped.
… full answer hidden, click for full answers
Premium members click below for full answer
My servlet cannot locate my XSLT file!
91. The getRemoteUser method returns null after basic authentication!
A: Basic authentication details are carried in the HTTP headers that a browser passes to the
servlet container when it makes a request. When the browser makes an initial request, it does
not include an Authorization header, so the first servlet request.getRemoteUser() method
returns null.
Your servlet must trigger the process by which the browser prompts for the login. The
browser will then issue a second HTTP request with an Authorization header that carries the
login details.
… full answer hidden, click for full answers
Premium members click below for full answer
The getRemoteUser method returns null after basic authentication!
92. I get "cannot find symbol" with getWrite()!
A: The HttpServletResponse class method for getting a PrintWriter is called getWriter(), not
getWrite(), and may throw an IOException. The method may also throw the runtime
exception UnsupportedEncodingException if the character set specified by the
setContentType() method is not supported, and IllegalStateException if the
getOutputStream() method has already been called.
93. I get "cannot override doGet()" throwing an Exception!
A: This compiler error means that your method throws an exception that is not declared by
the superclass method it is intended to override. The servlet doGet() method may throw a
ServletException, an IOException or any subclass of those types. Since Exception is a
superclass of the declared exceptions, it is not permitted.
If your doGet() method includes calls that may throw undeclared exceptions you should
catch those exceptions and handle them. For example, you may report the problem in the
servlet output, fall back to a simpler output or fixed error response, or throw a new
ServletException with the details of the primary exception. If the exception originates from
invalid servlet input, you may choose to send an HTTP 400, bad request, error response.
94. Could compiling a package cause an internal server error?
MYJAVAHUB.BLOGSPOT.COM
A: Possibly, but compiling a package wouldn't normally cause a 500 error directly. If you
attempted to compile a servlet or a utility class on the host machine and the classpath
environment setting was not configured properly, the classes would just fail to compile.
… full answer hidden, click for full answers
Premium members click below for full answer
Could compiling a package cause an internal server error?
95. I get "HTTP GET method is not in use"!
A: The servlet you are referring to has not implemented the doGet(HttpServletRequest,
HttpServletResponse) method, which is required to handle the type of requests made by
typing the address into a Web browser. It is possible the servlet has been designed to handle
HTTPpost requests from HTML form submissions only. In this case, you would have to
create a form whose action attribute is the servlet URL with the method attribute post, as
below.
… full answer hidden, click for full answers
Premium members click below for full answer
I get "HTTP GET method is not in use"!
96. What does this servlet stack trace mean: IndexOutOfBoundsException... ?
A: The answer to the question is in the first line of the stack trace. The interpreter attempted
to get the array list item at index 4, but the size of the array list was zero. Whatever code was
supposed to fill the list has not done so. To guard against this case, you should add a check
for the size of the array before you reference an item at a specific index. This may be a
symptom of concurrent modification of the array list by a separate thread.
97. My file throws an AccessControlException!
A: The AccessControlException explains the problem without having to look any code
extracts. The user profile that the servlet container is using does not have permission to
access this file. Modify the permissions on the file to allow read access by the servlet
container user if one exists. Otherwise, there may be a security policy for your servlet
container that restricts the rights your applications have to access the file system. Check your
servlet container documentation and adjust the configuration as necessary. The container
may be configured with strict security policy by default.
98. I get "Error allocating a servlet instance"!
A: It is difficult to solve Java servlet errors without more detailed diagnostic information but
the most likely reason for this error is a class definition not found. In other words, your
servlet class or one of the classes required by your servlet was not found by the servlet
container when it tried to bring the servlet into service.
MYJAVAHUB.BLOGSPOT.COM
The most likely solution is to re-compile your servlet and associated classes and re-deploy
them to your servlet container. If you use third party libraries with your servlet, make sure
they are deployed to the appropriate Web application directory or common container library
directory. You may need to stop and re-start your servlet container.
A build tool like Apache Ant can help ensure that you do not miss vital steps in the
compilation and deployment of your Web application.
99. I get an IllegalStateException with my forward() call!
A: The RequestDispatcher forward() method call will effectively end the servlet response
because the response stream will be committed in the process, but the controller servlet will
continue to execute any remaining statements in its doGet() or doPost() method. This can be
useful if you want to log status or store data after the response has been handled for example,
but if those statements attempt to make further calls on the servlet response it will throw an
IllegalStateException. For this reason it is best to handle forwarding logic with exclusive if /
else blocks, to be sure only one response is attempted.
100. Internet Explorer does not show my custom 500 error page!
A: The problem is with your browser, not your servlet container. Internet Explorer shows
what it regards as "friendly" error messages when it receives HTTP error codes such as 500,
404, etc. This is a problem because it may obscure any genuinely helpful error messages you
try to present to the user.
… full answer hidden, click for full answers
Premium members click below for full answer
Internet Explorer does not show my custom 500 error page!
101. My 500 error is java.lang.Exception!
A: It is very difficult to tell from this information alone what the problem is. The
java.lang.Exception class is the superclass of all exceptions, so we cannot tell whether it is a
runtime exception or checked exception thrown by your application. You should put
debugging log output in your servlet to find the point at which the exception is thrown. Use
the servlet method log(String) or log(String, Throwable).
If you have overridden the init(ServletConfig config) method, you must call
super.init(config) in the first line of the method to enable these log methods.
102. This government Web site throws a servlet error, what can I do?
A: Web server errors caused by Java servlets are the responsibility of the Web site owner
and you should alert them to the problem. Server errors can be caused by temporary
MYJAVAHUB.BLOGSPOT.COM
problems with a Web server or there may be fundamental programming errors that are only
seen in certain circumstances. It is possible that those problem circumstances include
unexpected differences in the way your Web browser works or your computer is set up.
Most Web site managers would welcome the opportunity to make a correction if you can
provide information about the browser you use and what happened immediately before the
error.
One possibility is that your Web browser has an exceptionally long "user agent", a software
code name that is a hidden part of your browser's Web page requests. Your browser's code
name is 2063 characters long, which may be more than the servlet expects. Use the Code
Style EchoRequest servlet to see the user-agent for yourself. Try the problem page with a
different Web browser to see if you can isolate the problem.
103. Why does my servlet give a 404 error?
A: There are many reasons why a servlet container may issue an HTTP 404 error for a
servlet. You should check you have added a servlet configuration and mapping to your
web.xml file and make sure you are requesting the URL path specified in the mapping.
If your servlet compiles successfully, another possibility is that it throws a ServletException
in the init(ServletConfig) method. If so, the servlet container will log the exception and take
the servlet out of service. Check your log files for any details.
104. What does HTTP status 405, method not supported mean?
A: The HTTP 405 status, "Method not supported", means that the submitted request method
is not implemented by the servlet that handled the response. For example, a servlet may only
have a doGet() method, not doPost(), and therefore be unable to issue an HTML document
for the response body. In other words, the response means you can't make that kind of
request for this servlet.
One common technique to easily enable a servlet to support POST requests is for the
doPost() method to call the doGet() method, though some the HttpServletRequest object
properties will vary from a normal GET request.
105. Are servlets multi-threaded?
A: Yes, servlets are normally multi-threaded. The servlet container allocates a thread for
each new request for a single servlet without any special programming. Each request thread
for your servlet runs as if a single user were accessing it alone, but you can use static
variables to store and present information that is common to all threads, like a hit counter for
instance.
106. What is a service thread and how do I create one?
A: The most common use of service threads are those used by a servlet container to handle
the HTTP request-response process with a Java servlet. Servlet containers use an
MYJAVAHUB.BLOGSPOT.COM
independent thread of execution so they can process many concurrent requests to many
servlets and manage the overall performance of the server. Servlet requests are handled
through the service() method, so they are named service threads, but other Java applications
may use a similar service scheme.
Servlet containers automatically create or obtain service threads from a thread pool when a
new HTTP request is received, so they do not need to be created explicitly in your servlet
code.
107. How does the container handle concurrent requests?
A: Servlet containers usually manage concurrent requests by creating a new Java thread for
each request. The new thread is given an object reference to the requested servlet, which
issues the response through the same thread. This is why it is important to design for
concurrency when you write a servlet, because multiple requests may be handled by the
same servlet instance.
108. Are you saying there is only one servlet instance for all requests?
A: The way that servlet containers handle servlet requests is not prescribed to this extent;
they may use a single servlet, they may use servlet pooling, it depends on the vendor's
system architecture. New threads are not necessarily created for every servlet request but
may be recycled through a worker thread pool for efficiency. The point is that you should
write your servlet code to take account of a multi-threaded context regardless of the
container implementation you happen to be using. In other words, you should adhere to the
principle of write once, run anywhere.
109. Are servlet requests handled first come, first served?
A: The use of a single servlet to handle multiple requests is usually done with Java threads.
For each HTTP request the servlet container assigns a worker thread in which to execute the
servlet code and a reference to the relevant servlet instance to call its service methods. The
priority order by which the service threads are acquired and process the request depends on
the detailed implementation of the servlet container. The natural principle is that it should be
first come first served, but the actual execution sequence also depends on the thread
scheduling scheme in the Java virtual machine.
Servlet containers normally limit the number of service threads that can be run concurrently,
so pending requests are typically added to a queue.
Once a service thread is assigned to a request, the sequence in which the thread is executed
depends on the thread scheduling system of the Java Runtime Environment (JRE). Threads
can enter complex stop, start sequences in contention with other service threads, which is
why your servlet code needs to be thread safe.
110. What is the single threaded model?
MYJAVAHUB.BLOGSPOT.COM
A: Standard servlets are normally handled in a multi-threaded context in the servlet
container. A number of virtually simultaneous requests for a single servlet could be handled
by different threads using the same servlet instance. Any number of threads could access or
modify the static and instance fields of a single servlet instance in an unpredictable
sequence. This makes the instance fields of servlets as vulnerable to threading issues as
static fields, and modification of shared resources must be considered carefully.
If your servlet implements the SingleThreadModel interface, it gets a guarantee from the
servlet container that any single instance of the servlet will only be accessed by one thread at
a time. The container either synchronizes access to the servlet's service() method, or uses a
single instance of the servlet drawn from a pool.
The single threaded model adds a performance overhead to locking or managing servlet
instances, so should not be used lightly. Generally, it is best to ensure synchronized access to
servlet resources in your application code.
111. Why use SingleThreadedModel if servlets are multi-threaded?
A: The SingleThreadedModel interface is used to ensure the safety of servlets that are
vulnerable to thread safety issues. Normally, servlets should be written to run safely in a
multi-threaded environment, and are executed in this context. The SingleThreadedModel is a
way to override the normal multi-threaded execution context of the servlet container.
112. How do I implement the single threaded model?
A: To create a servlet that a container will manage on a single threaded basis it must declare
that it implements the javax.servlet.SingleThreadModel interface. This is a marker interface,
there are no extra methods to fulfil, but this is sufficient for the container to identify the type
and manage it accordingly.
Public class SingleThreadServlet extends HttpServlet
implements SingleThreadModel {
// Standard HTTP servlet methods
}
The servlet container will typically synchronize access to a single instance of the servlet, or
create a pool of servlet instances and allocate one request per instance.
113. Should I use the SingleThreadedModel?
A: Not unless you have very good reason. The SingleThreadedModel interface has been
deprecated, which means that it should not be used and may be removed in a later release of
the Java servlet specification and Application Programming Interface (API). It has never
MYJAVAHUB.BLOGSPOT.COM
really been advisable to implement the SingleThreadedModel, you should always aim to
address thread safety issues in servlets using standard Java programming techniques.
114. How can I invoke servlet pooling with SingleThreadedModel?
A: The SingleThreadedModel servlet specification does not require the creation of a pool of
servlets. A single threaded model implementation may also synchronize access to a single
servlet instance to achieve the same outcome, so that only one request is processed at a time.
Apache Tomcat uses the synchronized approach, other servlet containers may use the pooled
approach.
If you are concerned about the performance impact of synchronized access to the servlet
instance, it would be preferable to re-design your servlet so that it does not depend on this
mechanism at all. For example, you might create a synchronized block around the statements
that are vulnerable to threading issues. By doing away with the single threaded model, you
will minimise the performance impact of thread control.
115. Can my servlet control the number of threads it accepts?
A: Your servlet should be designed to be thread safe and not to anticipate any limit to the
number of concurrent requests it will receive. You should configure the number of
concurrent requests to accept in your servlet container configuration. In Apache Tomcat this
property is set in the server.xml file's Connector element, as below.
<Connector
className="org.apache.catalina.connector.http.HttpConnector"
minProcessors="3"
maxProcessors="20"
acceptCount="10"/>
The acceptCount attribute sets the number of requests that can be queued waiting to be
handled.
The minProcessors attribute sets the number of request processors that are created when the
servlet container starts up.
The maxProcessors attribute sets the total number of request processors or that can be used
to handle requests.