Java Servlets Overview Servlet technology is used to

  • Slides: 63
Download presentation
Java Servlets

Java Servlets

Overview • Servlet technology is used to create web application that • resides at

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

Servlet vs. CGI A Servlet has: • Better performance: because it creates a thread

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.

Servlet

Servlet

Static vs. Dynamic Websites Static Website Dynamic Website • Prebuilt content is same every

Static vs. Dynamic Websites Static Website Dynamic Website • Prebuilt content is same every time the • Content is generated quickly and page is loaded 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 • It may generate different HTML for every request 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

Tomcat vs. Jboss vs. Glassfish • Tomcat: Run by Apache community - Open source

Tomcat vs. Jboss vs. Glassfish • Tomcat: Run by Apache community - Open source and has two flavors 1. 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. 2. Tomcat EE - This is a certified Java EE container, this supports all Java EE technologies. • Jboss: Run by Red. Hat 1. This is a full stack support for Java. EE and it is a certified Java EE container 2. 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

Servlet Container • It is the part of web server which can be run

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: 1. 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 2. 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. 3. 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.

Servlet Container • It is the part of web server which can be run

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: 1. Life Cycle Management 2. Multithreaded support 3. Object Pooling 4. Security 5. etc.

Java Servlets Technology Overview

Java Servlets Technology Overview

What is a Java Servlet? • Java Servlets are: • Technology for generating dynamic

What is a Java Servlet? • Java Servlets are: • Technology for generating dynamic Web pages (like PHP, 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 Http. Servlet class • Provides dynamic Web content generation (HTML, XML, …)

What is a Java Servlet? (2) • Servlets • Provide a general framework for

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, . . . )

Servlet Services • Java Servlets provide many useful services • Provides low-level API for

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

Why Use Servlets? • Portability • Write once, serve everywhere • Power • Can

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

Why Use Servlets? (2) • Safety • Strong type-checking • Memory management • Integration

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)

Time Servlet – Example import java. io. *; import javax. servlet. http. *; public

Time Servlet – Example import java. io. *; import javax. servlet. http. *; public class Time. Servlet extends Http. Servlet { public void do. Get( Http. Servlet. Request a. Request, Http. Servlet. Response a. Response throws Servlet. Exception, IOException { ) Print. Writer out = a. Response. get. Writer(); out. println("<HTML>"); out. println("The time is: " + new java. util. Date()); out. println("</HTML>"); } }

Deploying Servlets on Eclipse IDE • First create new Web application

Deploying Servlets on Eclipse IDE • First create new Web application

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

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

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

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

Java Servlets Technical Architecture

Java Servlets Technical Architecture

Servlets Architecture • The Http. Servlet class • Serves client's HTTP requests • For

Servlets Architecture • The Http. Servlet class • Serves client's HTTP requests • For each of the HTTP methods, GET, POST, and others, there is corresponding method: • do. Get(…) – serves HTTP GET requests • do. Post(…) – serves HTTP POST requests • do. Put(…), do. Head(…), do. Delete(…), do. Trace(…), do. Options(…) • The Servlet usually must implement one of the first two methods or the service(…) method

Servlets Architecture (2) • The Http. Servlet. Request object • Contains the request data

Servlets Architecture (2) • The Http. Servlet. Request object • Contains the request data from the client • HTTP request headers • Form data and query parameters • Other client data (cookies, path, etc. ) • The Http. Servlet. Response object • Encapsulates data sent back to client • HTTP response headers (content type, cookies, etc. ) • Response body (as Output. Stream)

Servlets Architecture (3) • The HTTP GET method is used when: 1. The processing

Servlets Architecture (3) • The HTTP GET method is used when: 1. The processing of the request does not change the state of the server 2. The amount of form data is small 3. You want to allow the request to be bookmarked • The HTTP POST method is used when: 1. The processing of the request changes the state of the server • e. g. storing data in a DB 2. The amount of form data is large 3. The contents of the data should not be visible in the URL • for example passwords

Servlets API • The most important servlet functionality: • Retrieve the HTML form parameters

Servlets API • The most important servlet functionality: • Retrieve the HTML form parameters from the request (both GET and POST parameters) Http. Servlet. Request. get. Parameter(String) • Retrieve a servlet initialization parameter Servlet. Config. get. Init. Parameter() • Retrieve HTTP request header information Http. Servlet. Request. get. Header(String)

web. xml Initial Parameters <servlet> <servlet-name>Init. Counter</servlet-name> <servlet-class>Init. Counter</servlet-class> <!-- This is a servlet

web. xml Initial Parameters <servlet> <servlet-name>Init. Counter</servlet-name> <servlet-class>Init. Counter</servlet-class> <!-- This is a servlet init parameter --> <init-param> <param-name>initial</param-name> <param-value>123</param-value> </init-param> </servlet> Init. Counter. java public void init() throws Servlet. Exception { String initial = get. Init. Parameter("initial"); try { count = Integer. parse. Int(initial); catch (Number. Format. Exception e) { } } count = 0; }

Servlets API (2) • Set an HTTP response header / content type Http. Servlet.

Servlets API (2) • Set an HTTP response header / content type Http. Servlet. Response. set. Header(<name>, <value>) / Http. Servlet. Response. set. Content. Type(String) • Acquire a text stream for the response Http. Servlet. Response. get. Writer() • Acquire a binary stream for the response Http. Servlet. Response. get. Output. Stream() • Redirect an HTTP request to another URL Http. Servlet. Response. send. Redirect()

Servlets Life-Cycle • The Web container manages the life cycle of servlet instances •

Servlets Life-Cycle • The Web container manages the life cycle of servlet instances • The life-cycle methods should not be called by your code New init() Destroyed Running destroy() service() do. Get() . . . () do. Delete() do. Post() do. Put() • You can provide an implementation of these methods in Http. Servlet descendent classes to manipulate the servlet instance and the resources it depends on

The init() Method • Called by the Web container when the servlet instance is

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: 1. You need to create or open any servlet-specific resources that you need for processing user requests 2. You need to initialize the state of the servlet

The service() Method • Called by the Web container to process a user request

The service() Method • Called by the Web container to process a user request • Dispatches the HTTP requests to one of the : • do. Get(…), • do. Post(…), • 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

The destroy() Method • Called by the Web container when the servlet instance is

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: 1. You need to release any servlet-specific resources that you had opened in the init() method 2. You need to persist the state of the servlet

Java Servlets Examples

Java Servlets Examples

Processing Parameters – Hello Servlet • We want to create a servlet that takes

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 <form method="GET or POST" action="the servlet"> <input type="text" name="user_name"> </form> • The servlet can later retrieve the value entered in the form field String name = request. get. Parameter("user_name");

Hello Servlet – Example Hello. Form. html <html><body> <form method="GET" action="Hello. Servlet"> Please enter

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

Hello Servlet – Example Hello. Servlet. java public void do. Get( Http. Servlet. Request

Hello Servlet – Example Hello. Servlet. java public void do. Get( Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Servlet. Output. Stream out= response. get. Output. Stream(); String user. Name = request. get. Parameter("user_name"); out. println("<html><head>"); out. println("t<title>Hello Servlet</title>"); out. println("</head><body>"); out. println("t<h 1>Hello, " + user. Name + "</h 1>"); out. println("</body></html>"); }

Creating The Form in Eclipse IDE • Create new HTML form

Creating The Form in Eclipse IDE • Create new HTML form

Creating New Servlet in Eclipse IDE • Create new Servlet

Creating New Servlet in Eclipse IDE • Create new Servlet

Hello Servlet in Action

Hello Servlet in Action

Hello Servlet – HTTP Request • What happens when the user enters his name?

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 /First. Web. App/Hello. Servlet? 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-shockwaveflash, */* Accept-Language: bg Accept-Encoding: gzip, deflate User-Agent: Mozilla/4. 0 (compatible; MSIE 6. 0; Windows NT 5. 1; Q 312461) Host: www. just. edu. jo: 8084 Connection: Keep-Alive

Hello Servlet – HTTP Response • What happens when Tomcat receive and process the

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

Using Sessions

Using Sessions

What is a Session? • A session is a state associated with particular user

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

Sessions in Servlets • Servlets include a built-in Sessions API • Sessions are maintained

Sessions in Servlets • Servlets include a built-in Sessions API • Sessions are maintained automatically, with no additional coding • The Web container associates an unique Http. Session 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

The Sessions API • The sessions API allows • To get the Http. Session

The Sessions API • The sessions API allows • To get the Http. Session object from the HTTPServlet. Request 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

Getting The Session Object • To get the session object use the method Http.

Getting The Session Object • To get the session object use the method Http. Servlet. Request. get. Session() • Example: Http. Session session = request. get. Session(); • 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 is. New() method

Behind The Scenes • When you call get. Session() each user is automatically assigned

Behind The Scenes • When you call get. Session() 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

Extracting Data From The Session • The session object works like a Hash. Map

Extracting Data From The Session • The session object works like a Hash. Map • Enables storing any type of Java object • Objects are stored by key (like in hash tables) • Extracting existing object: Integer access. Count = (Integer) session. get. Attribute("access. Count"); • Getting a list of all “keys” associated with the session Enumeration attributes = request. get. Attribute. Names();

Storing Data In The Session • We can store data in the session object

Storing Data In The Session • We can store data in the session object for using it later Http. Session session = request. get. Session(); session. set. Attribute("name", “SE 432"); • Objects in the session can be removed when not needed more session. remove. Attribute("name");

Getting Additional Session Information • Getting the unique session ID associated with this user,

Getting Additional Session Information • Getting the unique session ID associated with this user, e. g. gj 9 xswvw 9 p public String get. Id(); • Checking if the session was just created public boolean is. New(); • Checking when the session was first created public long get. Creation. Time(); • Checking when the session was last active public long get. Last. Accessed. Time();

Session Timeout • We can get the maximal session validity interval (in seconds) public

Session Timeout • We can get the maximal session validity interval (in seconds) public int get. Max. Inactive. Interval(); • After such interval of inactivity the session is automatically invalidated • We can modify the maximal inactivity interval public void set. Max. Inactive. Interval (int seconds); • A negative value specifies that the session should never time out

Terminating Sessions • To terminate session manually use the method: public void invalidate(); •

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

Login / Logout – Example • We want to create a simple Web application

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

Login Form Login. Form. html <html> <head><title>Login</title></head> <body> <form method="POST" action="Login. Servlet"> Please login:

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

Login Servlet Login. Servlet. java public class Login. Servlet extends Http. Servlet { public

Login Servlet Login. Servlet. java public class Login. Servlet extends Http. Servlet { public void do. Post( Http. Servlet. Request req, Http. Servlet. Response resp) throws IOException, Servlet. Exception { String username = req. get. Parameter("username"); String password = req. get. Parameter("password"); Print. Writer out = resp. get. Writer(); if (is. Login. Valid(username, password)) { Http. Session session = req. get. Session(); session. set. Attribute("USER", username); resp. send. Redirect("Main. Servlet"); } else { resp. send. Redirect("Invalid. Login. html"); } } }

Main. Servlet. java Main Servlet public class Main. Servlet extends Http. Servlet { public

Main. Servlet. java Main Servlet public class Main. Servlet extends Http. Servlet { public void do. Get( Http. Servlet. Request req, Http. Servlet. Response resp) throws Servlet. Exception, IOException { Http. Session session = req. get. Session(); String user. Name = (String) session. get. Attribute("USER"); if (user. Name != null) { resp. set. Content. Type("text/html"); Servlet. Output. Stream out = resp. get. Output. Stream(); out. println("<html><body><h 1>"); out. println("Hello, " + user. Name + "! "); out. println("</h 1></body></html>"); } else { resp. send. Redirect("Login. Form. html"); } } }

Logout Servlet Logout. Servlet. java public class Logout. Servlet extends Http. Servlet { protected

Logout Servlet Logout. Servlet. java public class Logout. Servlet extends Http. Servlet { protected void do. Get( Http. Servlet. Request req, Http. Servlet. Response resp) throws Servlet. Exception, IOException { Http. Session session = req. get. Session(); session. invalidate(); resp. set. Content. Type("text/html"); Servlet. Output. Stream out = resp. get. Output. Stream(); out. println("<html><head>"); out. println("<title>Logout</title></head>"); out. println("<body>"); out. println("<h 1>Logout successfull. </h 1>"); out. println("</body></html>"); } }

Invalid Login Page Invalid. Login. html <html> <head> <title>Error</title> </head> <body> <h 1>Invalid login!</h

Invalid Login Page Invalid. Login. html <html> <head> <title>Error</title> </head> <body> <h 1>Invalid login!</h 1> Please <a href="Login. Form. html">try again</a>. </body> </html>

The Browser's Cache Problems • Most Web browsers use caching of the displayed pages

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. set. Header("Pragma", "No-cache"); response. set. Date. Header("Expires", 0); response. set. Header("Cache-Control", "no-cache");

Cookies

Cookies

Cookies in Servlet • A cookie is a small piece of information that is

Cookies in Servlet • 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.

Cookie class & methods • Constructor • Cookie() • Cookie(String name, String value) •

Cookie class & methods • Constructor • Cookie() • Cookie(String name, String value) • Useful Methods of Cookie class: • • • public void set. Max. Age(int expiry) Sets Max age in seconds public String get. Name() Returns cookie name. public String get. Value() Returns cookie value. public void set. Name(String name) changes the name of the cookie. public void set. Value(String value) changes the value of the cookie. • Other methods • public void add. Cookie(Cookie ck): method of Http. Servlet. Response interface is used to add cookie in response object. • public Cookie[] get. Cookies(): method of Http. Servlet. Request interface is used to return all the cookies from the browser.

Filters

Filters

Servlet Filter • A filter is an object that is invoked at the preprocessing

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.

 • Usage of Filter • • • recording all incoming requests logs the

• Usage 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

Problems 1. Create a servlet that prints in a table the numbers from 1

Problems 1. Create a servlet that prints in a table the numbers from 1 to 1000 and their square root. 2. 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. 3. 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.