1 introduction to java server-side technologies: servlets and jsp sun tutorial to servletstutorial...

87
1 Introduction to Java Introduction to Java Server-Side Server-Side Technologies: Technologies: Servlets and JSP Servlets and JSP Sun tutorial to servlets Sun JSP Tutorial

Post on 19-Dec-2015

252 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

1

Introduction to JavaIntroduction to JavaServer-Side Technologies:Server-Side Technologies:

Servlets and JSPServlets and JSP

Sun tutorial to servlets

Sun JSP Tutorial

Page 2: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

2

Introduction to ServletsIntroduction to Servlets

Page 3: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

3

What is a Servlet?What is a Servlet?

• Servlets are Java programs that can be run

dynamically from a Web Server

• Servlets are a server-side technology

• A Servlet is an intermediating layer between an

HTTP request of a client and the data stored on

the Web server

Page 4: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

4

A Java ServletA Java Servlet

Web browser

Web server

request request

responseresponseServletServlet

Page 5: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

5

An ExampleAn Example

• In the following example, the local server calls

the Servlet TimeServlet with an argument

supplied by the user

• This example, as well as all the examples in this lecture

can be found at http://inferno:5000/

(accessible only from CS!)

Page 6: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

6

Reload / Refresh Servlet ResultReload / Refresh Servlet Result• Trying to refresh the content created by a servlet will lead to

fetching a new content from the server• This is not the case with static resources• Response headers of a static (as opposed to a servlet generated)

resource contain- Etag, Last-Modified

• While trying to refresh a resource- Cache-Contol: max-age=0 is sent and that means the server/proxies will

try to revalidate the resource- Only in the static case the resource could be revalidated against some

values the client holds- So in the static case the client sends the Etag value attached to the

If-None-Match header, and the Last-Modified value is sent in If-Modified-Since

Clear the cache, open and then reload /dbi/Time.htmlOpen and reload /dbi/initCompare the headers sent and received.

Page 7: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

7

What can Servlets do?What can Servlets do?

• Read data sent by the user (e.g., form data)

• Look up other information about the request in the HTTP

request (e.g. authentication data, cookies, etc.)

• Generate the result (may do this by talking to a database, file

system, etc.)

• Format the result as a document (e.g., convert it into HTML

format)

• Set the appropriate HTTP response parameters (e.g. cookies,

content-type, etc.)

• Send the resulting document to the user

Page 8: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

8

Supporting ServletsSupporting Servlets

• To run Servlets, the Web server must support them- Apache Tomcat

• Also functions as a module for other Apache servers

- Sun Java System Web Server and Java System Application Server

- IBM's WebSphere Application Server- BEA’s Weblogic Application Server- Macromedia’s Jrun – an engine that can be added to

Microsoft’s IIS, Apache’s Web servers and more...- Oracle Application Server- …

In your final project you will install this server to create a powerful website

Page 9: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

9

Creating a Simple ServletCreating a Simple Servlet

Read more about the Servlet Interface

Page 10: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

10

The The ServletServlet Interface Interface

• 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

Page 11: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

11

HTTP Request MethodsHTTP Request Methods

• POST - application data sent in the request body

• GET - application data sent in the URL

• HEAD - client sees only header of response

• PUT - place documents directly on server

• DELETE - opposite of PUT

• TRACE - debugging aid

• OPTIONS - list communication options

Page 12: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

12

Servlet HierarchyServlet Hierarchy

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

any request method

Called by the servlet container to

allow the servlet to respond to

a specific request method

A generic, protocol-independent

class, implementing Servlet

Page 13: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

13

Class Class HttpServletHttpServlet

• Class HttpServlet handles requests and responses

of 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

• This class is abstract

Read more about the HttpServlet Class

That is, a class that can be sub-

classed but not instantiated.

This class’ methods however

are not abstract…

Page 14: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

14

Creating a ServletCreating a Servlet• 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

You could also run:

CheckRequestServlet <host> /dbi/empty <port> <OTHER-METHODS>

Check the result of an empty implementation

http://localhost/dbi/empty

Page 15: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

15

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

}

}

HelloWorld.java

Page 16: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

16

Returning HTMLReturning HTML

• By default, no content type is given with a

response

• In order to generate HTML:- Tell the browser you are sending HTML, by setting the

Content-Type header (response.setContentType())

- Modify the printed text to create a legal HTML page

• You should set all headers before writing the

document content. Can you guess why?Download LiveHttpHeaders Extension

As you can check using LiveHttpHeaders plug-in

Page 17: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

17

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("<html><head><title>Hello World</title></head>\n");

out.println("<body>");

out.println("<h2>" + new java.util.Date() + "</h2>\n");

out.println("<h1>Hello World</h1>\n</body></html>"); }

}

HelloWorld.java

Content type wasn’t set,

but the browser will

understand…

)don’t rely on this in a real

product / the project)

Page 18: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

18

Configuring the ServerConfiguring the Server

<web-app> <servlet> <servlet-name>hello</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping></web-app></web-app>

myApp/WEB-INF/web.xml

myApp/WEB-INF/classes/HelloWorld.class

http://inferno:5000/dbi/hello

• More on this in when we Tomcat in depth…

Page 19: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

19

Getting Information Getting Information From the RequestFrom the Request

Page 20: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

20

An HTTP Request ExampleAn HTTP Request Example

GET /default.asp HTTP/1.0

Accept: image/gif, image/x-xbitmap, image/jpeg, image/png, */*

Accept-Language: en

Connection: Keep-Alive

Host: magni.grainger.uiuc.edu

User-Agent: Mozilla/4.04 [en] (WinNT; I ;Nav)

Cookie:SITESERVER=ID=8dac8e0455f4890da220ada8b76f;

ASPSESSIONIDGGQGGGAF=JLKHAEICGAHEPPMJKMLDEM

Accept-Charset: iso-8859-1,*,utf-8

Page 21: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

21

Getting HTTP DataGetting HTTP Data

• Values of the HTTP request can be accessed through the

HttpServletRequest object

• Get the value of the header hdr using

getHeader("hdr") of the request argument

• Get all header names: getHeaderNames()

• Methods for specific request information:

getCookies, getContentLength, getContentType,

getMethod, getProtocol, etc.

Read more about the HttpRequest Interface

Page 22: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

22

public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Servlet Example: Showing Request Headers"; out.println( "<html><head><title>" + title + "</title></head><body>\n" + "<h1>" + title+ "</h1>\n" + "<h2>Request Method: "+request.getMethod()+"</h2>" + "<h2>Request URI: "+request.getRequestURI()+"</h2>" + "<h2>ServletPath: "+request.getServletPath()+"</h2>" + "<h2>Request Protocol: "+request.getProtocol()+"</h2>" + "<table border=\"1\">\n" + "<tr><th>Header Name</th><th>Header Value</th></tr>");

Page 23: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

23

Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); out.println("<tr><td>" + headerName + "</td>" +"<td>"+request.getHeader(headerName)+"</td></tr>"); } out.println("</table>\n</body></html>");}

public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}}

Compare the results of the different browsers

Page 24: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

24

User Input in HTMLUser Input in HTML

• 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

• method: the HTTP method to use when passing

parameters to the application (e.g. get or post)

Page 25: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

25

The The <input><input> Tag 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

Page 26: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

26

GET ExampleGET Example<form method="get" action="http://www.google.com/search"> <p><input name="q" type="text" /> <input type="submit" /> <input type="reset" /> </p></form>

http://www.google.com/search?q=servlets

Page 27: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

27

<form method="post" action="http://www.google.com/search"> <p><input name="q" type="text" /> <input type="submit" /> <input type="reset" /> </p></form>

POST ExamplePOST Example

POST /search HTTP/1.1

Host: www.google.com

Content-type: application/x-www-form-urlencoded

Content-length: 10

<empty-line>

q=servlets

Google doesn’t support POST!(try to guess why)

Page 28: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

28

Getting the Parameter ValuesGetting the Parameter Values

• To get the (first) value of a parameter named x:

- req.getParameter("x")

where req is the service request argument

• If there can be multiple values for the parameter:

- req.getParameterValues("x")

• To get parameter names:

- req.getParameterNames()

Page 29: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

29

<html><head><title>Sending Parameters</title> <style type="text/css"> p{display:table-row} span{display:table-cell; padding:0.2em} </style></head><body>

<h1>Please enter the parameters</h1> <form action=“setcolors" method="get"> <p>Background color: <span><input type="text" name="bgcolor"/></span></p> <p>Font color: <span><input type="text" name="fgcolor"/> </span> </p> <p>Font size: <span><input type="text" name="size"/></span></p> <h2> <input type="submit" value="Submit Parameters"/></h2> </form>

</body></html>parameters.html

Page 30: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

30

public class SetColors extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html"); PrintWriter out = response.getWriter(); String bg = request.getParameter("bgcolor"); String fg = request.getParameter("fgcolor"); String size = request.getParameter("size");

An Example (cont)An Example (cont)

SetColors.java

Page 31: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

31

out.println("<html><head><title>Set Colors Example" +"</title></head>");

out.println("<body style=\"color:" + fg + ";background-color:" + bg + ";font-size:"+ size + "px\">"); out.println("<h1>Set Colors Example</h1>"); out.println("<p>You requested a background color " + bg + "</p>"); out.println("<p>You requested a font color " + fg + "</p>"); out.println("<p>You requested a font size " + size + "</p>");

out.println("</body></html>");}

An Example (cont)An Example (cont)

SetColors.java

Page 32: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

32

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);}

• You don't have to do anything different to read

POST data instead of GET data. (Cool!)

<form action="localhost/dbi/SetColors" method="post"> …

Handling PostHandling Post

Page 33: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

33

Creating the Creating the Response of the ServletResponse of the Servlet

Page 34: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

34

HTTP ResponseHTTP Response

• The response includes:Status line: version, status code, status message

Response headers

Empty line

Content

HTTP/1.1 200 OKContent-Type: text/htmlContent-Length: 89Server: Apache-Coyote/1.1

>HTML><HEAD><TITLE>HELLO WORLD</TITLE></HEAD<

>BODY><H1>Hello World </H1></BODY></HTML<

Read more about the HttpResponse Interface

Page 35: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

35

Setting the Response StatusSetting the Response Status• Use the following HttpServletResponse methods to set

the response status:

- setStatus(int sc) • Use when there is no error, like 201 (created) • No need to send 200 OK explicitly…

- sendError(sc), sendError(sc, message) • Use in erroneous situations, like 400 (bad request)• The server may return a formatted message

- sendRedirect(String location)• As opposed to forwarding which is done within the server side

completely, on redirect the client gets the “Location” header and a special code (302) and sends another request to the new location

http://localhost/dbi/redirect

Page 36: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

36

Setting the Response StatusSetting the Response Status

• Class HTTPServletResponse has static integer

variables for popular status codes- for example:

SC_OK(200), SC_NOT_MODIFIED(304),

SC_UNAUTHORIZED(401), SC_BAD_REQUEST(400)

• Status code 200 (OK) is the default

Page 37: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

37

Setting Response HeadersSetting Response Headers

• Use the following HTTPServletResponse methods to set the response headers:- setHeader(String hdr, String value),

setIntHeader(String hdr, int value)• If a header with the same name exists, it is

overridden.

- addHeader(String hdr, String value), addIntHeader(String hdr, int value)

• The header is added even if another header with the same name exists.

Page 38: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

38

Specific Response HeadersSpecific Response Headers

• Class HTTPServletResponse provides

setters for some specific headers:

- setContentType

- setContentLength • automatically set if the entire response fits

inside the response buffer

- setDateHeader

- setCharacterEncoding

Page 39: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

39

More Header MethodsMore Header Methods

• containsHeader(String header)- Check existence of a header in the response

• addCookie(Cookie)

• sendRedirect(String url)- automatically sets the Location header

• Do not write into the response after sendError

or sendRedirect

Check the result of writing a response after sendError/sendRedirect

http://localhost/dbi/bad.html

Page 40: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

40

The Response Content BufferThe Response Content Buffer

• The response body is buffered

• Data is sent to the client when the buffer is full

or 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

Check the result of sendError/setContentType getting “commited”

http://localhost/dbi/bad.html

Page 41: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

41

Buffer Related MethodsBuffer Related Methods

• setBufferSize, getBufferSize- What are the advantages of using big buffers? what are

the disadvantages?

• flushBuffer

• resetBuffer- Clears the unsent body content

• reset- Clears any data that exists in the buffer as well as the

status code and headers (if not yet sent)

• isCommitted

Page 42: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

42

Supporting HTTP MethodsSupporting HTTP Methods

Page 43: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

43

The HEAD MethodThe HEAD Method• The simple implementation of doHead is executing

doGet and excluding the response body • In addition, the size of the body is calculated and added

to the headers• You do not have to override this method• Why would one want to override this method?

- The content size is not calculated in servlets as opposed to static html resources…

Check the default implementation of doHead:

Run CheckRequestServlet <HOST> /dbi/init <PORT> GET Run CheckRequestServlet <HOST> /dbi/init <PORT> HEADRun CheckRequestServlet <HOST> /dbi/Time.html <PORT> HEAD

(shorter output yet its length is calculated…)In class HOST=localhost, PORT=80

Page 44: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

44

The HEAD Method The HEAD Method (cont)(cont)

• The right way to implement doHead is :- Don’t implement doHead explicitly

- Instead, check within the doGet call, what is the

requested method (httpServletRequest.getMethod())

- If it’s HEAD do the same without returning the

content

- This way the results of HEAD / GET requests are

similar as they should be

Page 45: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

45

OPTIONS and TRACEOPTIONS and TRACE

• doOptions returns the supported methods:

- For example, if you override doGet then the following

header will be returned:

Allow: GET, HEAD, TRACE, OPTIONS

• doTrace returns the request itself in the body of the

message, for debugging purposes

• You usually do not override these methods

- Override doOptions if you offer some new methods…

Page 46: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

46

Unsupported MethodsUnsupported Methods

• By default, the methods doPost, doGet, doPut and doDelete return an error status code 405 with the message:HTTP method XXX is not supported by this URL

• doHead calls doGet and therefore leads to the same result but with unsupported method GET

• In particular, you have to override doGet and doPost if you want to return an appropriate response for these methods- Many applications support only one of GET/POST

Page 47: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

47

Servlet Life CycleServlet Life Cycle

Page 48: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

48

Servlet Life CycleServlet Life Cycle

• When the servlet mapped URL 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

Page 49: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

49

Servlet Life CycleServlet Life Cycle

• When the Servlet in instantiated, its method init()

is invoked (in our case, by Tomcat)- External parameters are supplied

• Upon a request, its method service() is invoked

• Before the Servlet removal, its method destroy()

is invoked

Page 50: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

50

Servlet Life CycleServlet Life Cycle

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

Page 51: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

51

Initializing ServletsInitializing Servlets• 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

Read more about the ServletConfig Interface

If we use init(), how can we obtain a

reference to the ServletConfig ?

Page 52: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

52

<web-app>…<servlet>

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

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

A web.xml ExampleA web.xml Example

• More on this in when we Tomcat in depth…

Page 53: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

53

public class ServletInit extends HttpServlet { String _login = null; Calendar _initTime = null; public void init() throws ServletException { _login = getInitParameter("login"); _initTime = new GregorianCalendar(); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html"); PrintWriter out = res.getWriter();

out.println("<html><head><title>Initialization</title><body><h2>" + "I am the Servlet of <i>" + _login+ "</i><br/>" + "I was initialized at " + _initTime.get(Calendar.HOUR_OF_DAY) + ":"+ _initTime.get(Calendar.MINUTE) + ":"+ _initTime.get(Calendar.SECOND) + "</h2></body></html>"); }} ServletInit.java

Calls the method

getInitParameter

defined within the

ServletConfig interface

implemented by

HttpServlet class

Page 54: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

54

Loading a Servlet on StartupLoading a Servlet on Startup

• 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

• More on this in when we Tomcat in depth…<servlet> <servlet-name>InitExample</servlet-name> <servlet-class>ServletInit</servlet-class> <load-on-startup/></servlet>

You can use this element

to set the loading order

of those servlets which

are loaded on startup

Page 55: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

55

Destroying ServletsDestroying Servlets

• The server may remove a loaded Servlet, Why?:- asked to do so by an administrator (e.g. Server shutdown)- Servlet was idle for a long time- server needs to free resources

• The server removes a Servlet only if all threads have finished or a grace period has passed

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

Page 56: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

56

Thread SynchronizationThread 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)

Page 57: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

57

Introduction to JSPIntroduction to JSP

Page 58: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

58

Many HTML Pages are Mostly StaticMany HTML Pages are Mostly Static

• Servlets allow us to write dynamic Web pages- Easy access to request, session and context data

- Easy manipulation of the response (cookies, etc.)

- And lots more...

• It is very inconvenient to write and maintain long

and mostly static HTML pages using Servlets

(even though such pages are very common)

out.println("<h1>Bla Bla</h1>" + "bla bla bla bla"

+ "lots more here...")

Page 59: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

59

Introducing JSPIntroducing JSP

• The Idea:- Use HTML for most of the page.

- Write Servlet code directly in the HTML page,

marked with special tags.

• The server automatically translates a JSP page to

a Servlet class and the latter is actually invoked- In Tomcat 5.5, you can find the generated Servlet

code under $CATALINA_BASE/work/

• A JSP is no more than a very (very) convenient

way to write servlets which output textual data.

Page 60: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

60

RelationshipsRelationships

• Servlets: HTML code is printed using Java code

• JSP: Java code is embedded in HTML code

• Not only for HTML! JSP can be used for any

textual format. Servlets can be used for any data!

Java

HTML

HTML

JAVA

Page 61: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

61

ExampleExample

<html> <head> <title>Hello World</title> </head> <body> <h2><%= new java.util.Date() %></h2>

<h1>Hello World</h1> </body></html>

Open the generated Java code

Page 62: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

62

Generated Servlet HierarchyGenerated Servlet Hierarchy(Tomcat 5.0 Implementation)(Tomcat 5.0 Implementation)

Apache

Implementation

Generated

Servlet

Sun

Specifications

GenericServlet

Servlet

JspPage

HttpJspPageHttpServlet

HttpJspBase

mypage_jsp

classesinterfaces

Read more about Apache HttpJspBase Class

Abstract class extended by every generated

Servlet

Page 63: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

63

JSP Limitations and AdvantagesJSP Limitations and Advantages

• JSP can only do what a Servlet can do

• Easier to write and maintain HTML

• Easier to separate HTML from code

• Can be created using a "reverse engineering

technique":- Create static HTML and then replace static data with

Java code

Page 64: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

64

JSP Life CycleJSP Life Cycle

Page 65: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

65

JSP Life CycleJSP Life Cycle

The following table describes the life cycle of JSP

generated Servlet in details:

Page 66: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

66

JSP Life CycleJSP Life Cycle

Request

#1

Request

#2

Request

#3

Request

#4

Request

#5

Request

#6

JSP page

translated into

servlet

YesNoNoNoYesNo

JSP’s Servlet

compiled

YesNoNoNoYesNo

Servlet

instantiated and

loaded into

server's memory

YesNoYesNoYesNo

init (or

equivalent) called

YesNoYesNoYesNo

doGet (or

equivalent) called

YesYesYesYesYesYes

Written by Marty Hall. Core Servlets & JSP book: www.coreservlets.com

Pag

e first written

Server restarted

Pag

e mo

dified

Translation & compilation only after first call…

Page 67: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

67

JSP TranslationJSP Translation• When the JSP file is modified,

JSP is translated into a Servlet - But only after the JSP’s url is requested by the client

- Application needs not be reloaded when JSP file is modified

• Server does not generate the Servlet class

after startup, if the latter already exists and isn’t too old- Generated Servlet acts just like any other Servlet

• The generated servlet can handle GET, POST, HEAD requests

though it does not implement doGet(), doPost(), doHead() explicitly- Its Servlet.service() method calls the newly implemented main method named

HttpJspBase._jspService()

JSP file named file.jsp will be translated into

the Java file file_jsp.java

Page 68: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

68

init()init() and and destroy()destroy()

• init() of the generated Servlet is called every time

the Servlet class is loaded into memory and

instantiated

• destroy() of the generated Servlet is called every

time the generated Servlet is removed

• The latter two happen even if the reason is

modification of the JSP file

Page 69: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

69

jspInit jspInit andand jspDestroy jspDestroy

• In JSP pages, like regular Servlets, we sometimes want

to implement init and destroy

• It is illegal to use JSP declarations to override init or

destroy, since they are (usually) already implemented

by the generated Servlet

• Instead, override the methods jspInit() and jspDestroy()- The generated servlet is guaranteed to call these methods from

init and destroy, respectively

- The standard versions of jspInit and jspDestroy are empty

(placeholders for you to override)

Page 70: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

70

Thread SynchronizationThread Synchronization

• After the Servlet is generated, one instance of it

serves requests in different threads, just like any

other Servlet

• In particular, the service method (_jspService)

may be executed by several concurrent threads

• Thus, like Servlets, JSP programming requires

concurrency management

Page 71: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

71

Basic JSP ElementsBasic JSP Elements

A Quick Reference to JSP Elements

Page 72: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

72

Basic Elements in a JSP fileBasic Elements in a JSP file

• HTML code: <html-tag>content</html-tag>

• JSP Comments: <%-- comment --%>

• Expressions: <%= expression %>

• Scriptlets: <% code %>

• Declarations: <%! code %>

• Directives: <%@ directive attribute="value" %>

• Actions: <jsp:forward.../>, <jsp:include.../>

• EL Expressions: ${expression} Covered Later...

Page 73: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

73

JSP ExpressionsJSP Expressions

• A JSP expression is used to insert Java values directly

into the output

• It has the form: <%= expression %> , where

expression can be a Java object, a numerical

expression, a method call that returns a value, etc...

• For example:

<%= new java.util.Date() %>

<%= "Hello"+" World" %>

<%= (int)(100*Math.random()) %>

The heading space and the

following space are not created in

the result.

Use “ “ if you want a real space

Page 74: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

74

JSP ExpressionsJSP Expressions

• Within the generated Java code- A JSP Expression is evaluated

- The result is converted to a string

- The string is inserted into the page

• This evaluation is performed at runtime (when

the page is requested), and thus has full access to

information about the request, the session, etc...

Page 75: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

75

Expression TranslationExpression Translation

<h1>A Random Number</h1><%= Math.random() %>

public void _jspService(HttpServletRequest request, HttpServletResponse response)

throws java.io.IOException, ServletException { ... response.setContentType("text/html"); ... out.write("<h1>A Random Number</h1>\r\n"); out.print( Math.random() );

out.write("\r\n"); ...

}

The generated servlet calls out.write() for

Strings, and out.print() for objects

Default content-type

Page 76: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

76

Predefined Variables (Implicit Objects)Predefined Variables (Implicit Objects)

• The following predefined variables can be used:

- request: the HttpServletRequest

- response: the HttpServletResponse

- session: the HttpSession associated with the request

- out: the PrintWriter (a buffered version of type

JspWriter) used to fill the response content

- application: The ServletContext

- config: The ServletConfig

• These variables and more will be discussed in details

Page 77: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

77

<html>

<head>

<title>JSP Expressions</title>

</head>

<body>

<h2>JSP Expressions</h2>

<ul>

<li>Current time: <%= new java.util.Date() %></li>

<li>Your hostname:<%= request.getRemoteHost() %></li>

<li>Your session ID: <%= session.getId() %></li>

<li>The <code>testParam</code> form parameter:

<%= request.getParameter("testParam") %></li>

</ul>

</body>

</html>

Computer-code style

Page 78: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

78

JSP ScripletsJSP Scriplets

• JSP scriptlets let you insert arbitrary code into

the Servlet service method ( _jspService )

• Scriptlets have the form: <% Java Code %> • The code is inserted verbatim into the service

method, according to the location of the scriptlet

• Scriptlets have access to the same automatically

defined variables as expressions

Page 79: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

79

<%= foo() %> <% bar(); %>

public void _jspService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

...response.setContentType("text/html");...out.print(foo());bar();...

}

Scriptlet TranslationScriptlet Translation

Page 80: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

80

An Interesting ExampleAn Interesting Example

Scriptlets don't have to be complete code blocks:

<% if (Math.random() < 0.5) { %> You <b>won</b> the game! <% } else { %> You <b>lost</b> the game! <% } %>

if (Math.random() < 0.5) { out.write("You <b>won</b> the game!"); } else { out.write("You <b>lost</b> the game!"); }

Page 81: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

81

JSP DeclarationsJSP Declarations

• A JSP declaration lets you define methods or members that

get inserted into the Servlet class (outside of all methods)

• It has the following form: <%! Java Code %>

• For example: <%! private int someField = 5; %>

<%! private void someMethod(...) {...} %>

• JSPs are intended to contain a minimal amount of code so it

is usually of better design to define methods in a separate

Java class...

Page 82: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

82

Declaration ExampleDeclaration Example

• Print the number of times the current page has been

requested since the Servlet initialization:

<%! private int accessCount = 0; %>

<%! private synchronized int incAccess() {

return ++accessCount;

} %>

<h1>Accesses to page since Servlet init:

<%= incAccess() %> </h1>

Page 83: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

83

public class serviceCount_jsp extends... implements...

throws... {

private int accessCount = 0;

private synchronized int incAccess() {

return ++accessCount;

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

...

...

out.write("<h1>Accesses to page since Servlet init: ");

out.print(incAccess());

... } ... }

Generated Servlet

Java permits member

initialization on declaration, even if the location is

outside any method’s scope

Page 84: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

84

JSP DirectivesJSP Directives

• A JSP directive affects the structure of the Servlet class

that is generated from the JSP page

• It usually has the following form:

<%@ directive attribute1="value1" ...

attributeN="valueN" %>

• Three important directives: page, include and taglib

• include and taglib will be discussed later

Page 85: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

85

pagepage-Directive Attributes-Directive Attributes

• import attribute: A comma separated list of

classes/packages to import<%@ page import="java.util.*, java.io.*" %>

• contentType attribute: Sets the MIME-Type of the

resulting document (default is text/html as already

mentioned)<%@ page contentType="text/plain" %>

Imports from the class/Jar locations as mentioned in Tomcat

class

Page 86: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

86

pagepage-Directive Attributes -Directive Attributes (cont)(cont)

• What is the difference between setting the page

contentType attribute, and writing <

%response.setContentType("...");%> ?- In the latter case, the new servlet will call

response.setContentType() twice

- The first, impicit (from the JSP point of view), call

will be with the default content type.

- The second, explicit, call might even come after the

buffer was flushed or after the writer was

obtained…

Check: double-contenttype.jsp code using the explicit call, generated java code (servlet)

Page 87: 1 Introduction to Java Server-Side Technologies: Servlets and JSP Sun tutorial to servletstutorial to servlets Sun JSP TutorialJSP Tutorial

87

pagepage-Directive Attributes -Directive Attributes (cont)(cont)

• session="true|false" - use a session?

• buffer="sizekb|none|8kb"

- Specifies the content-buffer (out) size in kilo-bytes

• autoFlush="true|false"

- Specifies whether the buffer should be flushed when

it fills, or throw an exception otherwise

• isELIgnored ="true|false"

- Specifies whether JSP expression language is used

- EL is discussed later

The underlined value is the default

.If the JSP is defined as

using a session, a session cookie will be

sent to the client