You are on page 1of 59

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
web.xml 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 web.xml 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 web.xml file
Deploying Web Application

• Some of the common elements used in web.xml 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 javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
Java.util.Date today = new java.util.Date();
//writing html in the stream
pw.println("<html><body>");
pw.println(“<h1 align = center>Welcome to Servlet Demo</h1>");
Pw.println(“<br>”+ today);
pw.println("</body></html>");
pw.close();//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 java.io.*;
import javax.servlet.*; //Creating two cookies

import javax.servlet.http.*; 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) { response.addCookie(c1);

try{ response.addCookie(c2);

response.setContentType("text/html"); pwriter.print("<br><a href='welcome'>View Details</a>");

PrintWriter pwriter = response.getWriter(); pwriter.close();


}catch(Exception exp){

String name = request.getParameter("userName"); System.out.println(exp);

String password = request.getParameter("userPassword"); }

pwriter.print("Hello "+name); }

pwriter.print("Your Password is: "+password); }


Session Management
• Cookie Example: II Servlet Class
//Displaying user password value from cookie
import java.io.*; pwriter.print("Password: "+c[2].getValue());
import javax.servlet.*;
import javax.servlet.http.*; pwriter.close();
public class MyServlet2 extends HttpServlet { }catch(Exception exp){
public void doGet(HttpServletRequest request, System.out.println(exp);
HttpServletResponse response){ }
try{ }
response.setContentType("text/html"); }
PrintWriter pwriter = response.getWriter();
//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("Name: "+c[1].getValue());
Session Management
• Cookie Example: web.xml

<web-app>
<display-name>BeginnersBookDemo</display-name> <servlet>

<welcome-file-list> <servlet-name>Servlet2</servlet-name>

<welcome-file>index.html</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

index.html

<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
Session Management

• Example Cont.…
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
Session Management

• Example Cont.…

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
}

}
Session Management
• Example Cont.…
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();
}catch(Exception e){System.out.println(e);}
}
}
Session Management

• Example Cont.…
web.xml <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

Index.html

<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
Session Management

• URL Rewriting Example


FirstServlet.java
import java.io.*;
import javax.servlet.*; //appending the username in the query string
import javax.servlet.http.*; out.print("<a href='servlet2?uname="+n+"'>visit</a>");

public class FirstServlet extends HttpServlet {


out.close();

public void doGet(HttpServletRequest request, HttpServletResponse


response){ }catch(Exception e){System.out.println(e);}
try{ }

response.setContentType("text/html");
}
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
Session Management

• URL Rewriting Example


//getting value from the query string

SecondServlet.java String n=request.getParameter("uname");

import java.io.*; out.print("Hello "+n);

import javax.servlet.*;
import javax.servlet.http.*; out.close();

public class SecondServlet extends HttpServlet { }catch(Exception e){System.out.println(e);}


}

public void doGet(HttpServletRequest request, }


HttpServletResponse response)
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();
Session Management

• URL Rewriting Example


web.xml <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 = request.getSession();
getSesssion(true) always return a new
• HttpSessopm session = request.getSession(true); session

• Getting a pre-existing session


Returns a pre-existing session
• HttpSession session = request.getSession(false);

• Destroying a session
Destroying a session
• session.invalidate();
Session Management

• HttpSession Interface – Example

Index.html

<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

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

public class Validate extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
Session Tracking
• Example Contd…

String name = request.getParameter("user");


String pass = request.getParameter("pass");

if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
}
}
Session Management

• Example Contd…
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Welcome extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Hello "+user);
}
}
Session Management

<servlet-mapping>

• Example Cont.… <servlet-name>Validate</servlet-name>


<url-pattern>/Validate</url-pattern>
web.xml </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>index.html</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

You might also like