32
Servlets

Servlets

Embed Size (px)

Citation preview

Page 1: Servlets

Servlets

Page 2: Servlets

Outline• Introduction to web terminologies

– WWW ,URL, HTML and HTTP• Servlet & Its Advantages• Life Cycle of Servlet• Steps for Creating Servlet( in Apache Tomcat)

– Directory Structure – web.xml

• Servlet Request and Servlet Response• Servlet handling from data (Sample Programs on Servlet)• RequestDispatcher• State Management

– Cookies– HttpSession

Page 3: Servlets

WWW (World Wide Web)• The Web is a distributed information system based on

hypertext.• Most Web documents are hypertext documents

formatted via the HyperText Markup Language (HTML)• HTML documents contain

– text along with font specifications, and other formatting instructions

– hypertext links to other documents, which can be associated with regions of the text.

– forms, enabling users to enter data which can then be sent back to the Web server

Page 4: Servlets

URL (Unified Resources Locators)

• URL example: http://www.mit.asia/mca– The first part indicates how the document is to be

accessed• “http” indicates that the document is to be accessed

using the Hyper Text Transfer Protocol.– The second part gives the unique name of a

machine on the Internet.– The rest of the URL identifies the document within

the machine.

Page 5: Servlets

HTML & HTTP• HTML provides formatting, hypertext link, and image

display features– including tables, stylesheets (to alter default formatting), etc.

• HTML also provides input features• Select from a set of options

– Pop-up menus, radio buttons, check lists• Enter values

– Text boxes

• HyperText Transfer Protocol (HTTP) used for communication with the Web server

Page 6: Servlets

HTML Sample Code<html><body> <table border>

<tr> <th>ID</th> <th>Name</th> <th>Department</th> </tr><tr> <td>00128</td> <td>Zhang</td> <td>Comp. Sci.</td> </tr>

</table> <form action=“FirstPage" method=get>

Search for: <select name="persontype"> <option value="student" selected>Student </option> <option value="instructor"> Instructor </option> </select> <br>Name: <input type=text size=20 name="name"><input type=submit value="submit">

</form></body> </html>

Page 7: Servlets

Display of Sample HTML Source

Page 8: Servlets

Servlet• Servlet is a technology that is used to create web

application • Web component that is deployed on server side

to create dynamic web pages• Servlet is an API that provides many Interfaces

and classes including documentation• Servlet is an Interface that must be implemented

for creating any servlet• Servlet is a class that extend the functionalities

of server and responds to the incoming requests

Page 9: Servlets

Java Web Application Request Handling

Servlet

Page 10: Servlets

Advantages of Servlet Performance

The performance of servlets is superior to CGI because there is no process creation for each client request.

Each request is handled by the servlet container process. After a servlet has completed processing a request, it stays resident in

memory, waiting for another request. Portability

Like other Java technologies, servlet applications are portable. Rapid development cycle

As a Java technology, servlets have access to the rich Java library that will help speed up the development process.

Robustness Servlets are managed by the Java Virtual Machine. Don't need to worry about memory leak or garbage collection, which

helps you write robust applications. Widespread acceptance

Java is a widely accepted technology.

Page 11: Servlets

Life Cycle of Servlet

Initializationinit()

Serviceservice()

doGet()doPost()

doDelete()doHead()doTrace()

doOptions()

Destructiondestroy()

Concurrent Threadsof Execution

Page 12: Servlets

Life Cycle Methods• init() : – Servlet loads and initializes the servlet

• service():– Servlet handles one or more client Request and

Responses to the client• destroy():– Servlet is deactivated or server is terminated– Memory allocated for the servlet and its object are

garbage collected

Note: All above methods are inherited from GenericServlet class

Page 13: Servlets

Directory StructureROOT

Save .java program

Page 14: Servlets

Web.xml

Page 15: Servlets

Servlet Request• Servlet API provides two important interfaces– javax.servlet.ServletRequest– javax.servlet.http.HttpServletRequest

ServletRequest<<interface>>

HttpServletRequest<<interface>>

extends

getParameter()getAttribute()

getSession()getMethod()

Page 16: Servlets

Servlet Response• Servlet API provides two important interfaces– javax.servlet.ServletResponse– javax.servlet.http.HttpServletResponse

ServletResponse<<interface>>

HttpServletResponse<<interface>>

extends

PrintWriter getWriter()setContentType( String type)

void addCookie(Cookie c )int getStatus()

Page 17: Servlets

Sample Servlet Exampleimport java.io.*;import javax.servlet.*;

public class ServletExample extends GenericServlet{

public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException{response.setContentType("text/html"); // server responds in HTML format

PrintWriter out=response.getWriter();out.println("<html>");out.println("<body>");out.println("Hello World...");out.println("</body>");out.println("</html>");}

}

Page 18: Servlets

Request Dispatcher• It is an interface• Object of this interface can dispatch the

request to any resources(such as HTML,JSP, Servlet) on server

Methods Description

void forward(ServletRequest request,ServletResponse response)

Forwards a request from a servlet to another resource (HTML,JSP, Servlet) on the server

void include(ServletRequest request,ServletResponse response)

Includes the content of a resource (HTML,JSP, Servlet) in the response

Page 19: Servlets

Request Dispatcher

1) forward() method:RequestDispatcher rd=

request.getRequestDispatcher("Employee.jsp"); rd.forward(request, response);

2) include() method :RequestDispatcher rd=

request.getRequestDispatcher("HomePage.html"); rd.include(request, response);

Page 20: Servlets

Session Management

• Http is a Stateless protocol. Each request and response is independent

• Session Management is a mechanism used by WEB CONTAINER to store session information for the particular user.

Page 21: Servlets

Session Management

Page 22: Servlets

Session ManagementTechniques used by Servlet application for session management :– Cookies– HttpSession

Page 23: Servlets

Cookies(javax.servlet.http.Cookie class)• Small piece of information that are sent from web

server to the client• Stored on client’s computer

Page 24: Servlets

Cookies

• Advantages:– Simplest technique of maintaining the state– Maintained at client side

• Disadvantages:– It will not work if cookie is disabled from browser– Only textual information can be set in cookie

object

Page 25: Servlets

ExampleFirstServlet.javaprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,

IOException { Cookie ck = null; ck = new Cookie("uname", "MCA"); //setting value response.addCookie(ck); RequestDispatcher rd =

request.getRequestDispatcher(“SecondServlet"); rd.forward(request, response);}

Page 26: Servlets

ExampleSecondServlet.javaprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

Cookie cookvar = null;response.setContentType("text/html");PrintWriter out = response.getWriter();Cookie[] cks = request.getCookies(); //accepting cookie valueif (cks != null) {for (int i = 0; i < cks.length; i++) {cookvar = cks[i];out.print("Value:" + cookvar.getValue() );out.print( "Name:" + cookvar.getName());}

}out.close();

}

Page 27: Servlets

HttpSession

• HttpSession object is used to store entire session with specific client

• We can store , retrive and remove attribute from HttpSession object

• Any servlet can have access to HttpServlet object through the getSession() method of HttpServletRequest object

Page 28: Servlets

1) On Client’s first request, the Web container generates a unique session ID and gives it back to the client with response

2) The Client sends back the session ID with each request3) The Web Container uses this ID ,finds the matching session with the ID

and associates the session with the request

Page 29: Servlets
Page 30: Servlets

FirstServlet.javaimport 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);HttpSession session=request.getSession();session.setAttribute("uname",n);out.print("<a href=‘SecondServlet'>visit</a>");out.close();

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

}

Page 31: Servlets

SecondServlet.javaimport 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);}}

}

Page 32: Servlets

Assignment

1. Explain session management in detail .Also, explain how HttpSession works?

2. Write a servlet program to insert Employee details like : empid,employee_name,address,date_of_birth in Employee table using JDBC.