Java Servlets – Part II
Contents
• Deploying Web Applications
• Working Example
• Session Tracking/Management
• Cookies
• Hidden Form Fields
• URL Rewriting
• HttpSession Interface
Deploying Web Applications
• There are 2 ways to manually deploy a web application
• One way is to use a Web Archive (WAR) file, which is a Java Archive (JAR) that
contains all the files and directories for a web application
• You’ve to copy the WAR file into Tomcat’s webapps directory
• Tomcat will automatically expand the WAR file into a proper directory structure
• Another way is to manually deploy a web app by copying the directories and
files for the application into Tomcat’s webapps directory
Deploying Web Applications
• Standard directories and files for a Web Application
All web applications that use servlets must In addition, you can also include (optional)
Deploying
have the WEB-INF and WEB-INF\classes other standard directories such as WEB-
directories INF\lib or the META-INF directory
Web
Applications
The WEB-INF directory must contain a The WEB-INF\classes is the root directory
[Link] file for the application for all Java classes & Servlets
Deploying Web Applications
• Summary of the directories and files for a web application
Deploying Web Applications
• The Deployment Descriptor (DD)
• The [Link] file is known as the deployment descriptor which is used to
configure a web application
• It is this file from which the Web Container gets the information about the
servlet to be invoked
• The web container uses an xml parser (such as SAX, DOM & Pull) to get
the desired information from the [Link] file
Deploying Web Application
• Some of the common elements used in [Link] file are
• <web-app> It represents the whole application
• <servlet> represents the servlet
• <servlet-name> represents the name of the servlet
• <servlet-class> represents the class of the servlet
• <servlet-mapping> used to map the servlet
• <url-pattern> used at the client side to invoke the servlet
Working Example
• The servlet example can be created by the following three ways
• By implementing the Servlet interface
• By extending GenericServlet class, or
• By extending HttpServlet class
• The most commonly used approach is to use HttpServlet class as it provide
methods such as doGet(), doPost() etc.
• We will design a dynamic web page that will show up the current date and time
Working Example
• Sample code for Servlet
import [Link].*;
import [Link].*;
import [Link].*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
[Link]("text/html");//setting the content type
PrintWriter pw=[Link]();//get the stream to write the data
[Link] today = new [Link]();
//writing html in the stream
[Link]("<html><body>");
[Link](“<h1 align = center>Welcome to Servlet Demo</h1>");
[Link](“<br>”+ today);
[Link]("</body></html>");
[Link]();//closing the stream
}}
Working Example
• Creating the Deployment Descriptor (DD)
<web-app>
<servlet>
<servlet-name>Demo Web App</servlet-name>
Name of the servlet
Ties the <servlet> element to the <servlet-mapping> element
<servlet-class>DemoServlet</servlet-class>
</servlet> Name of the servlet class
<servlet-mapping>
<servlet-name>Demo Web App</servlet-name>
<url-pattern>/welcome</url-pattern> Name the client uses for the request
</servlet-mapping>
</web-app>
• Start the server and deploy the project
• To start the server type the following in your
command window
C:\tomcat\bin\
Working startup
Example • Copy the project folder and paste it inside the
webapps folder under tomcat directory
• Open any browser window and type the
following under URL tab
http://
localhost:8080/demo/welcome
Session Management
• Session simply means a particular interval of time
• Keeping track of users as they move around a web site is known as session
tracking
• It is a way to maintain state (data) of a user. In servlets, it is known as session
management
• The servlet container uses HttpSession interface to create a session between an
HTTP client and an HTTP server
• Why session tracking/management is difficult with HTTP protocol?
• HTTP is a stateless protocol, which means, every time a client
requests a page from the web server, it treats the request as a new
request
• After the web server returns the page, it drops the connection
• If the browser makes additional requests, the web server has no way
to associate the browser with its previous requests
Session • So we need to maintain the state of a user to recognize a particular
Management connection
Session Management
• Java servlets technology supports four techniques for session tracking:
• Cookies
• Hidden Form Fields
• URL Rewriting
• HttpSession Interface
Session Management
• Cookies in Servlet
• Cookie is a small piece of information that is persisted between multiple client requests
• The servlet API uses a cookie to store the session ID within clients browser
• When a HTTP request is made, a cookie is added to the request
• For the subsequent requests from the client, they can be recognized using the received cookie
• However, if cookies have been disabled within a browser, this type of session tracking won’t
work
• Cookies in Servlet
• By default each request is considered as a new request
• A cookie is added with the response from the servlet
• It will stored inside the browsers cache and will be sent in the
subsequent requests made by the user
• This way we can keep track or recognize a user/connection
Session
Management
• Cookie Types
session & persistent
Session Management
• Cookies Example
• HTML home page
<form action = “login”>
user Name: <input type = “text” name = “username”/><br/>
Password: <input type = “password” name = “userPassword”/><br/>
<input type = “submit” value = “submit”/>
</form>
Session Management
• Cookie Example: I Servlet Class
import [Link].*;
import [Link].*; //Creating two cookies
import [Link].*; Cookie c1=new Cookie("userName",name);
public class MyServlet1 extends HttpServlet Cookie c2=new Cookie("userPassword",password);
{
public void doGet(HttpServletRequest request, //Adding the cookies to response header
HttpServletResponse response) { [Link](c1);
try{ [Link](c2);
[Link]("text/html"); [Link]("<br><a href='welcome'>View Details</a>");
PrintWriter pwriter = [Link](); [Link]();
}catch(Exception exp){
String name = [Link]("userName"); [Link](exp);
String password = [Link]("userPassword"); }
[Link]("Hello "+name); }
[Link]("Your Password is: "+password); }
Session Management
• Cookie Example: II Servlet Class
//Displaying user password value from cookie
import [Link].*; [Link]("Password: "+c[2].getValue());
import [Link].*;
import [Link].*; [Link]();
public class MyServlet2 extends HttpServlet { }catch(Exception exp){
public void doGet(HttpServletRequest request, [Link](exp);
HttpServletResponse response){ }
try{ }
[Link]("text/html"); }
PrintWriter pwriter = [Link]();
//Reading cookies
Cookie c[]=[Link]();
//Displaying User name value from cookie
[Link]("Name: "+c[1].getValue());
Session Management
• Cookie Example: [Link]
<web-app>
<display-name>BeginnersBookDemo</display-name> <servlet>
<welcome-file-list> <servlet-name>Servlet2</servlet-name>
<welcome-file>[Link]</welcome-file> <servlet-class>MyServlet2</servlet-class>
</welcome-file-list> </servlet>
<servlet> <servlet-mapping>
<servlet-name>Servlet1</servlet-name> <servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet1</servlet-class> <url-pattern>/welcome</url-pattern>
</servlet> </servlet-mapping>
<servlet-mapping> </web-app>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
Session Management
• Cookie Example: Output
• Welcome Screen
• After clicking submit
Session Management
• Hidden Form Field
• A hidden text field is used for maintaining the state of a user
• When a client/user submits the form, the browser transfers these hidden values to the server
• Hidden boxes be present in the web pages of the browser window so they do not provide a
burden to the server
• It is widely used in comment form of a website. In such case, we store page id or page name in
the hidden field so as to uniquely identify each web page
• Hidden Form Field Example
• In the given example, we will store the name of a
user in a hidden textfield and get that value from
another servlet object
Session
Management
Session Management
• Hidden Form Field Example
[Link]
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
Session Management
• Example Cont.…
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
[Link]("text/html");
PrintWriter out = [Link]();
String n=[Link]("userName");
[Link]("Welcome "+n);
Session Management
• Example Cont.…
//creating form that have invisible textfield
[Link]("<form action='servlet2'>");
[Link]("<input type='hidden' name='uname' value='"+n+"'>");
[Link]("<input type='submit' value='go'>");
[Link]("</form>");
[Link]();
}catch(Exception e){[Link](e);}
}
}
Session Management
• Example Cont.…
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
[Link]("text/html");
PrintWriter out = [Link]();
//Getting the value from the hidden field
String n=[Link]("uname");
[Link]("Hello "+n);
[Link]();
}catch(Exception e){[Link](e);}
}
}
Session Management
• Example Cont.…
[Link] <servlet>
<web-app> <servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-mapping>
<servlet-class>FirstServlet</servlet-class>
<servlet-name>s2</servlet-name>
</servlet>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<servlet-mapping>
</web-app>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
Session Management
• URL Rewriting
• Session tracking can be achieved by URL rewriting if cookies are disabled in a browser by the client
• URL rewriting is a process of appending or modifying any URL structure while loading a web page
• A token (parameter) is added at the end of the URL. The token consists of a name/value pair
separated by an equal (=) sign
• When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server.
• From a servlet, we can use getParameter() method to obtain a parameter value
Session Management
• URL Rewriting – Example
• In the given example, we will maintain the state of the user by appending the name of the user
in the request URL
[Link]
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
Session Management
• URL Rewriting Example
[Link]
import [Link].*;
import [Link].*; //appending the username in the query string
import [Link].*; [Link]("<a href='servlet2?uname="+n+"'>visit</a>");
public class FirstServlet extends HttpServlet {
[Link]();
public void doGet(HttpServletRequest request, HttpServletResponse
response){ }catch(Exception e){[Link](e);}
try{ }
[Link]("text/html");
}
PrintWriter out = [Link]();
String n=[Link]("userName");
[Link]("Welcome "+n);
Session Management
• URL Rewriting Example
//getting value from the query string
[Link] String n=[Link]("uname");
import [Link].*; [Link]("Hello "+n);
import [Link].*;
import [Link].*; [Link]();
public class SecondServlet extends HttpServlet { }catch(Exception e){[Link](e);}
}
public void doGet(HttpServletRequest request, }
HttpServletResponse response)
try{
[Link]("text/html");
PrintWriter out = [Link]();
Session Management
• URL Rewriting Example
[Link] <servlet>
<web-app>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
<servlet>
</servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
<servlet-mapping>
</servlet>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
<servlet-mapping>
</servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</web-app>
</servlet-mapping>
Session Management
• HttpSession Interface
• Java servlets provide an interface called HttpSession which creates sessions with a unique
session id for each user
• On client’s first request, the web container generates a unique ID and gives it back to the
client with response
• The client sends back the session ID with each request making it easier for the container to
identify where the request is coming from
• The web container uses this ID, finds the matching session with this ID and associates the
session with the request
Session Management
• HttpSession Interface
Session Management
• HttpSession Interface
getSession() method returns a session, If the session already exist, it
return the existing session else creates a new session
• Creating a new session
• HttpSession session = [Link]();
getSesssion(true) always return a new
• HttpSessopm session = [Link](true); session
• Getting a pre-existing session
Returns a pre-existing session
• HttpSession session = [Link](false);
• Destroying a session
Destroying a session
• [Link]();
Session Management
• HttpSession Interface – Example
[Link]
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
Session Management
• HttpSession Interface – Example
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class Validate extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
Session Tracking
• Example Contd…
String name = [Link]("user");
String pass = [Link]("pass");
if([Link]("1234"))
{
//creating a session
HttpSession session = [Link]();
[Link]("user", name);
[Link]("Welcome");
}
}
}
Session Management
• Example Contd…
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class Welcome extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
HttpSession session = [Link]();
String user = (String)[Link]("user");
[Link]("Hello "+user);
}
}
Session Management
<servlet-mapping>
• Example Cont.… <servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
[Link] </servlet-mapping>
<web-app..> <servlet-mapping>
<servlet-name>Welcome</servlet-name>
<servlet> <url-pattern>/Welcome</url-pattern>
<servlet-name>Validate</servlet-name> </servlet-mapping>
<servlet-class>Validate</servlet-class>
</servlet> <welcome-file-list>
<servlet> <welcome-file>[Link]</welcome-file>
<servlet-name>Welcome</servlet-name> </welcome-file-list>
<servlet-class>Welcome</servlet-class>
</servlet> </web-app>
Home .html
Newcookies cls
Newcookies cls
Newcookies1
Newcookies1
XML
Output
Output
Output
Thank You