SERVLET AND JSP

Servlet

  • Servlet is a Java programming language class that runs on a Web server
  • Servlets are used for creating dynamic web applications in java by extending the capability of a server
  • The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets
  •  All servlets must implement the Servlet interface, which defines life-cycle methods.

Servlet Architecture

  • Web Browser: An application that runs on user or client machine to display the contents
  • Web Server: An application that runs on server machine to serve client request
  • Servlet Container: It is a part of web server which keep track of all servlets in the web server
  • HTTP request: It a message exchanged between web browser - web server and web server - servlet container
  • HTTP response: It a message exchanged between servlet container & web server and web server -& web browser
  • Database: It hold the data belongs to various applications and accessed through servlet

Servlet Life Cycle

Servlet Container

  • It is known as servlet engine which manages Java Servlet components on top of a web server to the request send by the client. 
  • Servlet Container provides the following services:
    • It manages the servlet life cycle
    • The resources like servlets, JSP pages and HTML files are managed by servlet container
    • It appends session ID to the URL path to maintain session.
    • Provides security service
    • It loads a servlet class from network services, file systems like remote file system and local file system

How web container handles the servlet request?

  • Maps the request with the servlet in the web.xml file
  • Creates request and response objects for this request
  • Calls the service method on the thread
  • The public service method internally calls the protected service method
  • The protected service method calls the doGet method depending on the type of request.
  • The doGet method generates the response and it is passed to the client.
  • After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.

How Servlet Works?

  • When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets
  • Once the servlet is loaded, the servlet container creates the instance of servlet class. 
  • For each instantiated servlet, its init() method is invoked.
  • Client (user browser) sends an Http request to web server on a certain port. 
  • Each time the web server receives a request, the servlet container creates HttpServletRequest and HttpServletResponse objects.
  • When servlet container shuts down, it unloads all the servlets and calls destroy() method for each initialized servlets.

Servlet Syntax:


public class Servlet-Name extends HttpServlet
{
public void init()
{
/* used to initialize resources */
}
public void service()
{
/* used to fulfill client request */
}
public void destroy()
{
/* Release the resources */
}
}

Example


public class HelloWorld extends GenericServlet
{
    public void service(ServletRequest request, ServletResponse response )
    throws IOException
    {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1> Hello World </h1>");
out.close();
    }
}

Note: Save this program as HelloWorld.java and locate it into servlet container

Java Servlet Packages


java.lang.Object 
|_extended by javax.servlet.GenericServlet
        
        |_extended by javax.servlet.http.HttpServlet

Interfaces in javax.servlet package

  • Servlet
  • ServletRequest
  • ServletResponse
  • ServletConfig
  • ServletContext
  • SingleThreadModel
  • RequestDispatcher
  • ServletRequestListener
  • ServletRequestAttributeListener
  • ServletContextListener
  • ServletContextAttributeListener
  • Filter
  • FilterConfig
  • FilterChain

Classes in javax.servlet package

  • GenericServlet
  • ServletInputStream
  • ServletOutputStream
  • ServletException
  • ServletRequestWrapper
  • ServletRequestEvent
  • ServletResponseWrapper
  • ServletContextEvent
  • ServletRequestAttributeEvent
  • ServletContextAttributeEvent
  • UnavailableException

Interfaces in javax.servlet.http package

  • HttpSession
  • HttpServletRequest
  • HttpServletResponse
  • HttpSessionAttributeListener
  • HttpSessionListener
  • HttpSessionBindingListener
  • HttpSessionActivationListener
  • HttpSessionContext

Classes in javax.servlet.http package

  • HttpServlet
  • Cookie
  • HttpSessionEvent
  • HttpSessionBindingEvent
  • HttpServletRequestWrapper
  • HttpServletResponseWrapper
  • HttpUtils

Form Get Action

  • HTML <form> tag has an attribute method="get/post"
  • When the method holds a value "get", the data submitted by the html form will be handled by doGet method of the servlet as follows:

user.html

<!DOCTYPE html>
<html>
   <head>
       <title>doGet Example</title>
   </head>
  <body>
<form name="myform" action="MyServlet" method="get">
Enter Name:<input type="text" name="uname"><br><br>
Enter Age:<input type="text" name="uage"><br><br>
<input type="submit" value="submit">
</form>
  </body>
</html>

MyServlet.java
import javax.servlet.*;  
import javax.servlet.http.*;  
public class MyServlet extends HttpServlet
{  
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{  
try
{  
response.setContentType("text/html");  
PrintWriter out = response.getWriter(); 
String name=request.getParameter("uname");
String age=request.getParameter("uage");
out.println("<h3>Welcome to doGet Method</h3> ");  
out.println("<br>Name:"+name);  
out.println("<br>Age:"+age);
out.close();  
}
catch(Exception e)
{
System.out.println(e);
}  
}  
}  

response.setContentType() - sets the response type
response.getWriter() - establishes path between client and server
request.getParameter()  - collects data from html form.

Form post action


  • HTML <form> tag has an attribute method="get/post"
  • When the method holds a value "post", the data submitted by the html form will be handled by doGet method of the servlet as follows:
user.html
<!DOCTYPE html>
<html>
   <head>
       <title>doPost Example</title>
   </head>
  <body>
<form name="myform" action=“MyServlet" method=“post">
Enter Name:<input type="text" name="uname"><br><br>
Enter Password:<input type="password" name="pwd"><br><br>
<input type="submit" value="submit">
</form>
  </body>
</html>

MyServlet.java
import javax.servlet.*;  
import javax.servlet.http.*;  
public class MySerlvet extends HttpServlet
{  
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{  
try
{  
response.setContentType("text/html");  
PrintWriter out = response.getWriter(); 
String name=request.getParameter("uname");
String pwd=request.getParameter("pwd");
out.println("<h3>Welcome to doPost Method</h3> ");  
out.println("<br>Name:"+name);  
out.println("<br>Password:"+pwd);
out.close();  
}
catch(Exception e)
{
System.out.println(e);
}  
}  
}  


Session Handling

  • Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.
  • Http is a stateless protocol. So the state information can be stored in the server using session management techniques.
  • Sessions are shared among the servlets accessed by a client.
  • Techniques
    • Cookies
    • Hidden Form Field
    • URL Rewriting
    • HttpSession

Session Handling using Cookies

  • Cookies are small pieces of information that are sent in response from the web server to the client.
  • 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.
  • Types of Cookie
    • Non-persistent cookie - valid for single session
    • Persistent cookie - valid for multiple session 

How cookies works?

  • By default, each request is considered as a new request.
  • Servlet adds cookie in response
  • Then cookie is stored in the cache of the browser
  • If request is sent by the same user, cookie is added with request by default. Thus, server recognizes the user as the old user.

Methods of Cookie Class


Example

login.html

<html>
<body>
<form method="post" action="Validate1"> 
Name:<input type="text" name="user" /><br/> 
Password:<input type="password" name="pass" ><br/>
<input type="submit" value="submit">
 </form>
</body>
</html>

Validate1.java

//Session Handling using Cookies
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate1 extends HttpServlet 
{
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
{
        response.setContentType("text/html");
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        if(name.equals("abc")&&pass.equals("1234"))
        {
            Cookie ck = new Cookie("username",name);
            response.addCookie(ck);
            response.sendRedirect("Welcome");
        }
    }
}`

Welcome.java

//Session Handling using Cookies
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
      protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,          IOException 
{
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        Cookie[] cks = request.getCookies();
        out.println("Welcome "+cks[1].getValue());
    }
}

Session Handling using URL Rewriting

  • If the client has disabled cookies in the browser then session management using cookie wont work. 
  • In that case URL Rewriting can be used as a backup

Example

login.html

<html>
<body>
<form method="post" action="Validate"> 
Name:<input type="text" name="user" /><br/> 
Password:<input type="password" name="pass" ><br/>
<input type="submit" value="submit">
 </form>
</body>
</html>

Validate.java

//Session Handling using URL Rewriting
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");
          String name = request.getParameter("user");
          String pass = request.getParameter("pass");
          if(pass.equals("1234"))
          {
response.sendRedirect(“Welcome?uname="+name);        
  }
    }
}

Welcome.java

//Session Handling using URL Rewriting
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");
        PrintWriter out = response.getWriter();
   String user = request.getParameter("uname"); 
   out.println("Welcome "+user);   
}
}

Session Handling using Hidden Form Fields

  • "hidden" attribute of <form> tag can be used for session management for passing data from one page to another page
<html>
<body>
<form method="post" action="Validate">
         User:         <input type="text" name="user" /><br/>
         Password: <input type=“password" name="pass" ><br/>
                           <input type="submit" value=“Submit">
</form>
</body>
</html>

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");
PrintWriter out=response.getWriter();
        String uname = request.getParameter("user");
        String pass = request.getParameter("pass");
        if(pass.equals("1234"))
        {
out.println(“<form action=‘Welcome’ method=‘post’>”);
out.println(“<input type=‘hidden’ name=‘uname’ value=“+uname+”>”);
out.println(“<input type=‘submit’ value=‘Go’>”);
        }
    }
}

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();
        String user=request.getParameter(“uname”);
        out.println("Hello "+user);
    }
}

Session Handling using HttpSession Object
  • HttpSession object is used to store entire session with a specific client
  • On client's first request, the Web Container generates a unique session ID and gives it back to the client with response. This is a temporary session created by web container.
  • The client sends back the session ID with each request. Making it easier for the web container to identify where the request is coming from.
  • The Web Container uses this ID, finds the matching session with the ID and associates the session with the request.
HttpSession Methods


login.html

<html>
<body>
<form method="post" action="FirstServlet">
         User Name:         <input type="text" name="uname" /><br/>
         Password: <input type="password" name="pass" ><br/>
                           <input type="submit" value="Submit">
</form>
</body>
</html>

FirstServlet.java

//Session Handling using HttpSession
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("uname");  
out.print("Welcome "+n);  
HttpSession session=request.getSession();  
session.setAttribute("uname",n);  
out.print("<a href='SecondServlet'>visit</a>");  
out.close();  
}
catch(Exception e) {  System.out.println(e); }  
}  

SecondServlet.java

//Session Handling using HttpSession
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();  
HttpSession session=request.getSession(false);  
String n=(String)session.getAttribute("uname");  
out.print("Hello "+n);  
out.close();  
}
catch(Exception e)
{
System.out.println(e);
}  
}  


JSP

  • Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications.
  • JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.
  • JSP technology enables rapid development of web-based applications
  • JSP pages are easier to maintain then a Servlet
  • JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP adds Java code inside HTML using JSP tags

Architecture


JSP Life Cycle


JSP Syntax

  • JSP Scriptlet
    • Scriptlet tag allows to write Java code into JSP file.
    • JSP container moves statements in _jspservice() method while generating servlet from jsp.
    • Syntax:
                  <% ... %>
  • JSP Declaration Tag
    • for declaring variables, methods and classes
    • declaration is made outside the service method
    • Syntax:
                      <%! Datatype varname; %>
  • JSP Expression
    • evaluates the expression placed in it
        <%= ... %>
  • JSP Directives
         <%@ ... %>

JSP Scriptlet Example

<!DOCTYPE html>
<html>
<head><title>JSP Example</title></head>
<body>
<% out.println(“Hello World”); %>
</body>
</html>


JSP Declaration Example

<!DOCTYPE html>
<html>
<head><title>JSP Example</title></head>
<body>
<%! int num=10; %>
<% out.println(“This number is ”+num); %>
</body>
</html>


JSP Expression Example

date.jsp

<html>
<body>
Hello!  The time is now <%= new java.util.Date() %>
</body>
</html>

Directives

  • The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.
  • There are three types of directives:
  • page directive
        <%@ page attribute="value" %> 
  • include directive
        <%@ include file="resourceName" %>

  • taglib directive
        <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>


page directive

  • Attributes of JSP page directive
    • import
    • contentType
    • extends
    • info
    • buffer
    • language
    • isELIgnored
    • isThreadSafe
    • autoFlush
    • session
    • pageEncoding
    • errorPage
    • isErrorPage

include directive

header.html

<html>
<head>
<title>K.Ramakrishnan College of Technology</title>
</head>
<body>
<h1>K.Ramakrishnan College of Technology</h1>
footer.html

</body>
</html>

main.jsp

<%@ include file="header.html" %>
<p>Main content</p>
<%@ include file="footer.html" %>

taglib directive

  • The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.
Syntax:
      <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>  

JSP Action Tags

jsp:forward & jsp:param Example


page1.jsp

<html>  
<body>  
<h2>this is index page</h2>  
<jsp:forward page="page2.jsp" >  
<jsp:param name=“email" value=“abc@gmail.com" />  
</jsp:forward>  
</body>  
</html> 

page2.jsp

<html>  
<body>  
  <%= request.getParameter(“email") %>  
  </body>  
</html>

jsp:include


<html>
<body>
<h2>this is index page</h2>  
  <jsp:include page=“page2.jsp" />  
  <h2>end section of index page</h2> 
</body>
</html>


THANK YOU