1 / 39

Java Servlet Technology

Java Servlet Technology. Ref : The Java EE 5Tutorial • June 2010 http://www.vnrgroups.com/download_files/Servlets.ppt Servlet_tutorial.pdf. Definition. Java Servlet technology was created as a portable way to provide dynamic, user-oriented content. What Is a Servlet ?.

Download Presentation

Java Servlet Technology

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.


Presentation Transcript

  1. Java Servlet Technology Ref: TheJava EE 5Tutorial • June 2010 http://www.vnrgroups.com/download_files/Servlets.ppt Servlet_tutorial.pdf

  2. Definition • Java Servlet technology was created as a portable way to provide dynamic, user-oriented content.

  3. What Is a Servlet? • A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. • Primarily Web-servers • Java Servlet technology defines HTTP-specific servletclasses.

  4. Introduction – request-response model • Request-response model. HTTP Request request Server <html> <head> <body> … <html> <head> <body> … Client response HTTP HTML

  5. Introduction – what is a request and response HTTP Request HTTP Response • Key elements of a “request” • stream: • HTTP method (action to be performed). • The page to access (a URL). • Form parameters. • Key elements of a “response” • stream: • A status code (for whether the request was successful). • Content-type (text, picture, html, etc…). • The content ( the actual content).

  6. Introduction – What is a Servlet Where does Servlet come into the picture? I can serve only static HTML pages Web Server Application Not a problem. I can handle dynamic requests. Helper Application Web Server machine “The Helper Application is nothing but a SERVLET”

  7. Servlet Architecture -Web Container • What is a Web Container? request GET. ….. GET. ….. GET. ….. Web Server Web Container Servlet Client

  8. Servlet Architecture – Web Container The CONTAINER What is the role of Web Container ? • Communication Support • Lifecycle Management • Multi-threading support • Security • JSP Support S2 S1 JSP1 S3 S4 The container can contain multiple Servlets & JSPs within it

  9. Coding Servlets • The javax.servletand javax.servlet.httppackages provide interfaces and classes for writing servlets. • Create a subclass of HttpServlet • public class HelloServlet extends HttpServlet{..} • Override few methods of HttpServlet • doGet(), doPost()

  10. Invoking Servlet <form action=“HelloServlet" method="post" > <p>User Id:<input type="text" name="userid" /></p> <p><input type="submit" value="Say Hello" /></p> </form>

  11. Servlet Life Cycle • A servlet life cycle can be defined as the entire process from its creation till the destruction • The servlet is initialized by calling the init () method. • The servlet calls service() method to process a client's request. • The servlet is terminated by calling the destroy() method. • Finally, servlet is garbage collected by the garbage collector of the JVM.

  12. Web Container’s role • The life cycle of a servlet is controlled by the container in which the servlet has been deployed. • If an instance of the servlet does not exist, the web container • Loads the servlet class. • Creates an instance of the servlet class. • Initializes the servlet instance by calling the init method • Invokes the service method, passing request and response objects • If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy method

  13. Servlet Operation

  14. The init() method • The init method is designed to be called only once when the servlet is first created

  15. The service() method • The servlet (web) container calls the service() method: • to handle requests coming from the client( browsers) and • to write the formatted response back to the client. • Each time the server receives a request for a servlet, the server spawns a new thread and calls service • service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate

  16. doGet() & doPost() • Each method is called with two parameters • A request parameter containing data about the request • A response parameter that is used by the servlet to create the response • public void doGet(HttpServletRequest request, HttpServletResponse response) • public void doPost(HttpServletRequest request, HttpServletResponse response)

  17. request object (Ref: Chp:6) • object that provides client request information to a servlet. • The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service method • A ServletRequest object provides data including parameter name and values, attributes, and an input stream.

  18. request object • The request object used to retrieve form data sent by the client. • getParameter(“name“): to get the value of a form parameter. • getParameterValues(): returns multiple values, for example checkbox. • getParameterNames(): complete list of all parameters in the current request.

  19. response object • Object assists a servlet in sending a response to the client. • The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method. • PrintWriter out = response.getWriter(); • out.println(“<h1> Amrita </h1>”);

  20. Servlet Architecture – Web Container • How does the Container handle a request? Servlet request Web Container Http request response Thread Web Server <Html> <Body> ……. </Body> </Html> response Service() Client doGet()

  21. Servlet Lifecycle - Hierarchy Interface Servlet If not overridden, implements init() method from the ‘Servlet’ interface, Abstract class GenericServlet If not overridden, implements service() method. HttpServlet Abstract class We implement the HTTP methods here. Concrete class Your Servlet

  22. Servlet Lifecycle – 3 big moments

  23. Servlet Lifecycle – Thread handling • The Container runs multiple threads to process multiple requests to a single servlet. Container Client B Client A Servlet Thread A Thread B response request request response

  24. State management • HTTP is a "stateless" protocol . • servlet provides HttpSession object which provides a way to identify a user across more than one page request and to store information about that user. • HttpSession session = request.getSession(); • setAttribute(String name, Object value) This method binds an object to this session, using the name specified.

  25. Setting Session variable • HttpSession session= request.getSession(); • session.setAttribute("name", request.getParameter("uname")); Getting Session Variable • HttpSession session=request.getSession(); • String n=(String) session.getAttribute("name");

  26. Session & Cookies • session: a series of transaction between user and application • session state: the short-term memory that the application needs in order to maintain the session • e.g., shopping cart, user-id • cookie: a small file stored by the client at the instruction of the server

  27. Cookies • text files stored on the client computer and they are kept for various information tracking purpose. Setting Cookie • Cookie cookie =newCookie("key","value"); • cookie.setMaxAge(60*60*24); • response.addCookie(cookie);

  28. Getting Cookies • Use getCookies( ) method of HttpServletRequest • Cookie[] cookies =null; • cookies = request.getCookies(); • cookies[i].getValue(); • Set cookie age as zero using setMaxAge() method to delete an existing cookie.

  29. Application Context • Share data for the whole application use servletcontext object • ServletContext context=getServletContext(); • context.setAttribute("name", p);

  30. Forwarding Request • RequestDispatcher object • Or void sendRedirect(String location) of response object. • response.sendRedirect("http://amritapuri.org"); if(request.getParameter("name").equals("amma")) response.sendRedirect("http://amritapuri.org"); else response.sendRedirect("http://amrita.edu");

  31. RequestDispatcher • The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. • forward () : Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. • include () : Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

  32. if(request.getParameter("name").equals("amma")) { RequestDispatcher rd= request.getRequestDispatcher("index.html"); rd.forward(request, response); } else { PrintWriter out=response.getWriter(); out.print("UserName Error!"); RequestDispatcher rd= request.getRequestDispatcher("test.html"); rd.include(request, response); }

  33. Servlet Deployment • a servlet application is located at the path <Tomcat-installation-directory>/webapps/ROOT and • the class file would reside in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.

  34. web.xml • <servlet> • <servlet-name>HelloWorld</servlet-name> • <servlet-class>HelloWorld</servlet-class> • </servlet> • <servlet-mapping> • <servlet-name>HelloWorld</servlet-name> • <url-pattern>/HelloWorld</url-pattern> • </servlet-mapping>

  35. @WebServlet • The @WebServlet annotation is used to declare a servlet. • The annotated class must extend the javax.servlet.http.HttpServlet class @WebServlet(description = “Servlet", urlPatterns = { "/MCAServlet" }) @WebServlet(urlPatterns = {"/sendFile", "/uploadFile"})

  36. JSP Overview - Servlets v/s JSPs JSPs : Java within HTML Presentation logic Servlets : HTML within Java business logic public void doGet(request, response) { PrintWriter out = response.getWriter(); String name = request.getParameter(name); out.println(“<html><body>”); out.println("Hello” + name); out.println(“</body></html>”); } <html> <body> <% String name = request.getParameter(name); %> Hello <%= name %> </body> </html>

  37. JSP Overview - What is a JSP • In the end, a JSP is just a Servlet. Is loaded and Initialized as Is translated to Compiles to writes JSP Import javax. servlet. HttpServlet.* 0010 0001 1100 1001 0001 0011 Servlet MyJsp_jsp Servlet MyJsp.jsp MyJsp_jsp.java MyJsp_jsp.class

  38. JSP Elements • Scriptlets • <% int I = 10; %> • <% Dog d = new Dog(); %> • Expressions • <%= i %> • <%= d.getName() %> • Declarations • <%! int i=10; %> • <%! void display() { System.out.println(“Hello”); } %> • Directives • Pages - <%@ page import=“foo.*, bar.*” %> • include - <%@ include file=“/foo/myJsp.jsp” %> • taglib - <%@ taglib uri=“Tags” prefix=“cool” %> = out.println(i); = out.println(d.getName());

  39. JSP Elements – JSP to Servlet import javax.servlet.HttpServlet.* import foo.*; public class MyJsp_jsp extends HttpServlet { int count = 0; public void display() { out.println(“Hello”); } public void _jspService(req, res) { int i = 0; out.println(“<html>\r<body>”); out.println(“Hello! Welcome”); } } <%@ page import=“foo.*” %> <html> <body> <% int i = 10; %> <%! int count = 0; %> Hello! Welcome <%! Public void display() { out.println(“Hello”); } %> </body> </html> • Where does the JSP code land in the Servlet?

More Related