| Home > Advance
Java FAQ
> Servlets FAQ |
| Servlets |
| |
|
Q .
What are servlets?
|
Ans :
Servlets are server-side Java applications, as opposed to client-side applets or standalone
applications. While servlets are compatible with many different types of servers, typically they are
used in web servers, as a replacement for CGI scripts or Active-Server Pages (ASP).
Java servlets offer many advantages over other forms of server-side processing. Apart from the obvious
(they are written in the Java programming language, a big plus after all), servlet based applications
are far easier to write than CGI scripts. There's no need to write code for parsing HTTP request
parameters, as this code is provided by the javax.servlet.http package. You have access to the entire
Java API, with no networking restrictions (making servlets far more attractive than applets). There
are also performance increases over CGI scripts, as servlets persist over time, and do not create a
new process for every connection.
|
|
Q . What do I need to develop servlets?
|
Ans
:
To develop servlets, you need a basic familiarity with Java I/O streams, HTML, and the
HyperText-Transfer Protocol (HTTP). You'll also need to download the Java Servlet Development Kit
(JSDK) which is freely available from Sun Microsystems. Finally, you'll need a web-server that
supports servlets, or a servlet engine which augments your server's capability.
|
|
Q .
Where can I get more information on servlets?
|
Ans
:
Gamelan's TechFocus recently published a two-part introductory tutorial on servlets, which I can
highly recommend. For more information see http://www.gamelan.com/journal/techworkshop/
|
|
Q .
How does servlet performance compare to applets?
|
Ans
:
Client-side Java has been dogged by performance problems due to slow loading times, older JVMs without
JIT compilation, and inefficient coding. Applets have gained a reputation of poor performance, which
often gives Java itself a bad name. Server-side Java, however, doesn't suffer from the same
performance problems. The speed of execution is much better, as the server administrator can install
more recent JVMs (some of which are optimized for server-side processing). The load time is virtually
instantaneous, as there is no network latency to contend with. You're also in a better position
regarding security restrictions - servlets can establish network connections without the sandbox
problems that plague unsigned applets.
|
|
Q . How does servlet performance compare to CGI?
|
Ans
:
Servlet performance is often far superior to CGI. Rather than forking a new process for each request,
a pool of threads can be used to execute servlet requests. Servlets persist across connections, so
there's no need to perform initialization tasks repeatedly. This, when coupled with a fast JVM and
servlet engine, can offer better performance than CGI.
|
|
Q . Should I use single-threaded, or multi-threaded servlets?
|
Ans :
By default, servlets are multi-threaded. If you specifically require a single-threaded servlet, you
should implement the javax.servlet.SingleThreadModel interface. This guarantees that no two threads
will be operating on the same instance of the servlet, but still allows concurrent execution of the
servlet. The servlet engine will maintain a pool of available threads, and create new instances of the
servlet as required. This can cause performance problems however, and should be used sparingly except
on low-traffic servers.
|
|
Q . How do I send cookies from a servlet?
|
Ans
:
HTTP is a stateless protocol, which makes tracking user actions difficult. One solution is to use a
cookie, which is a small piece of data sent by a web browser every time it requests a page from a
particular site. Servlets, and CGI scripts, can send cookies when a HTTP request is made - though as
always, there is no guarantee the browser will accept it.
Cookies are represented by the javax.servlet.http.Cookie class. Cookie has a single constructor, which
takes two strings (a key and a value).
// Create a new cookie
Cookie cookie = new Cookie ("counter", "1");
Adding a cookie to a browser is easy. Cookies are sent as part of a HTTPServletResponse, using the
addCookie( Cookie ) method. You can call this method multiple times, but remember that most browsers
impose a limit of ten cookies, and 4096 bytes of data per hostname.
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException
{
response.addCookie(new
Cookie("cookie_name", "cookie_value"));
}
|
|
Q . How do I read browser cookies from a servlet?
|
Ans
:
Reading cookies from a servlet is quite easy. You can gain access to any cookies sent by the browser
from the javax.servlet.http.HttpServletRequest passed to the servlet's doGet, doPost, etc methods.
HttpServletResponse offers a method, Cookies[] getCookies() which returns an array of Cookie objects.
However, if no cookies are available, this value may be null, so be sure to check before accessing any
array elements.
// Check for cookies
Cookie[] cookie_jar = request.getCookies();
// Check to see if any cookies exists
if (cookie_jar != null)
{
for (int i =0; i< cookies.length; i++)
{
Cookie aCookie = cookie_jar[i];
pout.println ("Name : " + aCookie.getName());
pout.println ("Value: " + aCookie.getValue());
}
}
|
|
Q .
How do I make cookies expire after a set time period?
|
Ans
:
Depending on how you use the data stored in a cookie, it is sometimes a good idea to make the cookie
expire. Since anyone using the browser will have the cookie sent on their behalf, it may appear to be
a legitimate user when in actual fact it is not. This often happens in places like Internet cafes,
school or university computing labs, or libraries. If your cookie sends a user identifier that
facilitates access to sensitive data, or allows changes to be made (for example, a web-based email
service), then you should expire cookies after a small time period. If the user keeps using your
servlet, you always have the option of resending the cookie with a longer duration.
To specify an expiration time, you can use the setMaxTime(int) method of javax.servlet.http.Cookie. It
takes as a parameter the number of seconds before the cookie will expire. For example, for a five
minute expiration, we would do the following :-
// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());
// Expire the cookie in five minutes (5 * 60)
cookie.setMaxTime( 300 );
When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only
be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a
negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits. Note
however that not everyone will shutdown their browser, and it might be available for minutes, hours
even days. Finally, specifying a value of zero will expire the cookie instantly.
|
|
Q .
Why aren't cookies stored by my servlets accessible to my CGI scripts or ASP pages?
|
Ans
:
By default, cookies are accessible to every HTTP request for the current directory, and any
subdirectories. Now on most web servers and servlet engines, servlets are located in a special
directory. For example, when using servletrunner (which ships with the Java Servlet Development Kit),
servlets must be invoked under the /servlet/ directory.
http://webserver/servlet/servletname
If you want your cookies to be accessible elsewhere, you must specify the root path of your webserver,
using the javax.servlet.Cookie.setPath( String ) method.
// Create a cookie for everyone to share
Cookie myCookie = new Cookie ("counter", "1");
// Set path for cookie
myCookie.setPath( "/" );
Once you've set the path, any script (for example, stored in /cgi-bin/) can access the cookies stored
by your servlets.
|
|
Q . How can I void a cookie, and delete it from the browser?
|
Ans
:
You can specify an expiration date, using the setMaxTime(int) method of javax.servlet.http.Cookie.
Specifying a expiration time of zero will void the cookie, and delete it from the browser.
// Expire the cookie immediately
cookie.setMaxTime( 0 );
// Send cookie back to the browser to void it
response.addCookie(cookie);
|
|
Q . Can I use servlet for file access from remote servers ?
-- asked by
Sheetal
|
Ans
:
Yes you can use, but in remote system one process has to run to listen to servlet requests.
|
|
|
|