You are on page 1of 15

Running Servlet

Six Steps to Running Your First Servlet


Once Tomcat is installed and configured, you can put it to work. Six steps take you from writing
your servlet to running it. These steps are as follows:
1. Create a directory structure under Tomcat for your application.
2. Write the servlet source code. You need to import the javax.servlet package and the
javax.servlet.http package in your source file.
3. Compile your source code.
4. Create a deployment descriptor. public void doGet(HttpServletRequest
request,
5. Run Tomcat
6. Call Your servlet from a web broswer.

Step 1: Create a Directory Structure under Tomcat


When you install Tomcat, several subdirectories are automatically created under the Tomcat home
directory (%TOMCAT_HOME%). One of the subdirectories is webapps. The webapps directory is
where you store your web applications. A web application is a collection of servlets and other
contents installed under a specific subset of the server's URL namespace. A separate directory is
dedicated for each servlet application. Therefore, the first thing to do when you build a servlet
application is create an application directory. This section explains how to create a directory
structure for an application called myApp.
1. Create a directory called myApp under the webapps directory. The directory name is
important because this also appears in the URL to your servlet.
2. Create the src and WEB-INF directories under myApp, and create a directory named classes
under WEB-INF. The directory structure is shown in Figure 1.4. The src directory is for your
source files, and the classes directory under WEB-INF is for your Java classes. If you have
html files, you put them directly in the myApp directory. You also may want to create a
directory called images under myApp for all your image files.
Note that the admin, ROOT, and examples directories are for applications created automatically
when you install Tomcat.
Figure 1.4 Tomcat application directory structure.

Step 2: Write the Servlet Source Code


In this step, you prepare your source code. You can write the source code yourself using your
favorite text editor or copy it from the CD included with the book.
The code in Listing 1.1 shows a simple servlet called TestingServlet. The file, named
TestingServlet.java, sends to the browser a few HTML tags and some text. For now, don't worry if
you haven't got a clue about how it works.
Listing 1—TestingServlet.java
iimport javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class TestingServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome to the Servlet Testing Center");
out.println("</BODY>");
out.println("</HTML>");
}
}

Now, save your TestingServlet.java file to the src subdirectory under myApp. You actually can
place the source files anywhere; however, it is always a good idea to be organized by storing all
your source code files in the src directory.

Step 3: Compile Your Source Code


For your servlet source code to compile, you need to include in your CLASSPATH environment
variable the path to the servlet.jar file. The servlet.jar is located in the common\lib\ subdirectory
under %CATALINA_HOME%.
NOTE
If you have forgotten how to edit the CLASSPATH environment variable, refer to Appendix A,
"Tomcat Installation and Configuration."
If you are using Windows, remember that the new environment variable takes effect only for new
console windows. In other words, after changing a new environment variable, open a new console
window for typing your command lines.
Now, change directory to your working directory and type the following if you are using Windows:
javac -d ..\WEB-INF\classes\ TestingServlet.java

If you are using Linux/UNIX, the command is very similar, except that / is used to separate a
directory from a subdirectory.
javac -d ../WEB-INF/classes/ TestingServlet.java

The -d option specifies where to place the generated class files. The command also assumes that
you have placed the JDK's bin directory in the path so you can call any program in it from any
directory.
Step 4: Create the Deployment Descriptor
A deployment descriptor is an optional component in a servlet application, taking the form of an
XML document called web.xml. The descriptor must be located in the WEB-INF directory of the
servlet application. When present, the deployment descriptor contains configuration settings
specific to that application. Deployment descriptors are discussed in detail in Chapter 16.
"Application Deployment."
For this step, you now need to create a web.xml file and place it under the WEB-INF directory
under myApp.
The web.xml for this example application must have the following content.<?xml version="1.0"
encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
</web-app>

The web.xml file has one element: web-app. You should write all your servlets under <web-app>.
For each servlet, you have a <servlet> element and you need the <servlet-name> and <servlet-
class> elements. The <servlet-name> is the name for your servlet, by which it is known to Tomcat.
The <servlet-class> is the compiled file of your servlet without the .class extension.
Having more than one servlet in an application is common. For every servlet, you need a <servlet>
element in the web.xml file. For example, the following code shows how the web.xml looks if you
add another servlet called Login.
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
</web-app>

Step 5: Run Tomcat

If it is not already running, you need to start Tomcat. For information on how to do that, see
Appendix A, "Tomcat Installation and Configuration."
Step 6: Call Your Servlet from a Web Browser
You are ready to call your servlet from a web browser. By default, Tomcat runs on port 8080 in
myApp virtual directory under the servlet subdirectory. The servlet that you just wrote is named
Testing. The URL for that servlet has the following format:
http://domain-name/virtual-directory/servlet/servlet-name

If you run the web browser from the same computer as Tomcat, you can replace domain-name with
localhost. Therefore, the URL for your servlet would be
http://localhost:8080/myApp/servlet/Testing.

In the deployment descriptor you wrote in Step 4, you actually mapped the servlet class file called
TestingServlet with the name "Testing" so that your servlet can be called by specifying its class file
(TestingServlet) or its name (Testing). Without a deployment descriptor, your servlet must be called
by specifying its class name; that is, TestingServlet. This means that if you had not written a
deployment descriptor in Step 4, you would have to use the following URL to call your servlet:

http://localhost:8080/myApp/servlet/TestingServlet
Servlets - Debugging

It is always difficult to testing/debugging a servlets. Servlets tend to involve a large amount of


client/server interaction, making errors likely but hard to reproduce.

Here are a few hints and suggestions that may aid you in your debugging.

System.out.println()
System.out.println() is easy to use as a marker to test whether a certain piece of code is being
executed or not. We can print out variable values as well. Additionally −
 Since the System object is part of the core Java objects, it can be used everywhere without
the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans
and classes, and standalone applications.
 Stopping at breakpoints technique stops the normal execution hence takes more time.
Whereas writing to System.out doesn't interfere much with the normal execution flow of the
application, which makes it very valuable when timing is crucial.
Following is the syntax to use System.out.println() −

System.out.println("Debugging message");

All the messages generated by above syntax would be logged in web server log file.

Message Logging
It is always great idea to use proper logging method to log all the debug, warning and error
messages using a standard logging method. I use log4J to log all the messages.
The Servlet API also provides a simple way of outputting information by using the log() method as
follows −

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ContextLog extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {

String par = request.getParameter("par1");

//Call the two ServletContext.log methods


ServletContext context = getServletContext( );

if (par == null || par.equals(""))


//log version with Throwable parameter
context.log("No message received:", new IllegalStateException("Missing
parameter"));
else
context.log("Here is the visitor's message: " + par);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
String title = "Context Log";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\
n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">Messages sent</h2>\n" +
"</body>
</html>"
);
} //doGet
}

The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs
are found in <Tomcat-installation-directory>/logs.
The log files do give an indication of new emerging bugs or the frequency of problems. For that
reason it's good to use the log() function in the catch clause of exceptions which should normally
not occur.

Using JDB Debugger


You can debug servlets with the same jdb commands you use to debug an applet or an application.
To debug a servlet, we debug sun.servlet.http.HttpServer and carefully watch as HttpServer
executes servlets in response to HTTP requests made from browser. This is very similar to how
applets are debugged. The difference is that with applets, the actual program being debugged is
sun.applet.AppletViewer.
Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the
same for servlets, you have to help your debugger by doing the following −
 Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated
classes.
 Set your debugger's classpath so that it can also find your servlets and support classes,
typically server_root/servlets and server_root/classes.
You normally wouldn't want server_root/servlets in your classpath because it disables servlet
reloading. This inclusion, however, is useful for debugging. It allows your debugger to set
breakpoints in a servlet before the custom servlet loader in HttpServer loads the servlet.
Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set
breakpoints in whatever servlet you're interested in debugging, then use a web browser to make a
request to the HttpServer for the given servlet (http://localhost:8080/servlet/ServletToDebug). You
should see execution being stopped at your breakpoints.
Using Comments
Comments in your code can help the debugging process in various ways. Comments can be used in
lots of other ways in the debugging process.
The Servlet uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be
used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the
code you just commented and find out the problem.

Client and Server Headers


Sometimes when a servlet doesn't behave as expected, it's useful to look at the raw HTTP request
and response. If you're familiar with the structure of HTTP, you can read the request and response
and see exactly what exactly is going with those headers.

Important Debugging Tips


Here is a list of some more debugging tips on servlet debugging −
 Remember that server_root/classes doesn't reload and that server_root/servlets probably
does.
 Ask a browser to show the raw content of the page it is displaying. This can help identify
formatting problems. It's usually an option under the View menu.
 Make sure the browser isn't caching a previous request's output by forcing a full reload of
the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-
Refresh.
 Verify that your servlet's init() method takes a ServletConfig parameter and calls
super.init(config) right away.

Thread-Safe Servlet
In the context of servlets, thread safety refers to the ability of a servlet to properly handle concurrent
requests from multiple threads without encountering data corruption or inconsistency issues.
Servlets in Java are multithreaded by nature, as they can handle multiple requests simultaneously.
Therefore, it's crucial to ensure that servlets are thread-safe to maintain the integrity of data and
prevent race conditions.
Here are some key points to consider for achieving thread safety in servlets:
1. Instance Variables and Shared Resources:
 Avoid using instance variables to store request-specific information unless they are
thread-safe or properly synchronized.
 If a servlet uses shared resources, such as a database connection or an external
service, make sure access to these resources is synchronized to prevent conflicts.
2. Local Variables:
 Prefer using local variables within methods rather than instance variables when
dealing with request-specific data. Local variables are inherently thread-safe since
they are confined to the scope of a single method invocation.
3. Synchronization:
 If multiple threads can access and modify shared resources, use synchronization to
control access and update operations. You can use the synchronized keyword on
methods or blocks of code to ensure only one thread can execute the synchronized
portion at a time.
public synchronized void doPost(HttpServletRequest request, HttpServletResponse response) {

// Thread-safe code here

4. Thread-Local Variables:

 Consider using thread-local variables for data that is specific to a particular thread.
Thread-local variables ensure that each thread has its own copy of the data,
eliminating the need for synchronization.
private static ThreadLocal<SomeObject> threadLocalData = new ThreadLocal<>();
5. Immutable Objects:
 Whenever possible, use immutable objects. Immutable objects cannot be modified
once they are created, making them inherently thread-safe.
6. Avoiding Singletons:
 Be cautious when using singleton patterns in servlets, especially if the singleton
holds state. If a singleton is shared among multiple threads, ensure that its methods
are thread-safe or use synchronization.
Remember that servlet containers, such as Apache Tomcat, manage the lifecycle and threading of
servlets. However, it's the responsibility of the servlet developer to ensure that the servlet code is
thread-safe, as the container can instantiate multiple instances of a servlet to handle concurrent
requests.

Cookies
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is
sent by the user, cookie is added with request by default. Thus, we recognize the user as the old
user.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.

Constructor of Cookie class


Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class


There are given some commonly used methods of the Cookie class.

Method Description
public void setMaxAge(int
Sets the maximum age of the cookie in seconds.
expiry)
Returns the name of the cookie. The name cannot be changed after
public String getName()
creation.
public String getValue() Returns the value of the cookie.
public void setName(String
changes the name of the cookie.
name)
public void setValue(String
changes the value of the cookie.
value)

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to


add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.

How to create Cookie?


Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
}

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing it in another
servlet. As we know well that session corresponds to the particular user. So if you access it from too
many browsers with different values, you will get the different value.
index.html
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }

SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }

web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
HTTP Redirects
HTTP redirects in servlets are a mechanism by which a servlet can instruct the client's browser to
navigate to a different URL. This is often used for various purposes, such as handling form
submissions, authentication, or directing users to a different part of a web application. The
HttpServletResponse class provides a method called sendRedirect() for achieving this.

Here's a simple example of how you can use HTTP redirects in a servlet:

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RedirectServlet")
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Specify the URL to which you want to redirect
String redirectURL = "https://www.example.com";

// Perform the redirect using HttpServletResponse.sendRedirect()


response.sendRedirect(redirectURL);
}
}
HTTP redirects in servlets are a mechanism by which a servlet can instruct the client's browser to
navigate to a different URL. This is often used for various purposes, such as handling form
submissions, authentication, or directing users to a different part of a web application. The
HttpServletResponse class provides a method called sendRedirect() for achieving this.

Here's a simple example of how you can use HTTP redirects in a servlet:
java

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RedirectServlet")
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Specify the URL to which you want to redirect
String redirectURL = "https://www.example.com";

// Perform the redirect using HttpServletResponse.sendRedirect()


response.sendRedirect(redirectURL);
}
}

In this example:
1. The servlet is mapped to the URL pattern "/RedirectServlet" using the @WebServlet
annotation.
2. In the doGet method, the sendRedirect() method of the HttpServletResponse
object is called with the target URL ("https://www.example.com" in this case).
When the client's browser receives this response, it will automatically make a new request to the
specified URL, and the user will be redirected to that location.
It's important to note that after calling sendRedirect(), the current response is considered
complete, and no further processing should be done in the servlet. The browser will handle the
redirection, and any code after the sendRedirect() call will not be executed.

Additionally, you can use relative URLs for redirection within the same web application:
String relativeURL = "/anotherPage.jsp";
response.sendRedirect(request.getContextPath() + relativeURL);
HTTP redirects in servlets are a mechanism by which a servlet can instruct the client's browser to
navigate to a different URL. This is often used for various purposes, such as handling form
submissions, authentication, or directing users to a different part of a web application. The
HttpServletResponse class provides a method called sendRedirect() for achieving this.

Here's a simple example of how you can use HTTP redirects in a servlet:
java
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RedirectServlet")
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Specify the URL to which you want to redirect
String redirectURL = "https://www.example.com";

// Perform the redirect using HttpServletResponse.sendRedirect()


response.sendRedirect(redirectURL);
}
}

In this example:
1. The servlet is mapped to the URL pattern "/RedirectServlet" using the @WebServlet
annotation.
2. In the doGet method, the sendRedirect() method of the HttpServletResponse
object is called with the target URL ("https://www.example.com" in this case).
When the client's browser receives this response, it will automatically make a new request to the
specified URL, and the user will be redirected to that location.
It's important to note that after calling sendRedirect(), the current response is considered
complete, and no further processing should be done in the servlet. The browser will handle the
redirection, and any code after the sendRedirect() call will not be executed.

Additionally, you can use relative URLs for redirection within the same web application:
java

String relativeURL = "/anotherPage.jsp";


response.sendRedirect(request.getContextPath() + relativeURL);

In this example, getContextPath() is used to obtain the context path of the web application,
and the relative URL is appended to it for the redirection.
Remember to handle exceptions (IOException in this case) that may occur during the
redirection process.

You might also like