Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java Servlets


Published on

Short presentation about Java Servlets.

Published in: Technology
  • Be the first to comment

Java Servlets

  1. 1. Java Servlets Svetlin Nakov Borislava Spasova
  2. 2. Contents <ul><li>Java Servlets Technology Overview </li></ul><ul><ul><li>What is a Java Servlet? </li></ul></ul><ul><ul><li>Servlet Services </li></ul></ul><ul><ul><li>Why Use Servlets? </li></ul></ul><ul><ul><li>Time Servlet – Example </li></ul></ul><ul><ul><li>Deploying Servlets on Eclipse IDE </li></ul></ul><ul><li>Servlets Architecture </li></ul><ul><ul><li>Servlets API </li></ul></ul><ul><ul><li>Servlets Life-Cycle </li></ul></ul>
  3. 3. Contents (2) <ul><li>Servlet Examples </li></ul><ul><ul><li>Processing Parameters – Hello Servlet </li></ul></ul><ul><ul><li>Image Counter Servlet </li></ul></ul><ul><li>Using Sessions </li></ul><ul><ul><li>What is a Session? </li></ul></ul><ul><ul><li>The Sessions API </li></ul></ul><ul><ul><li>Session Timeout </li></ul></ul><ul><li>Session Examples </li></ul><ul><ul><li>Login / Logout Application </li></ul></ul><ul><ul><li>The Browser's Cache Problems </li></ul></ul>
  4. 4. Java Servlets Technology Overview
  5. 5. What is a Java Servlet? <ul><li>Java Servlets are: </li></ul><ul><ul><li>Technology for generating dynamic Web pages (like PHP, ASP, ASP.NET, ...) </li></ul></ul><ul><ul><li>P rotocol and platform-independent server side components, written in Java , which extend the standard Web servers </li></ul></ul><ul><ul><li>Java programs that serve HTTP requests </li></ul></ul><ul><li>The HttpServlet class </li></ul><ul><ul><li>Provides d ynamic Web content generation (HTML, XML, …) </li></ul></ul>
  6. 6. What is a Java Servlet? (2) <ul><li>Servlets </li></ul><ul><ul><li>P rovide a general framework for services built on the request-response paradigm </li></ul></ul><ul><ul><li>Portable to any Java application server </li></ul></ul><ul><ul><li>Have access to the entire family of Java and Java EE APIs </li></ul></ul><ul><ul><ul><li>JDBC, Persistence, EJB, JMS, JAX-WS, JTA, JTS, RMI, JNDI, JAXP, ... </li></ul></ul></ul><ul><ul><li>Fundamental part of all Java Web application technologies (JSP, JSF, ...) </li></ul></ul>
  7. 7. Servlet Services <ul><li>Java Servlets provide many useful services </li></ul><ul><ul><li>Provides low-level API for building Internet services </li></ul></ul><ul><ul><li>Serves as foundation to JavaServer Pages (JSP) and JavaServer Faces (JSF) technologies </li></ul></ul><ul><ul><li>Can deliver multiple types of data to any client </li></ul></ul><ul><ul><ul><li>XML, HTML, WML, GIF, etc... </li></ul></ul></ul><ul><ul><li>Can serve as “Controller” of JSP/Servlet application </li></ul></ul>
  8. 8. Why Use Servlets? <ul><li>Portability </li></ul><ul><ul><li>Write once, serve everywhere </li></ul></ul><ul><li>Power </li></ul><ul><ul><li>Can take advantage of all Java APIs </li></ul></ul><ul><li>Elegance </li></ul><ul><ul><li>Simplicity due to abstraction </li></ul></ul><ul><li>Efficiency & Endurance </li></ul><ul><ul><li>Highly scalable </li></ul></ul>
  9. 9. Why Use Servlets? (2) <ul><li>Safety </li></ul><ul><ul><li>Strong type-checking </li></ul></ul><ul><ul><li>Memory management </li></ul></ul><ul><li>Integration </li></ul><ul><ul><li>Servlets tightly coupled with server </li></ul></ul><ul><li>Extensibility & Flexibility </li></ul><ul><ul><li>Servlets designed to be easily extensible, though currently optimized for HTTP uses </li></ul></ul><ul><ul><li>Flexible invocation of servlet (SSI, servlet-chaining, filters, etc.) </li></ul></ul>
  10. 10. Time Servlet – Example <ul><li>import*; </li></ul><ul><li>import javax.servlet.*; </li></ul><ul><li>import javax.servlet.http.*; </li></ul><ul><li>public class Time Servlet extends HttpServlet { </li></ul><ul><li>public void doGet(HttpServletRequest aRequest, </li></ul><ul><li>HttpServletResponse aResponse) </li></ul><ul><li>throws ServletException, IOException { </li></ul><ul><li>PrintWriter out = aResponse.getWriter(); </li></ul><ul><li>out.println(&quot;<HTML>&quot;); </li></ul><ul><li>out.println(&quot;The time is: &quot; + </li></ul><ul><li>new java.util.Date()); </li></ul><ul><li>out.println(&quot;</HTML>&quot;); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  11. 11. Deploying Servlets on Eclipse IDE <ul><li>First create new Web application </li></ul>
  12. 12. Deploying Servlets on Eclipse IDE (2) <ul><li>Add new servlet to the Web application </li></ul>
  13. 13. Deploying Servlets on Eclipse IDE (3) <ul><li>Run the servlet </li></ul>
  14. 14. Deploying Servlets on Eclipse IDE (4) <ul><li>The servlet in action </li></ul>
  15. 15. Java Servlets Technical Architecture
  16. 16. Servlets Architecture <ul><li>The HttpServlet class </li></ul><ul><ul><li>Serves client's HTTP requests </li></ul></ul><ul><li>For each of the HTTP methods, GET, POST, and others , there is c orresponding method : </li></ul><ul><ul><li>doGet ( … ) – serves HTTP GET requests </li></ul></ul><ul><ul><li>doPost ( … ) – serves HTTP POST requests </li></ul></ul><ul><ul><li>doPut ( … ) , doHead ( … ) , doDelete ( … ) , doTrace ( … ) , doOptions ( … ) </li></ul></ul><ul><li>The Servlet usually must implement one of the first two methods or the service( … ) method </li></ul>
  17. 17. Servlets Architecture (2) <ul><li>The HttpServletRequest object </li></ul><ul><ul><li>Contains the request data from the client </li></ul></ul><ul><ul><ul><li>HTTP request headers </li></ul></ul></ul><ul><ul><ul><li>Form data and query parameters </li></ul></ul></ul><ul><ul><ul><li>Other client data (cookies, path, etc.) </li></ul></ul></ul><ul><li>The HttpServletResponse object </li></ul><ul><ul><li>Encapsulates data sent back to client </li></ul></ul><ul><ul><ul><li>HTTP response headers (content type, cookies, etc.) </li></ul></ul></ul><ul><ul><ul><li>Response body (as OutputStream ) </li></ul></ul></ul>
  18. 18. Servlets Architecture (3) <ul><li>The HTTP GET method is used when: </li></ul><ul><ul><li>The processing of the request does not change the state of the server </li></ul></ul><ul><ul><li>The amount of form data is small </li></ul></ul><ul><ul><li>You want to allow the request to be bookmarked </li></ul></ul><ul><li>The HTTP POST method is used when: </li></ul><ul><ul><li>The processing of the request changes the state of the server, e.g. storing data in a DB </li></ul></ul><ul><ul><li>The amount of form data is large </li></ul></ul><ul><ul><li>The contents of the data should not be visible in the URL (for example, passwords) </li></ul></ul>
  19. 19. Servlets API <ul><li>The most important servlet functionality: </li></ul><ul><ul><li>Retrieve the HTML form parameters from the request (both GET and POST parameters) </li></ul></ul><ul><ul><li>Retrieve a servlet initialization parameter </li></ul></ul><ul><ul><li>Retrieve HTTP request header information </li></ul></ul>HttpServletRequest.getParameter( String ) ServletConfig.getInitParameter () HttpServletRequest.getHeader( String )
  20. 20. Servlets API (2) <ul><ul><li>Set an HTTP response header / content type </li></ul></ul><ul><ul><li>Acquire a text stream for the response </li></ul></ul><ul><ul><li>Acquire a binary stream for the response </li></ul></ul><ul><ul><li>Redirect an HTTP request to another URL </li></ul></ul>HttpServletResponse.setHeader (<name>, <value>) / HttpServletResponse.setContentType( String ) HttpServletResponse.getWriter() HttpServletResponse . getOutputStream() HttpServletResponse.sendRedirect()
  21. 21. Servlets Life-Cycle <ul><li>You can provide an implementation of these methods in HttpServlet descendent classes to manipulate the servlet instance and the resources it depends on </li></ul><ul><li>The Web container manages the life cycle of servlet instances </li></ul><ul><li>The life-cycle methods should not be called by your code </li></ul>init() ...() service() doGet() doPost() doDelete() destroy() doPut() New Destroyed Running
  22. 22. The init() Method <ul><li>Called by the Web container when the servlet instance is first created </li></ul><ul><li>The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed </li></ul><ul><li>Override the init() method when: </li></ul><ul><ul><li>You need to create or open any servlet-specific resources that you need for processing user requests </li></ul></ul><ul><ul><li>You need to initialize the state of the servlet </li></ul></ul>
  23. 23. The service() Method <ul><li>Called by the Web container to process a user request </li></ul><ul><li>Dispatches the HTTP requests to doGet( … ) , doPost( … ) , etc. depending on the HTTP request method (GET, POST, and so on) </li></ul><ul><ul><li>Sends the result as HTTP response </li></ul></ul><ul><li>Usually we do not need to override this method </li></ul>
  24. 24. The destroy() Method <ul><li>Called by the Web container when the servlet instance is being eliminated </li></ul><ul><li>The Servlet specification guarantees that all requests will be completely processed before this method is called </li></ul><ul><li>Override the destroy method when: </li></ul><ul><ul><li>You need to release any servlet-specific resources that you had opened in the init() method </li></ul></ul><ul><ul><li>You need to persist the state of the servlet </li></ul></ul>
  25. 25. Java Servlets Examples
  26. 26. Processing Parameters – Hello Servlet <ul><li>We want to create a servlet that takes an user name as a parameter and says &quot;Hello, <user_name>&quot; </li></ul><ul><li>We need HTML form with a text field </li></ul><ul><li>The servlet can later retrieve the value entered in the form field </li></ul><form method=&quot; GET or POST &quot; action=&quot; the servlet &quot;> <input type=&quot;text&quot; name=&quot; user_name &quot;> </form> String n ame = r equest.getParameter(&quot;user_name&quot;);
  27. 27. Hello Servlet – Example <ul><li><html><body> </li></ul><ul><li><form method=&quot;GET&quot; action=&quot;HelloServlet&quot;> </li></ul><ul><li>Please enter your name: </li></ul><ul><li><input type=&quot;text&quot; name=&quot; user_name &quot;> </li></ul><ul><li><input type=&quot;submit&quot; value=&quot;OK&quot;> </li></ul><ul><li></form> </li></ul><ul><li></body></html> </li></ul>HelloForm.html import*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { Hello Servlet . java
  28. 28. Hello Servlet – Example public void doGet(HttpServletRequest r equest, HttpServletResponse r esponse) throws ServletException, IOException { r esponse.setContentType(&quot;text/html&quot;); ServletOutputStream out = r esponse.getOutputStream(); String userName = r equest.getParameter(&quot;user_name&quot;); out.println(&quot;<html> <head> &quot;); out.println(&quot;t<title>Hello Servlet</title>&quot;); out.println(&quot;</head><body>&quot;); out.println(&quot;t<h1>Hello, &quot; + userName + &quot;</h1>&quot;); out.println(&quot;</body></html>&quot;); } Hello Servlet . java
  29. 29. Creating The Form in Eclipse IDE <ul><li>Create new HTML form </li></ul>
  30. 30. Creating New Servlet in Eclipse IDE <ul><li>Create new Servlet </li></ul>
  31. 31. Hello Servlet in Action
  32. 32. Hello Servlet – HTTP Request <ul><li>What happens when the user enters his name? </li></ul><ul><ul><li>Internet Explorer (IE) sends the following HTTP request to Tomcat </li></ul></ul>GET /FirstWebApp/HelloServlet?user_name=Nakov HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg,image/pjpeg, application/, application/, application/msword, application/x-shockwave-flash, */* Accept-Language: bg Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461) Host: nakov:808 4 Connection: Keep-Alive
  33. 33. Hello Servlet – HTTP Response <ul><li>What happens when Tomcat receive and process the HTTP request </li></ul><ul><ul><li>Tomcat sends the following HTTP response to Internet Explorer </li></ul></ul>HTTP/1.1 200 OK Content-Length: 100 Date: Fri, 26 Mar 200 6 10:06:28 GMT Server: Apache-Coyote/1.1 <html><head> <title>Hello Servlet</title> </head><body> <h1>Hello, Nakov</h1> </body></html>
  34. 34. Image Counter Servlet <ul><li>We want to create a servlet that displays an image counter (as JPEG image) </li></ul><ul><li>The servlet should maintain an internal counter </li></ul><ul><ul><li>Can be initialized in the init() method and incremented in the doGet () method </li></ul></ul><ul><li>It should produce binary output (the JPEG) image </li></ul><ul><ul><li>The content type should be set to &quot;image/jpeg&quot; </li></ul></ul>
  35. 35. Image Counter Servlet (2) import javax.servlet.*; import javax.servlet.http.*; ... public class ImageCounterServlet extends HttpServlet { private String mStartDate; private int mVisitCounter; public void init() { mStartDate = (new Date()).toString(); mVisitCounter = 0; } public BufferedImage createImage(String msg) { ... }
  36. 36. Image Counter Servlet (3) public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String msg; synchronized(this) { mVisitCounter++; msg = &quot;&quot; + mVisitCounter + &quot; visits since &quot; + mStartDate; } BufferedImage image = createImage(msg); response.setContentType(&quot;image/jpeg&quot;); OutputStream out = response.getOutputStream(); // Encode the image in JPEG format and // write the image to the output stream } }
  37. 37. Image Counter Servlet in Action
  38. 38. Using Sessions
  39. 39. What is a Session? <ul><li>A session is a state associated with particular user that is maintained at the server side </li></ul><ul><ul><li>Sessions persist between the HTTP requests </li></ul></ul><ul><li>Sessions e nable creating applications that depend on individual user data. For example: </li></ul><ul><ul><li>Login / logout functionality </li></ul></ul><ul><ul><li>Wizard pages </li></ul></ul><ul><ul><li>Shopping c arts </li></ul></ul><ul><ul><li>Personalization s ervices </li></ul></ul><ul><ul><li>Maintaining state about the user’s preferences </li></ul></ul>
  40. 40. Sessions in Servlets <ul><li>Servlets include a built-in Session s API </li></ul><ul><ul><li>Sessions are maintained automatically, with no additional coding </li></ul></ul><ul><ul><li>The Web container associates an unique HttpSession object to each different client </li></ul></ul><ul><ul><li>Different clients have different session objects at the server </li></ul></ul><ul><ul><li>Requests from the same client have the same session object </li></ul></ul><ul><ul><li>Sessions can store various data </li></ul></ul>
  41. 41. The Sessions API <ul><li>The sessions API allows </li></ul><ul><ul><li>To get the HttpSession object from the HTTPServletRequest object </li></ul></ul><ul><ul><li>Extract data from the user’s session object </li></ul></ul><ul><ul><li>Append data to the user’s session object </li></ul></ul><ul><ul><li>Extract meta-information about the session object, e.g. when was the session created </li></ul></ul>
  42. 42. Getting The Session Object <ul><li>To get the session object use the method HttpServletRequest.getSession() </li></ul><ul><li>Example: </li></ul><ul><li>If the user already has a session, the existing session is returned </li></ul><ul><li>If no session still exists, a new one is created and returned </li></ul><ul><li>If you want to know if this is a new session, call the isNew() method </li></ul>HttpSession session = request.getSession();
  43. 43. Behind T he Scenes <ul><li>When you call getSession () each user is automatically assigned a unique Session ID </li></ul><ul><li>How does this Session ID get to the user? </li></ul><ul><ul><li>Option 1: If the browser supports cookies, the servlet will automatically create a session cookie, and store the session ID within the cookie </li></ul></ul><ul><ul><ul><li>In Tomcat, the cookie is called JSESSIONID </li></ul></ul></ul><ul><ul><li>Option 2: If the browser does not support cookies, the servlet will try to extract the session ID from the URL </li></ul></ul>
  44. 44. Extracting Data From The Session <ul><li>The s ession object works like a HashMap </li></ul><ul><ul><li>E nables storing any type of Java object </li></ul></ul><ul><ul><li>Objects are stored by key (like in hash tables) </li></ul></ul><ul><li>Extracting existing object: </li></ul><ul><li>Getting a list of all “keys” associated with the session </li></ul>Integer accessCount = (Integer) session.getAttribute(&quot;accessCount&quot;); Enumeration attributes = request.getAttributeNames();
  45. 45. Storing Data In The Session <ul><li>We can store data in the session object for using it later </li></ul><ul><li>Objects in the session can be removed when not needed more </li></ul>HttpSession session = request.getSession(); session.setAttribute(&quot;name&quot;, &quot;Svetlin Nakov&quot;); session. remove Attribute(&quot;name&quot;);
  46. 46. Getting Additional Session Information <ul><li>Getting the unique session ID associated with this user, e.g. gj9xswvw9p </li></ul><ul><li>Checking if the session was just created </li></ul><ul><li>Checking when the session was first created </li></ul><ul><li>Checking when the session was last active </li></ul>public boolean isNew(); public String getId(); public long getLastAccessedTime(); public long getCreationTime();
  47. 47. Session Timeout <ul><li>We can get the maximal session validity interval ( in seconds ) </li></ul><ul><ul><li>After such interval of inactivity the session is automatically invalidated </li></ul></ul><ul><li>We can modify the maximal inactivity interval </li></ul><ul><ul><li>A negative value specifies that the session should never time out </li></ul></ul>public int getMaxInactiveInterval(); public void setMaxInactiveInterval (int seconds) ;
  48. 48. Terminating Sessions <ul><li>To terminate session manually use the method: </li></ul><ul><ul><li>Typically done during the &quot;user logout&quot; </li></ul></ul><ul><li>The session can become invalid not only manually </li></ul><ul><ul><li>Sessions can expire automatically due to inactivity </li></ul></ul>public void invalidate() ;
  49. 49. Login / Logout – Example <ul><li>We want to create a simple Web application that restricts the access by login form </li></ul><ul><ul><li>We will use sessions to store information about the authenticated users </li></ul></ul><ul><ul><ul><li>We will use the key &quot;username&quot; </li></ul></ul></ul><ul><ul><ul><li>When it present, there is a logged in user </li></ul></ul></ul><ul><ul><li>During the login we will add the user name in the session </li></ul></ul><ul><ul><li>Logout will invalidate the session </li></ul></ul><ul><ul><li>The main servlet will check the current user </li></ul></ul>
  50. 50. Login Form <html> <head><title>Login</title></head> <body> <form method=&quot;POST&quot; action=&quot;LoginServlet&quot;> Please login:<br> Username: <input type=&quot;text&quot; name=&quot;username&quot;><br> Password: <input type=&quot;password&quot; name=&quot;password&quot;><br> <input type=&quot;submit&quot; value=&quot;Login&quot;> </form> </body> </html> LoginForm.html
  51. 51. Login Servlet public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String username = req.getParameter(&quot;username&quot;); String password = req.getParameter(&quot;password&quot;); PrintWriter out = resp.getWriter(); if (isLoginValid(username, password)) { HttpSession session = req.getSession(); session.setAttribute(&quot;USER&quot;, username); response.sendRedirect(&quot;MainServlet&quot;); } else { response.sendRedirect(&quot;InvalidLogin.html&quot;); } } } Login Servlet . java
  52. 52. Main Servlet public class MainServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = request.getSession(); String userName = (String) s ession.getAttribute(&quot;USER&quot;); if (userName != null) { response.setContentType(&quot;text/html&quot;); ServletOutputStream out = resp.getOutputStream(); out.println(&quot;<html> <body><h1> &quot;); out.println(&quot;Hello, &quot; + userName + &quot;! &quot;); out.println(&quot; </h1> </body></html>&quot;); } else { response.sendRedirect(&quot;LoginForm.html&quot;); } } }
  53. 53. Logout Servlet public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); response.setContentType(&quot;text/html&quot;); ServletOutputStream out = response.getOutputStream(); out.println(&quot;<html><head>&quot;); out.println(&quot;<title>Logout</title></head>&quot;); out.println(&quot;<body>&quot;); out.println(&quot;<h1>Logout successfull.</h1>&quot;); out.println(&quot;</body></html>&quot;); } }
  54. 54. Invalid Login Page <html> <head> <title>Error</title> </head> <body> <h1>Invalid login!</h1> Please <a href=&quot;LoginForm.html&quot;>try again</a>. </body> </html> InvalidLogin.html
  55. 55. The Browser's Cache Problems <ul><li>Most Web browsers use caching of the displayed pages and images </li></ul><ul><ul><li>This can cause the user to see old state of the pages </li></ul></ul><ul><ul><ul><li>Seems like a bug in the application </li></ul></ul></ul><ul><li>To prevent showing the old state we need to disable the browser cache: </li></ul>response.setHeader(&quot;Pragma&quot;, &quot;No-cache&quot;); response.setDateHeader(&quot;Expires&quot;, 0); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;);
  56. 56. Problems <ul><li>Create a servlet that prints in a table the numbers from 1 to 1000 and their square root. </li></ul><ul><li>Create a servlet that takes as parameters two integer numbers and calculates their sum. </li></ul><ul><li>Create a HTML form that invokes the servlet. Try to use GET and POST methods. </li></ul><ul><li>Implement a servlet that plays the &quot;Number guess game&quot;. When the client first invoke the servlet it generates a random number in the range [1..100]. The user is asked to guess this number. At each guess the servlet says only &quot;greater&quot; or &quot;smaller&quot;. The game ends when the user tell the number. </li></ul>
  57. 57. Homework <ul><li>Create a servlet that takes as a parameter a number and displays it as image that is hard to be recognized by OCR software. The image should have intentionally inserted defects. </li></ul><ul><li>Create an HTML form and a servlet for performing conversions of distances from one metric to another. The metrics that should be supported are: meter, centimeter, kilometer, foot, inch, yard, mile. </li></ul><ul><li>1 cm = 0.01 meters 1 km = 1000 meters </li></ul><ul><li>1 foot = 0.3048 meters 1 inch = 0.0254 meters </li></ul><ul><li>1 yard = 0.9144 meters 1 mile = 1609.344 meters </li></ul>
  58. 58. Homework (2) <ul><li>Create a sequence of HTML forms and servlets that allow entering information about a student. The information is entered in 3 steps in 3 separate forms: </li></ul><ul><li>Step 1: First name, last name, age </li></ul><ul><li>Step 2: Address (country, town, street) </li></ul><ul><li>Step 3: University, faculty, specialty </li></ul><ul><li>The data entered in the 3 steps should be stored in the session and finally displayed. </li></ul><ul><li>Create a servlet that reads an image (from WEB-INFimglogo.gif ) and returns it. </li></ul>