Presentation is loading. Please wait.

Presentation is loading. Please wait.

* 07/16/96 Java Servlets (c) 2006 National Academy for Software Development - http://academy.devbg.org*

Similar presentations


Presentation on theme: "* 07/16/96 Java Servlets (c) 2006 National Academy for Software Development - http://academy.devbg.org*"— Presentation transcript:

1 * 07/16/96 Java Servlets (c) 2006 National Academy for Software Development -

2 Overview Servlet technology is used to create web application that
resides at the server side and generates dynamic web page Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a server-side programming language What is a Servlet? A technology that is used to create dynamic web applications An API that provides many interfaces and classes An interface that can be implemented for creating server-side program A class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests A web component that is deployed on the server to create dynamic web page

3 Servlet vs. CGI A Servlet has:
Better performance: because it creates a thread for each request not process. Portability: because it uses java language. Robustness: because it is managed by the JVM, thus we don't need to worry about memory leak, garbage collection etc.

4 Servlet

5 Static vs. Dynamic Websites
Static Website Dynamic Website Prebuilt content is same every time the page is loaded Content is generated quickly and changes regularly It uses the HTML code for developing a website It uses the server side languages such as: PHP, SERVLET, JSP, and ASP.NET etc. for development It sends exactly the same response for every request It may generate different HTML for each of the request The content is only changed when someone publishes and updates the file (sends it to the web server) The page contains "server-side" code that allows the server to generate the unique content when the page is loaded

6 Tomcat vs. Jboss vs. Glassfish
Tomcat: Run by Apache community - Open source and has two flavors Tomcat - Web profile - light weight which is only servlet container and does not support Java EE features like Enterprise Java Bean (EJB), Java Message Service (JMS) etc. Tomcat EE - This is a certified Java EE container, this supports all Java EE technologies. Jboss: Run by RedHat This is a full stack support for JavaEE and it is a certified Java EE container This includes Tomcat as web container internally Glassfish: Run by Oracle A full stack certified Java EE Container. It has its own web container (not Tomcat) Comes from Oracle itself, it would support the latest spec

7 Servlet Container It is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss. Out-of-process: The web server and servlet container are different programs which are run in a different processes. For performing the communications between them, web server uses the plug-in provided by the servlet container.

8 Servlet Container It is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: Servlet Container performs many operations that are given below: Life Cycle Management Multithreaded support Object Pooling Security etc.

9 Java Servlets Technology Overview * 07/16/96
(c) 2006 National Academy for Software Development -

10 What is a Java Servlet? Java Servlets are: The HttpServlet class
Technology for generating dynamic Web pages (like PHP, ASP, ASP.NET, ...) Protocol and platform-independent server side components, written in Java, which extend the standard Web servers Java programs that serve HTTP requests The HttpServlet class Provides dynamic Web content generation (HTML, XML, …)

11 What is a Java Servlet? (2)
Servlets Provide a general framework for services built on the: request-response paradigm Portable to any Java application server Have access to the entire family of Java and Java EE APIs JDBC, Persistence, EJB, JMS, JAX-WS, JTA, JTS, RMI, JNDI, JAXP, ... Fundamental part of all Java Web application technologies (JSP, JSF, ...)

12 Servlet Services Java Servlets provide many useful services
Provides low-level API for building Internet services Serves as foundation to Java Server Pages (JSP) and Java Server Faces (JSF) technologies Can deliver multiple types of data to any client XML, HTML, GIF, etc... Can serve as “Controller” of JSP/Servlet application

13 Why Use Servlets? Portability Power Elegance Efficiency & Endurance
* 07/16/96 Why Use Servlets? Portability Write once, serve everywhere Power Can take advantage of all Java APIs Elegance Simplicity due to abstraction Efficiency & Endurance Highly scalable (c) 2006 National Academy for Software Development -

14 Why Use Servlets? (2) Safety Integration Extensibility & Flexibility
* 07/16/96 Why Use Servlets? (2) Safety Strong type-checking Memory management Integration Servlets tightly coupled with server Extensibility & Flexibility Servlets designed to be easily extensible, though currently optimized for HTTP uses Flexible invocation of servlet (servlet-chaining, filters) (c) 2006 National Academy for Software Development -

15 Time Servlet – Example import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TimeServlet extends HttpServlet { public void doGet( HttpServletRequest aRequest, HttpServletResponse aResponse ) throws ServletException, IOException { PrintWriter out = aResponse.getWriter(); out.println("<HTML>"); out.println("The time is: " + new java.util.Date()); out.println("</HTML>"); }

16 Deploying Servlets on Eclipse IDE
First create new Web application

17 Deploying Servlets on Eclipse IDE (2)
Add new servlet to the Web application

18 Deploying Servlets on Eclipse IDE (4)
The servlet in action

19 Java Servlets Technical Architecture * 07/16/96
(c) 2006 National Academy for Software Development -

20 Servlets Architecture
The HttpServlet class Serves client's HTTP requests For each of the HTTP methods, GET, POST, and others, there is corresponding method: doGet(…) – serves HTTP GET requests doPost(…) – serves HTTP POST requests doPut(…), doHead(…), doDelete(…), doTrace(…), doOptions(…) The Servlet usually must implement one of the first two methods or the service(…) method

21 Servlets Architecture (2)
The HttpServletRequest object Contains the request data from the client HTTP request headers Form data and query parameters Other client data (cookies, path, etc.) The HttpServletResponse object Encapsulates data sent back to client HTTP response headers (content type, cookies, etc.) Response body (as OutputStream)

22 Servlets Architecture (3)
* 07/16/96 Servlets Architecture (3) The HTTP GET method is used when: The processing of the request does not change the state of the server The amount of form data is small You want to allow the request to be bookmarked The HTTP POST method is used when: The processing of the request changes the state of the server e.g. storing data in a DB The amount of form data is large The contents of the data should not be visible in the URL for example passwords Example of HTTP GET: Google search Example of HTTP POST: Login page (c) 2006 National Academy for Software Development -

23 Servlets API The most important servlet functionality:
Retrieve the HTML form parameters from the request (both GET and POST parameters) Retrieve a servlet initialization parameter Retrieve HTTP request header information HttpServletRequest.getParameter(String) ServletConfig.getInitParameter() HttpServletRequest.getHeader(String)

24 Initial Parameters web.xml InitCounter.java
<servlet> <servlet-name>InitCounter</servlet-name> <servlet-class>InitCounter</servlet-class> <!-- This is a servlet init parameter --> <init-param> <param-name>initial</param-name> <param-value>123</param-value> </init-param> </servlet> InitCounter.java public void init() throws ServletException { String initial = getInitParameter("initial"); try { count = Integer.parseInt(initial); } catch (NumberFormatException e) { count = 0; } }

25 Servlets API (2) Set an HTTP response header / content type
Acquire a text stream for the response Acquire a binary stream for the response Redirect an HTTP request to another URL HttpServletResponse.setHeader(<name>, <value>) / HttpServletResponse.setContentType(String) HttpServletResponse.getWriter() HttpServletResponse.getOutputStream() HttpServletResponse.sendRedirect()

26 * 07/16/96 Servlets Life-Cycle The Web container manages the life cycle of servlet instances The life-cycle methods should not be called by your code init() ...() service() doGet() doPost() doDelete() destroy() doPut() New Destroyed Running You can provide an implementation of these methods in HttpServlet descendent classes to manipulate the servlet instance and the resources it depends on (c) 2006 National Academy for Software Development -

27 * 07/16/96 The init() Method Called by the Web container when the servlet instance is first created The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed Override the init() method when: You need to create or open any servlet-specific resources that you need for processing user requests You need to initialize the state of the servlet (c) 2006 National Academy for Software Development -

28 * 07/16/96 The service() Method Called by the Web container to process a user request Dispatches the HTTP requests to one of the : doGet(…), doPost(…), etc. depending on the HTTP request method: GET, POST, and so on Sends the result as HTTP response Usually we do not need to override this method (c) 2006 National Academy for Software Development -

29 * 07/16/96 The destroy() Method Called by the Web container when the servlet instance is being eliminated The Servlet specification guarantees that all requests will be completely processed before this method is called Override the destroy method when: You need to release any servlet-specific resources that you had opened in the init() method You need to persist the state of the servlet (c) 2006 National Academy for Software Development -

30 Java Servlets Examples * 07/16/96
(c) 2006 National Academy for Software Development -

31 Processing Parameters – Hello Servlet
We want to create a servlet that takes an user name as a parameter and says "Hello, <user_name>" We need HTML form with a text field The servlet can later retrieve the value entered in the form field <form method="GET or POST" action="the servlet"> <input type="text" name="user_name"> </form> String name = request.getParameter("user_name");

32 Hello Servlet – Example
HelloForm.html <html><body> <form method="GET" action="HelloServlet"> Please enter your name: <input type="text" name="user_name"> <input type="submit" value="OK"> </form> </body></html> HelloServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet {

33 Hello Servlet – Example
HelloServlet.java public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); ServletOutputStream out= response.getOutputStream(); String userName = request.getParameter("user_name"); out.println("<html><head>"); out.println("\t<title>Hello Servlet</title>"); out.println("</head><body>"); out.println("\t<h1>Hello, " + userName + "</h1>"); out.println("</body></html>"); }

34 Creating The Form in Eclipse IDE
Create new HTML form

35 Creating New Servlet in Eclipse IDE
Create new Servlet

36 Hello Servlet in Action

37 Hello Servlet – HTTP Request
What happens when the user enters his name? The web browser, such as Chrome and Internet Explorer (IE) sends the following HTTP request to Tomcat GET /FirstWebApp/HelloServlet?user_name=Test HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg,image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, 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: Connection: Keep-Alive

38 Hello Servlet – HTTP Response
What happens when Tomcat receive and process the HTTP request Tomcat sends the following HTTP response to Internet Explorer HTTP/ OK Content-Length: 100 Date: Fri, 26 Mar :06:28 GMT Server: Apache-Coyote/1.1 <html><head> <title>Hello Servlet</title> </head><body> <h1>Hello, Test</h1> </body></html>

39 * 07/16/96 Using Sessions (c) 2006 National Academy for Software Development -

40 What is a Session? A session is a state associated with particular user that is maintained at the server side Sessions persist between the HTTP requests Sessions enable creating applications that depend on individual user data. For example: Login / logout functionality Wizard pages Shopping carts Personalization services Maintaining state about the user’s preferences

41 Sessions in Servlets Servlets include a built-in Sessions API
Sessions are maintained automatically, with no additional coding The Web container associates an unique HttpSession object to each different client Different clients have different session objects at the server Requests from the same client have the same session object Sessions can store various data

42 The Sessions API The sessions API allows
To get the HttpSession object from the HTTPServletRequest object Extract data from the user’s session object Append data to the user’s session object Extract meta-information about the session object, e.g. when was the session created

43 Getting The Session Object
To get the session object use the method HttpServletRequest.getSession() Example: If the user already has a session, the existing session is returned If no session still exists, a new one is created and returned If you want to know if this is a new session, call the isNew() method HttpSession session = request.getSession();

44 Behind The Scenes When you call getSession() each user is automatically assigned a unique Session ID How does this Session ID get to the user? Option 1: If the browser supports cookies, the servlet will automatically create a session cookie, and store the session ID within the cookie In Tomcat, the cookie is called JSESSIONID Option 2: If the browser does not support cookies, the servlet will try to extract the session ID from the URL

45 Extracting Data From The Session
* 07/16/96 Extracting Data From The Session The session object works like a HashMap Enables storing any type of Java object Objects are stored by key (like in hash tables) Extracting existing object: Getting a list of all “keys” associated with the session Integer accessCount = (Integer) session.getAttribute("accessCount"); Note: As of Servlet 2.2, the getValue() method is now deprecated. Use getAttribute() instead. Enumeration attributes = request.getAttributeNames(); (c) 2006 National Academy for Software Development -

46 Storing Data In The Session
* 07/16/96 Storing Data In The Session We can store data in the session object for using it later Objects in the session can be removed when not needed more HttpSession session = request.getSession(); session.setAttribute("name", “SE 432"); session.removeAttribute("name"); Note: As of Servlet 2.2, the getValue() method is now deprecated. Use getAttribute() instead. (c) 2006 National Academy for Software Development -

47 Getting Additional Session Information
Getting the unique session ID associated with this user, e.g. gj9xswvw9p Checking if the session was just created Checking when the session was first created Checking when the session was last active public String getId(); public boolean isNew(); public long getCreationTime(); public long getLastAccessedTime();

48 Session Timeout We can get the maximal session validity interval (in seconds) After such interval of inactivity the session is automatically invalidated We can modify the maximal inactivity interval A negative value specifies that the session should never time out public int getMaxInactiveInterval(); public void setMaxInactiveInterval (int seconds);

49 Terminating Sessions To terminate session manually use the method:
Typically done during the "user logout" The session can become invalid not only manually Sessions can expire automatically due to inactivity public void invalidate();

50 Login / Logout – Example
We want to create a simple Web application that restricts the access by login form We will use sessions to store information about the authenticated users We will use the key "username" When it present, there is a logged in user During the login we will add the user name in the session Logout will invalidate the session The main servlet will check the current user

51 Login Form LoginForm.html <html>
<head><title>Login</title></head> <body> <form method="POST" action="LoginServlet"> Please login:<br> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="Login"> </form> </body> </html>

52 Login Servlet LoginServlet.java
public class LoginServlet extends HttpServlet { public void doPost( HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String username = req.getParameter("username"); String password = req.getParameter("password"); PrintWriter out = resp.getWriter(); if (isLoginValid(username, password)) { HttpSession session = req.getSession(); session.setAttribute("USER", username); resp.sendRedirect("MainServlet"); } else { resp.sendRedirect("InvalidLogin.html"); }

53 Main Servlet MainServlet.java
public class MainServlet extends HttpServlet { public void doGet( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); String userName = (String) session.getAttribute("USER"); if (userName != null) { resp.setContentType("text/html"); ServletOutputStream out = resp.getOutputStream(); out.println("<html><body><h1>"); out.println("Hello, " + userName + "! "); out.println("</h1></body></html>"); } else { resp.sendRedirect("LoginForm.html"); } }

54 Logout Servlet LogoutServlet.java
public class LogoutServlet extends HttpServlet { protected void doGet( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.invalidate(); resp.setContentType("text/html"); ServletOutputStream out = resp.getOutputStream(); out.println("<html><head>"); out.println("<title>Logout</title></head>"); out.println("<body>"); out.println("<h1>Logout successfull.</h1>"); out.println("</body></html>"); }

55 Invalid Login Page InvalidLogin.html <html> <head>
<title>Error</title> </head> <body> <h1>Invalid login!</h1> Please <a href="LoginForm.html">try again</a>. </body> </html>

56 The Browser's Cache Problems
Most Web browsers use caching of the displayed pages and images This can cause the user to see old state of the pages Seems like a bug in the application To prevent showing the old state we need to disable the browser cache: response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache");

57 Cookies

58 Cookies in Servlet Advantage of Cookies Disadvantage of Cookies
A cookie is a small piece of information that is persisted between the multiple client requests 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 only. Removed each time the user closes browser. Persistent cookie: Valid for multiple sessions . It is not removed each time the user closes the browser. It is removed only if user logout or signout. Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage of Cookies It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object.

59 Cookie class & methods Constructor Useful Methods of Cookie class:
Cookie(String name, String value) Useful Methods of Cookie class: public void setMaxAge(int expiry) Sets Max age in seconds public String getName() Returns cookie name. public String getValue() Returns cookie value. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie. Other methods public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

60 Filters

61 Servlet Filter A filter is an object that is invoked at the preprocessing and post processing of a request It is mainly used to perform filtering tasks such as: encryption and decryption and input validation The servlet filter is pluggable: i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet. So maintenance cost will be less.

62 Usage of Filter Advantage of Filter recording all incoming requests
logs the IP addresses of the computers from which the requests originate conversion data compression encryption and decryption input validation etc. Advantage of Filter Filter is pluggable. One filter don't have dependency onto another resource. Less Maintenance

63 * 07/16/96 Problems Create a servlet that prints in a table the numbers from 1 to 1000 and their square root. Create a servlet that takes as parameters two integer numbers and calculates their sum. Create a HTML form that invokes the servlet. Try to use GET and POST methods. Implement a servlet that plays the "Number guess game". 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 "greater" or "smaller". The game ends when the user tell the number. (c) 2006 National Academy for Software Development -


Download ppt "* 07/16/96 Java Servlets (c) 2006 National Academy for Software Development - http://academy.devbg.org*"

Similar presentations


Ads by Google