Java Servlets - Part II-1
Java Servlets - Part II-1
Contents
• Deploying Web Applications
• Working Example
• Session Tracking/Management
• Cookies
• URL Rewriting
• HttpSession Interface
Deploying Web Applications
• 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
• 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
• 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
• 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
<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
C:\tomcat\bin\
Working startup
http://
localhost:8080/demo/welcome
Session Management
• Keeping track of users as they move around a web site is known as session
tracking
• 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
• Cookies
• 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
• 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
• It will stored inside the browsers cache and will be sent in the
subsequent requests made by the user
• Cookies Example
{
public void doGet(HttpServletRequest request, //Adding the cookies to response header
try{ response.addCookie(c2);
pwriter.print("Hello "+name); }
<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
• Welcome Screen
• 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
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Session Management
• Example Cont.…
}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();
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.
• 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
response.setContentType("text/html");
}
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Session Management
import javax.servlet.*;
import javax.servlet.http.*; out.close();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
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
• Destroying a session
Destroying a session
• session.invalidate();
Session Management
Index.html
Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.*;
<servlet-mapping>