Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlet.

Similar presentations


Presentation on theme: "Servlet."— Presentation transcript:

1 Servlet

2 What are Java Servlets An alternate form of server-side computation that uses Java The Web server is extended to support an API, and then Java programs use the API to create dynamic web pages Using Java servlets provides a platform-independent replacement for CGI scripts. Servlets can be embedded in many different servers because the servlet API, which you use to write servlets, assumes nothing about the server's environment or protocol.

3 The Advantages of Servlets Over Traditional CGI
Efficiency CGI invoking Overhead of starting a new process can dominate the execution time. For N simultaneous request, the same code is loaded into memory N times. When terminated, lose cache computation, DB connection & .. Servlet JVM stays running and handles each request using Java thread. Only a single copy is loaded into memory Straightforward to store data between requests

4 The Advantages of Servlets Over Traditional CGI
Convinient CGI invoking Easy to install and setup Servlet Provides an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions and other utilities. No need to learn new programming languages if you are familiar with Java already. Easy to implement DB connection pooling & resource-sharing optimization.

5 Servlet Life Cycle Initialization Execution Destruction
the servlet engine loads the servlet’s *.class file in the JVM memory space and initializes any objects Execution when a servlet request is made, a ServletRequest object is sent with all information about the request a ServletResponse object is used to return the response Destruction the servlet cleans up allocated resources and shuts down

6 Simple Example import java.io.*; import javax.servlet.*;
import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>");out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>");out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>");out.println("</html>");}}

7 Client Interaction When a servlet accepts a call from a client, it receives two objects: A ServletRequest, which encapsulates the communication from the client to the server. A ServletResponse, which encapsulates the communication from the servlet back to the client. ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

8 The ServletRequest Interface
The ServletRequest interface allows the servlet access to: Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream. Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods. Interfaces that extend ServletRequest interface allow the servlet to retrieve more protocol-specific data. For example, the HttpServletRequest interface contains methods for accessing HTTP-specific header information.

9 The ServletResponse Interface
The ServletResponse interface gives the servlet methods for replying to the client. It: allows the servlet to set the content length and MIME type of the reply. provides an output stream, ServletOutputStream, and a Writer through which the servlet can send the reply data. Interfaces that extend the ServletResponse interface give the servlet more protocol-specific capabilities. For example, the HttpServletResponse interface contains methods that allow the servlet to manipulate HTTP-specific header information.

10 Request Information Example Source Code-1/2
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class RequestInfo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Request Information Example </title>"); out.println("</head>");out.println("<body>");

11 Request Information Example Source Code-2/2
out.println("<h3>Request Information Example</h3>"); out.println("Method: " + request.getMethod()); out.println("Request URI: " + request.getRequestURI()); out.println("Protocol: " +request.getProtocol()); out.println("PathInfo: " + request.getPathInfo()); out.println("Remote Address: " + request.getRemoteAddr()); out.println("</body>");out.println("</html>"); } /* We are going to perform the same operations for POST requests as for GET methods, so this method just sends the request to the doGet method.*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response);}}

12 Request Header Example

13 Request Header Example Source Code
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class RequestHeaderExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getHeader(name); out.println(name + " = " + value);}}}

14 Request Parameters

15 Request Parameters Source Code -1/2
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class RequestParamExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("GET Request. No Form Data Posted"); }

16 Request Parameters Source Code –2/2
public void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { Enumeration e = request.getParameterNames(); PrintWriter out = res.getWriter (); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getParameter(name); out.println(name + " = " + value);}}}

17 Additional Capabilities of HTTP Servlets
Cookies are a mechanism that a servlet uses to have clients hold a small amount of state-information associated with the user. Servlets can use the information in a cookie as the user enters a site (as a low-security user sign-on,for example), as the user navigates around a site (as a repository of user preferences for example), or both. HTTP servlets also have objects that provide cookies. The servlet writer uses the cookie API to save data with the client and to retrieve this data.

18 Cookies

19 Cookies Source Code – 1/2 import java.io.*; import javax.servlet.*;
import javax.servlet.http.*; public class CookieExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); // print out cookies Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i];String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value);}

20 Cookies Source Code –2/2 // set a cookie
String name = request.getParameter ("cookieName"); if (name != null && name.length() > 0) { String value = request.getParameter("cookieValue"); Cookie c = new Cookie(name, value); response.addCookie(c);}}}

21 Servlet References For an excellent tutorial on java servlets see:
The java Servlet API can be found at:

22 Session Capabilities 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. session-tracking capabilities. The servlet writer can use these APIs to maintain state between the servlet and the client that persists across multiple connections during some time period.

23 Sessions

24 Sessions Source Code –1/2
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); // print session info Date created = new Date( session.getCreationTime()); Date accessed = new Date(session.getLastAccessedTime());

25 Sessions Source Code –2/2
out.println("ID " + session.getId()); out.println("Created: " + created); out.println("Last Accessed: " + accessed); String dataName = request.getParameter("dataName"); if (dataName != null && dataName.length() > 0) {String dataValue = request.getParameter("dataValue"); session.setAttribute(dataName, dataValue);} // print session contents Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = String)e.nextElement(); value = session.getAttribute(name).toString(); out.println(name + " = " + value);}}}


Download ppt "Servlet."

Similar presentations


Ads by Google