YOU ARE DOWNLOADING DOCUMENT

Please tick the box to continue:

Transcript
Page 2: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 3: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

A Java application that is being run by a Web server

Can receive parameters in an HTTP request

Generates an HTTP response

Web browser

Web server

request request

responseresponseServletServlet

What is a Servlet

3

Page 4: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Friendly Time</title> </head>

<body> <h2>What is your name?</h2>

<form method="get" action="time/show"> <p><input name="username" type="text" />

<input type="submit" value="send" /> </p> </form> </body></html>

4

The name of the application

(Servlet)

The name of a parameter

What is a Servlet - Example

Page 5: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

5

sendsend

What is a Servlet - Example

Page 6: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

What is a Servlet - Example

6

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

public class TimeServlet extends HttpServlet {  public void doGet(HttpServletRequest req, HttpServletResponse res)    throws ServletException, IOException {    res.setContentType("text/html");    PrintWriter out = res.getWriter();    Calendar cal = new GregorianCalendar();

    String username = req.getParameter("username");    out.println("<html><head><title>Time</title></head>");    out.println(      "<body style=\"text-align:center\">\n<h2>Hello "        + username        + ".<br/>The time is: "        + "<span style=\"color:red\">"        + cal.get(Calendar.HOUR_OF_DAY)        + ":"        + cal.get(Calendar.MINUTE)        + ":"        + cal.get(Calendar.SECOND)        + "</span>"        + "</h2>\n</body>\n</html>");  }}

Page 7: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

7

What is a Servlet - Example

http://localhost:8080/Examples/time/show?username=Homer

Page 8: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Web Application File Structure

8

time.html

TimeServlet.class

TimeServlet.java

web.xml

Page 9: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

9

<?xml version="1.0" encoding="ISO-8859-1"?><web-app> <servlet> <servlet-name>hello</servlet-name> <servlet-class>examples.HelloServlet</servlet-class> </servlet> <servlet> <servlet-name>time</servlet-name> <servlet-class>TimeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>time</servlet-name> <url-pattern>/time/show</url-pattern> </servlet-mapping> </web-app>

Servlet web.xml

Page 10: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Servlet Annotations

As of Java EE 6 you can use Annotation instead of web.xml

@WebServlet(name = "TestServlet", urlPatterns = {"/search"})

public class TestServlet extends HttpServlet {

... {

• @WebServlet – the annotation that defines the class as a servlet

• Name – the servlet name

• urlPattern – one or more patterns that will be handled by the servlet

10

Page 11: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Java provides the interface Servlet

Specific Servlets implement this interface

Whenever the Web server is asked to invoke a specific Servlet, it activates the method service() of an instance of this Servlet

service(request,response)

MyServlet

(HTTP)

request

(HTTP)

response

11

The Servlet Interface

Page 12: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

YourOwnServlet

HttpServlet

Generic Servlet

Servlet service(ServletRequest, ServletResponse)

doGet(HttpServletRequest , HttpServletResponse)

doPost(HttpServletRequest HttpServletResponse)

doPutdoTrace

Called by the servlet container to allow the servlet to respond to a

specific request method

A generic, protocol-independent class,

implementing Servlet

Servlet Hierarchy

12

Called by the servlet container to allow the

servlet to respond to any request method

Page 13: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Class HttpServlet handles requests and responses according to the HTTP protocol

The service() method of HttpServlet checks the request method and calls the appropriate HttpServlet method:

doGet, doPost, doPut, doDelete, doTrace, doOptions or doHead

13

Class HttpServlet

Page 14: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Extend the class HTTPServlet

Implement doGet or doPost (or both; also maybe others…)

Both methods get:• HttpServletRequest: methods for getting form (query) data,

HTTP request headers, etc.

• HttpServletResponse: methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client

Many times, we implement doPost by calling doGet, or vice-versa

14

Creating a Servlet

Page 15: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class TextHelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("Hello World"); } public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException { doGet(req, res); }}

Creating a Servlet – Hello World

15

Page 16: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

DEMO

Examples.servlets.DateServlet

16

Page 17: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 18: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Getting HTTP Headers

Values of the HTTP request can be accessed through the HttpServletRequest object

Methods for specific request information: getCookies, getContentLength, getContentType, getMethod, getProtocol, etc.

18

Page 19: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 20: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Using HTML forms, we can pass parameters to Web applications

<form action=… method=…> …</form> comprises a single form

• action: the address of the application to which the form data is sent (should be relative to the current page)

• method: the HTTP method to use when passing parameters to the application (e.g. get or post)

20

User Input in HTML

Page 21: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

The <input> Tag

Inside a form, INPUT tags define fields for data entry

Standard input types include: buttons, checkboxes, password fields, radio buttons, text fields, image-buttons, text areas, hidden fields, etc.

Each one associates a single (string) value with a named parameter

21

Page 22: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Getting user input in the servlet

Use the following HTTPServleRequest methods to get the user input:

• getParameter(“<name of parameter>”);

• getParameterNames – returns an enumeration of all the parameters that came on the request

• getParameterMap – return a map of all the parameters and their values

22

Page 23: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

DEMO

Examples.htmlinput

23

Page 24: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 25: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Class HTTPServletResponse provides setters for some specific headers:

- setContentType

- setContentLength • automatically set if the entire response fits inside

the response buffer

- setDateHeader

- setCharacterEncoding

25

Setting Response HeadersSetting Response Header

Page 26: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

The response body is buffered

Data is sent to the client when the buffer is full or when the buffer is explicitly flushed

Once the first data chunk is sent to the client, the response is committed

• You cannot set the response line nor change the headers. Such operations are either ignored or cause an exception to be thrown

26

The Response Content Buffer

Page 27: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 28: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

When a URL that a servlet is mapped to is requested, the server loads the Servlet class and initializes one instance of it

Each client request is handled by the Serlvet instance in a separate thread

The server can remove the Servlet

The Servlet can remain loaded to handle additional requests

Browser

Browser

Browser

ServerServlet

Instance

Servlet Life Cycle

28

Page 29: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Servlet Life Cycle – con’t

When the Servlet in instantiated, its method init() is invoked (in our case, by Tomcat)

• External parameters can be provided

Upon a request, its method service() is invoked

Before the Servlet removal, its method destroy() is invoked

29

Page 30: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Servlet Class

Calling the

init method

Servlet

Instance

Deal with requests:

call the

service method

Destroy the Servlet:

call the

destroy method

Garbage

Collection

ServletConfig

In our case by servlet we refer to any class

extending HttpServlet

Servlet Life Cycle – con’t

30

Page 31: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

The method init has a parameter of type ServletConfig

ServletConfig has methods to get external initialization parameters (getInitParameter())

• In Tomcat, these parameters are set in web.xml

To make initializations, override init() and not init(ServletConfig)

• The former is automatically called by the latter after performing default initializations

If we use init(), how can we obtain a reference to the

ServletConfig ?

Servlet.getServletConfig()

31

Initializing Servlets

Page 32: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

<web-app>…<servlet>

<servlet-name>InitExample</servlet-name> <servlet-class>ServletInit</servlet-class>

<init-param> <param-name>login</param-name> <param-value>Homer</param-value> </init-param> </servlet> …</web-app>

32

A web.xml Example

Page 33: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

A Servlet is usually loaded when it is first being called

You can set Tomcat to load a specific Servlet on startup in the Servlet declaration inside web.xml

<servlet> <servlet-name>InitExample</servlet-name> <servlet-class>ServletInit</servlet-class> <load-on-startup/></servlet>

33

Loading a Servlet on Startup

Page 34: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

DEMO

Examples.servlets

34

Page 35: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 36: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Servlet Context

Allows servlets that belong to the same application to share data and communicate

• For instance, can be used to store details for a JDBC connection (details that are shared by different servlets)

Allows setting and getting attributes

Provides information about the server

Can be used for writing messages to a log file

Use: getServletContext().getAttribute(), and getServletContext().setAttribute() to add objects to a map which is shared between all servlets

36

Page 37: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

<web-app>…<context-param>

<param-name>db-server</param-name> <param-value>db.mta.ac.il</param-value> </context-param>

<servlet> <servlet-name>InitExample</servlet-name> <servlet-class>ServletInit</servlet-class>

<init-param> <param-name>login</param-name> <param-value>Homer</param-value> </init-param> </servlet> …</web-app>

37

A web.xml Example

Page 38: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

The server may remove a loaded Servletasked to do so by an administrator (e.g. Server shutdown)Servlet was idle for a long timeserver needs to free resources

The server removes a Servlet only if all threads have finished or a grace period has passedBefore removing, calls the destroy() method

can perform cleanup, e.g., close database connections

Is it possible for the Servlet to end without its destroy being called?

You can do it if you kill the process explicitly

38

Destroying Servlets

Page 39: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Thread Synchronization

Multiple threads are accessing the same Servlet object at the same time

Therefore, you have to deal with concurrency

init() and destroy() are guaranteed to be executed only once (before/after all service executions)

39

Page 40: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

DEMO

Examples.servletcontext

40

Page 41: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 42: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Request Dispatcher

Servlets have the abilities to ‘call’ each other.

Since no servlet has a reference to another servlet, the way to perform this ‘call’ is by using the Request Dispatcher.

There are 2 ways to make this ‘call’: Forward – will forward the request and response to another

servlet and after the other servlet has finished processing the request, the response will be returned to the client (without returning to the calling servlet)

Include – will forward the request and response to another servlet and after the other servlet has finished processing the request, it will return to the calling servlet

42

Page 43: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Request Dispatcher

Before forwarding/including other servlets, it is possible to modify the request (for example, add/remove/update parameters)

To get the Request Dispatcher call the servlet context: getServletContext().

getRequestDispatcher(“/otherServletPath”)

Tip!

When including another servlet make sure the other servlet does not closes its response writer when it finishes.

43

Page 44: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

DEMO

Examples.servletcontext

44

Page 45: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Age

nda

• What is a Servlet

• Handling HTTP Requests

• User Input in HTML

• Handling HTTP Response

• Servlet Life Cycle

• Servlet Context

• Request Dispatcher

• Sessions

Page 46: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Sessions

HTTP is stateless, hence, for implementing sessions we need to send back and forth a session identifier

The session identifier is generated by the server and being sent to the client

Each request that is part of the session is sent back to the server

Sending session idsBy using cookies

URL rewriting

Hidden form fields

46

Page 47: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Session Objects

47

Session table

Server

Client

Generate a new session

id

3

Send response with a cookie saying the session id is 3The following requests will include session id 3 and will be recorded by the server

Does the server keep the session object forever?

Page 48: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

HttpSession

Information related to a session is encapsulated in HttpSession objects

Data is set and retrieved by setAttribute and getAttribute

48

Page 49: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

DEMO

Examples.poll

49

Page 50: © Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Links

Tutorial: http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html

Core Servlets Tutorials:

http://www.coreservlets.com/

http://courses.coreservlets.com/Course-Materials/csajsp2.html

Overview:

http://alvinjayreyes.com/2013/07/27/a-brief-overview-of-jee6/

50


Related Documents