58
Java Servlets Svetlin Nakov Borislava Spasova

Java Servlets

Embed Size (px)

DESCRIPTION

Short presentation about Java Servlets.

Citation preview

Page 1: Java Servlets

Java ServletsSvetlin Nakov

Borislava Spasova

Page 2: Java Servlets

Contents

1. Java Servlets Technology Overview

• What is a Java Servlet?

• Servlet Services

• Why Use Servlets?

• Time Servlet – Example

• Deploying Servlets on Eclipse IDE

2. Servlets Architecture

• Servlets API

• Servlets Life-Cycle

Page 3: Java Servlets

Contents (2)

3. Servlet Examples• Processing Parameters – Hello Servlet

• Image Counter Servlet

4. Using Sessions• What is a Session?

• The Sessions API

• Session Timeout

5. Session Examples• Login / Logout Application

• The Browser's Cache Problems

Page 4: Java Servlets

Java ServletsTechnology Overview

Page 5: Java Servlets

What is a Java Servlet?

• Java Servlets are:

• 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, …)

Page 6: Java Servlets

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

Page 7: Java Servlets

Servlet Services

• Java Servlets provide many useful services

• Provides low-level API for building Internet services

• Serves as foundation to JavaServer Pages (JSP) and JavaServer Faces (JSF) technologies

• Can deliver multiple types of data to any client

• XML, HTML, WML, GIF, etc...

• Can serve as “Controller” of JSP/Servlet application

Page 8: Java Servlets

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

Page 9: Java Servlets

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 (SSI, servlet-chaining, filters, etc.)

Page 10: Java Servlets

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>"); } }

Page 11: Java Servlets

Deploying Servlets on Eclipse IDE

• First create new Web application

Page 12: Java Servlets

Deploying Servlets on Eclipse IDE (2)

• Add new servlet to the Web application

Page 13: Java Servlets

Deploying Servlets on Eclipse IDE (3)

• Run the servlet

Page 14: Java Servlets

Deploying Servlets on Eclipse IDE (4)

• The servlet in action

Page 15: Java Servlets

Java ServletsTechnical Architecture

Page 16: Java Servlets

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

Page 17: Java Servlets

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)

Page 18: Java Servlets

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)

Page 19: Java Servlets

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(HttpServletRequest.getParameter(StringString))

ServletConfig.getInitParameterServletConfig.getInitParameter()()

HttpServletRequest.getHeader(HttpServletRequest.getHeader(StringString))

Page 20: Java Servlets

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.setHeaderHttpServletResponse.setHeader(<name>, <value>) /(<name>, <value>) / HttpServletResponse.setContentType(HttpServletResponse.setContentType(StringString))

HttpServletResponse.getWriter()HttpServletResponse.getWriter()

HttpServletResponseHttpServletResponse..getOutputStream()getOutputStream()

HttpServletResponse.sendRedirect()HttpServletResponse.sendRedirect()

Page 21: Java Servlets

Servlets Life-Cycle

• You can provide an implementation of these methods in HttpServlet descendent classes to manipulate the servlet instance and the resources it depends on

• The Web container manages the life cycle of servlet instances

• The life-cycle methods should not be called by your code

• 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

Page 22: Java Servlets

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

Page 23: Java Servlets

The service() Method

• Called by the Web container to process a user request

• Dispatches the HTTP requests to 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

Page 24: Java Servlets

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

Page 25: Java Servlets

Java ServletsExamples

Page 26: Java Servlets

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");

Page 27: Java Servlets

Hello Servlet – Example

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

HelloForm.htmlHelloForm.html

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet {

HelloHelloServletServlet..javajava

Page 28: Java Servlets

Hello Servlet – Example

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>");

}

HelloHelloServletServlet..javajava

Page 29: Java Servlets

Creating The Form in Eclipse IDE

• Create new HTML form

Page 30: Java Servlets

Creating New Servlet in Eclipse IDE

• Create new Servlet

Page 31: Java Servlets

Hello Servlet in Action

Page 32: Java Servlets

Hello Servlet –HTTP Request

GET /FirstWebApp/HelloServlet?user_name=Nakov HTTP/1.1Accept: 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: bgAccept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)Host: nakov:8084Connection: Keep-Alive

• What happens when the user enters his name?

• Internet Explorer (IE) sends the following HTTP request to Tomcat

• What happens when the user enters his name?

• Internet Explorer (IE) sends the following HTTP request to Tomcat

Page 33: Java Servlets

Hello Servlet –HTTP Response

HTTP/1.1 200 OKContent-Length: 100Date: Fri, 26 Mar 2006 10:06:28 GMTServer: Apache-Coyote/1.1 <html><head>

<title>Hello Servlet</title></head><body>

<h1>Hello, Nakov</h1></body></html>

• What happens when Tomcat receive and process the HTTP request

• Tomcat sends the following HTTP response to Internet Explorer

• What happens when Tomcat receive and process the HTTP request

• Tomcat sends the following HTTP response to Internet Explorer

Page 34: Java Servlets

Image Counter Servlet

• We want to create a servlet that displays an image counter (as JPEG image)

• The servlet should maintain an internal counter

• Can be initialized in the init() method and incremented in the doGet() method

• It should produce binary output (the JPEG) image

• The content type should be set to "image/jpeg"

Page 35: Java Servlets

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) { ... }

Page 36: Java Servlets

Image Counter Servlet (3)

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String msg; synchronized(this) { mVisitCounter++; msg = "" + mVisitCounter + " visits since " + mStartDate; } BufferedImage image = createImage(msg); response.setContentType("image/jpeg"); OutputStream out = response.getOutputStream(); // Encode the image in JPEG format and // write the image to the output stream } }

Page 37: Java Servlets

Image Counter Servlet in Action

Page 38: Java Servlets

Using Sessions

Page 39: Java Servlets

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

Page 40: Java Servlets

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

Page 41: Java Servlets

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

Page 42: Java Servlets

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();HttpSession session = request.getSession();

Page 43: Java Servlets

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

Page 44: Java Servlets

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 accessCount = (Integer)(Integer) session.getAttribute("accessCount");session.getAttribute("accessCount");

Enumeration attributes =Enumeration attributes = request.getAttributeNames();request.getAttributeNames();

Page 45: Java Servlets

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();HttpSession session = request.getSession();session.setAttribute("name", "Svetlin Nakov");session.setAttribute("name", "Svetlin Nakov");

session.session.removeremoveAttribute("name");Attribute("name");

Page 46: Java Servlets

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 boolean isNew();public boolean isNew();

public String getId();public String getId();

public long getLastAccessedTime();public long getLastAccessedTime();

public long getCreationTime();public long getCreationTime();

Page 47: Java Servlets

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 int getMaxInactiveInterval();

public void setMaxInactiveInterval (int seconds)public void setMaxInactiveInterval (int seconds);;

Page 48: Java Servlets

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()public void invalidate();;

Page 49: Java Servlets

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

Page 50: Java Servlets

Login Form

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

LoginForm.htmlLoginForm.html

Page 51: Java Servlets

Login Servlet

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); response.sendRedirect("MainServlet"); } else { response.sendRedirect("InvalidLogin.html"); } }}

LoginLoginServletServlet..javajava

Page 52: Java Servlets

Main Servlet

public class MainServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = request.getSession(); String userName = (String)

session.getAttribute("USER"); if (userName != null) { response.setContentType("text/html"); ServletOutputStream out = resp.getOutputStream(); out.println("<html><body><h1>"); out.println("Hello, " + userName + "! "); out.println("</h1></body></html>"); } else { response.sendRedirect("LoginForm.html"); } }}

MainServlet.javaMainServlet.java

Page 53: Java Servlets

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("text/html"); ServletOutputStream out = response.getOutputStream(); out.println("<html><head>"); out.println("<title>Logout</title></head>"); out.println("<body>"); out.println("<h1>Logout successfull.</h1>"); out.println("</body></html>"); }}

LogoutServlet.javaLogoutServlet.java

Page 54: Java Servlets

Invalid Login Page

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

InvalidLogin.htmlInvalidLogin.html

Page 55: Java Servlets

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");

Page 56: Java Servlets

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.

Page 57: Java Servlets

Homework

1. 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.

2. 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.1 cm = 0.01 meters 1 km = 1000 meters

1 foot = 0.3048 meters 1 inch = 0.0254 meters

1 yard = 0.9144 meters 1 mile = 1609.344 meters

1. 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.

2. 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.1 cm = 0.01 meters 1 km = 1000 meters

1 foot = 0.3048 meters 1 inch = 0.0254 meters

1 yard = 0.9144 meters 1 mile = 1609.344 meters

Page 58: Java Servlets

Homework (2)

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

Step 1: First name, last name, age

Step 2: Address (country, town, street)

Step 3: University, faculty, specialty

The data entered in the 3 steps should be stored in the session and finally displayed.

4. Create a servlet that reads an image (from WEB-INF\img\logo.gif) and returns it.

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

Step 1: First name, last name, age

Step 2: Address (country, town, street)

Step 3: University, faculty, specialty

The data entered in the 3 steps should be stored in the session and finally displayed.

4. Create a servlet that reads an image (from WEB-INF\img\logo.gif) and returns it.