Servlet
Servlet
Servlet
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.
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>
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
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 −
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.
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) {
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.
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)
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";
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";
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";
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
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.