+ All Categories
Home > Documents > Module2 WEB APPLICATION ESSENTIALS - … … · A First Java Servlet 1 package...

Module2 WEB APPLICATION ESSENTIALS - … … · A First Java Servlet 1 package...

Date post: 30-Mar-2018
Category:
Upload: lyduong
View: 224 times
Download: 4 times
Share this document with a friend
52
WEB APPLICATION ESSENTIALS Module 2 Objectives > After completing this lesson, you should be able to: Describe Java servlet technology Describe JavaServer Pages technology Define a Model-View-Controller (MVC) architecture Understand the basic goals of MVC in a Java EE web application Explain Java EE containers Describe Java application servers Describe the web application development process Identify the essential structure of a WAR file
Transcript

WEB APPLICATION ESSENTIALS

Module 2

Objectives> After completing this lesson, you should be able to:

– Describe Java servlet technology

– Describe JavaServer Pages technology

– Define a Model-View-Controller (MVC) architecture

– Understand the basic goals of MVC in a Java EE web application

– Explain Java EE containers

– Describe Java application servers

– Describe the web application development process

– Identify the essential structure of a WAR file

Java Servlets: Architecture

User Workstation Application Server

Browser

<HTML>

</HTML>

<< HTTP>>

HTTP request

HTTP response

Database

Web Container

Servlet

image

audio

video

<XML>

</XML>

A First Java Servlet

1 package com.examples.lesson02;

2

3 import java.io.IOException;

4 import java.io.PrintWriter;

5 import javax.servlet.ServletException;

6 import javax.servlet.annotation.WebServlet;

7 import javax.servlet.http.HttpServlet;

8 import javax.servlet.http.HttpServletRequest;

9 import javax.servlet.http.HttpServletResponse;

10

11

12 @WebServlet(name="HelloServlet", urlPatterns={"/HelloServlet"})

13 public class HelloServlet extends HttpServlet {

14

15 @Override

16 protected void doGet(HttpServletRequest request,

17 HttpServletResponse response)

18 throws ServletException, IOException {

19 response.setContentType("text/html;charset=UTF-8");

20 PrintWriter out = response.getWriter();

A First Java Servlet

21 try {

22 out.println("<html>");

23 out.println("<head>");

24 out.println("<title>Servlet HelloServlet</title>");

25 out.println("</head>");

26 out.println("<body>");

27 out.println("<h1>HELLO SERVLET!</h1>");

28 out.println("<h2>");

29 out.println(1+1);

30 out.println("</h2>");

31 out.println("</body>");

32 out.println("</html>");

33 } finally {

34 out.close();

35 }

36 }

37 }

HTTP Methods– HTTP Get > doGet

– HTTP Post > doPost

– Merge these calls to processRequest.

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

protected void processRequest(HttpServletRequest request,

HttpServletResponse response)

JavaServer Pages Technology> Java Server Pages (JSPs) embed Java in HTML.1 <%--

2 Simple Hello JSP example

3 --%>

5 <%@page contentType="text/html" pageEncoding="UTF-8"%>

6 <!DOCTYPE html>

7 <html>

8 <head>

9 <meta http-equiv="Content-Type"

10 content="text/html; charset=UTF-8">

10 <title>JSP helloJsp</title>

11 </head>

12 <body>

13 <h1>HELLO JSP!</h1>

14 <h2>${1+1}</h2>

15 </body>

16 </html>

Request

How a JSP Is Processed

Web Client

Web Client

Web Client

jsp_servlets

JSP Page

The JSP page was previously accessed or has been modified.

Translate

Compile

No

Yes

12

34

Internet

Application Server with JSP Container

Comparison of Servlets and JSP Components

Servlets JSP Components

DescriptionJava classes authored in the Java

programming language

Text documents similar to HTML pages with embedded programmatic elements

CharacteristicsServlets extend generic base classes in the API, typically the HttpServlet

interface.

JSP components:

•Can be enhanced with custom tags

•Are translated into servletsby the web container

When to UseDevelopers use servlets when the

amount of code is greater than the amount of content.

Developers and content authors use JSPs when more content than code is needed.

Servlet and JSP Component Collaboration> Most modern web applications use servlets and JSP

components in collaboration. Their capabilities are similar, but they are expressed differently.

RequestDispatcher rd = getServletContext().getRequestDispatcher("/myJsp.jsp");

rd.forward(request,response);

Servlet JSP Component

Type of Operation

•Process form data

•Perform computations

•Collect data for rendering

Generate presentation (particularly HTML)

Role Handle requests, perform computations, transfer control to JSP components

Render a response to the initial request

Model, View, and Controller

> The model is not related to a specific UI.

> The view formats results for presentation.

> The controller performs request handling and pre-processing.

Controller

View

Model

MVC in a Java EE Web Application> The Java EE platform has several component types that

are suitable for the roles in an MVC paradigm:

Controller

- Servlets

View

- JSPs

- JSF Facelet Pages

Model

- POJOs (with or without CDI)

- EJBs

- JSF Backing (Managed) Beans

Java EE ContainersEJB Components

• Session beans

• Message-driven beans

Applet Container

Application Client Container

Browser

Web Container

EJB Container

Database

Applet

Webpages

Application Client

Java EE Server

Web Components

– Servlets

– JSP

– JSF

Java EE–Compliant Application Servers > There are many Java EE application server

implementations.

– GlassFish

– WebLogic

– IBM WebSphere

– Apache TomEE

– JBoss Application Server

> and many more…

IBM

JBossby Red Hat

Apache TomEE

Java Web Application Development Process

Assemble

• Enterprise Application Module (EAR)

• EJB Component Module (JAR)

• Web Module (WAR)

• Resource Module (RAR)

Developer

Deployer

Deployment Tool

Application Components

Package Applications

ApplicationsApplication

Server

Essential Structure of a WAR Filewebapp.war

/webapp (Context root)

lib classesweb.xml

package…other.jarsupport.jar

META-INF

WEB-INF

web-fragment.xml

MyServlet.class

index.html detailView.jsp item.jpg

Accessible via URL:http://<server>:<port>/webapp/index.html

Accessible via URL:http://<server>:<port>/webapp/MyServlet

http://server:port/context_root/resource

Web Context Root and Alias Mapping> A web application URI has the following form:

> Example:

The web application context (usually the

name of your project)

The JSP file name or the URL pattern of a

servlet

http://localhost:7001/lesson02/helloJsp.jsp

Deployment Descriptors (DD)> Are XML-formatted files

> Provide a declarative way to describe the interactions between components and between a component and its container

> Are used to configure vendor-specific features. Application servers may have additional non-portable deployment descriptors to do this job.

> Java EE 6 offers three choices:

– web.xml in WEB-INF/ in a WAR

– web-fragment.xml in META-INF/ in a JAR or in WEB-INF/lib in a WAR

– In annotations in source files

web.xml

QuizTo create an HTTP Servlet class you have to:

a. Extend the javax.servlet.http.HttpServletclass

b. Implement the javax.servlet.http.HttpServlet interface

c. Extend the javax.servlet.Servlet class

d. Implement the javax.servlet.Servlet interface

QuizA server is running locally and listening on port 7001. A webapp.war file is deployed on the server and it is running on the /webapp context root. The webapp.war file contains an HTML file named contacts.html.

> How do you access the contacts.html file from a web browser?

a.http://localhost:7001/contacts.html

b.http://localhost/webapp/contacts.html

c.http://localhost:7001/webapp/contacts.html

d.http://localhost/contacts.html

QuizWhich of the following files can be used to configure servlets? (Choose three.)

a. The same class file and using the @WebServletannotation

b. web-fragment.xml file in META-INF/ in a JAR file or in WEB-INF/lib in a WAR file

c. web.xml file in META-INF/ in a JAR file

d. Java classes and using XML comments

e. web.xml file in WEB-INF/ in a WAR file

f. web-fragment.xml file in the root folder of a WAR file

QuizA web application contains a WEB-INF/lib/foo.jarfile, which in turn contains a META-INF/resources/bar.jsp JSP page.

> At what URL (relative to the context root of the web application) is that JSP page accessible?

a. /foo/bar.jsp

b. /foo/resources/bar.jsp

c. /resources/bar.jsp

d. /bar.jsp

DEVELOPING A SERVLET

Module 2

Web Application Essentials

Objectives> After completing this lesson, you should be able to:

– Describe the HTTP headers and their function

– Explain the request and response process

– Understand the life cycle of a servlet

– List injection and lifecycle method annotations

– Understand the threading model of a servlet

– Provide a Java class that extends the HttpServletabstract class to respond to requests from the client browser

Topics– HTTP Revisited

– Request and Response Process

– Servlet Life Cycle: Overview

– Servlet Life Cycle and Annotations

– Servlets and Threading

– Developing a Simple HTTP Servlet

HTTP MethodsHTTP Method Description

OPTIONSRequest the communication options available on the request/response chain

GET Request to retrieve information identified by the Request-URL

HEADIdentical to the GET except that it does not return a message body, only the headers

POSTRequest for the server to accept the entity enclosed in the body of the HTTP message

PUTRequest for the server to store the entity enclosed in the body of the HTTP message

DELETERequest for the server to delete the resource identified by the request URI

TRACERequest for the server to invoke an application layer loop-back of the request message

CONNECT Reserved for use with a proxy that can switch to being a tunnel

HTTP Revisited> Request format

> Request headers

Header Use

Accept The MIME types that the client can receive

Host The Internet host and port number of the resource being requested

Referrer The address from which the request URI was obtained

User-Agent The information about the client originating the request

GET /lesson03/servlets/helloServlet HTTP/1.1

Connection : keep-aliveUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.1)

Gecko/20100101 Firefox/10.0.1Host: localhost:7001Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Encoding: gzip, deflateAccept-Language: en-us,en;q=0.5

HTTP method Requested URL HTTP version

Request line

Request headers

HTTP Revisited> HTTP response

HTTP/1.1 200 OK

Content-Length: 136Content-Type: text/html;charset=UTF-8Date: Tue, 10 Apr 2012 23:36:58 GMTX-Powered-By: Servlet/3.0 JSP/2.2

<HTML><HEAD><TITLE>Hello Servlet</TITLE></HEAD><BODY BGCOLOR=‘white’><B>Hello World</B></BODY></HTML>

HTTP version

Response message number

Status line

Response headers

Blank line

Message body

Text version of the response message

HTTP Revisited> HTTP response headers

Header Use

Content-TypeA MIME type (such as text/html), whichclassifies the type of data in the response

Content-LengthThe length (in bytes) of the payload of theresponse

ServerAn informational string about the server that responded to this HTTP request

Cache-ControlA directive for the web browser (or proxies) to indicate whether the content of the response should be cached

Topics– HTTP Revisited

– Request and Response Process

– Servlet Life Cycle: Overview

– Servlet Life Cycle and Annotations

– Servlets and Threading

– Developing a Simple HTTP Servlet

Request and Response Process> The browser connects to the web container.

Client

Application Server

WebBrowser

<< TCP socket>>

Web ContainerHTTP request

The input stream of the socket contains the HTTP request data. The output stream of the socket contains the HTTP response data.

Web Container

Request and Response Process> The web container objectifies the input/output streams.

Client

WebBrowser

<< TCP socket>>

HTTP request

<<creates>>

<<creates>>

The web container creates a request object by parsing the HTTP request stream data on the input stream of the socket.

The web container creates a response object that generates the HTTP response stream on the output stream of the socket.

Application Server

:HttpServlet Request

Servlet

:HttpServlet Response

Application Server

Web Container

service(req,resp)

Request and Response Process> The web container executes the servlet.

The web container executes the service method on

the selected servlet. The request and response objects are passed as arguments to this method.

Client

WebBrowser

<< TCP socket>>

HTTP request

:HttpServlet Request

Servlet

:HttpServlet Response

Application Server

Web Container

Request and Response Process> The servlet uses the output stream to generate the

response.

:HttpServlet Request

service(req,resp)Servlet

:HttpServlet Response

:PrintWriter

The response object provides the servlet with a PrintWriter object that allows the servlet to generate the body of the response using the print or println methods

Client

WebBrowser

<< TCP socket>>

HTTP request

HTTP response

Quiz> What is responsible for the creation of the request and

response objects after the request is received?

a.The application server

b.The web container

c. The servlet

d.The web browser

Topics• HTTP Revisited

• Request and Response Process

• Servlet Life Cycle: Overview

• Servlet Life Cycle and Annotations

• Servlets and Threading

• Developing a Simple HTTP Servlet

Servlet Life Cycle: Overview

1. Load the servlet class.2. Create the servlet instance.3. Call the init method.

Ready

4. Call the service method.

5. Call the destroy method.

<<interface>> Servlet

init(ServletConfig)service(req,resp)destroy()

Servlet Class Loading

> Class files are in one of the following locations:

– Under WEB-INF/classes/

– In JAR files in WEB-INF/lib/

Application Server

Web Container

<XML>

</XML>

<<load class>>

AddLeagueFormServlet.class

web.xml

<servlet><servlet-name>AddLeagueForm</servlet-name><servlet-class>view.AddLeagueFormServlet</servlet-class><init-param>

<param-name>seasons-list</param-name><param-value>Spring,Summer,Autumn,Winter</param-value>

</init-param></servlet>

One Instance Per Servlet Definition

> Since v2.4 of the servlet specification, only one instance of a servlet may exist in one web container per definition.

> SingleThreadModel is deprecated.

Web Container

<XML>

</XML>

<<creates>>

AddLeagueForm

web.xml

Servlet

Application Server

init Lifecycle Method

– The init method is a good place for one-time initialization.

– UnavailableException implies “try again later.”

Web Container

<XML>

</XML>

init(config)

AddLeagueForm

web.xml

Servlet

<servlet><servlet-name>AddLeagueForm</servlet-name><servlet-class>s1314.view.AddLeagueFormServlet</servlet-class><init-param>

<param-name>seasons-list</param-name><param-value>Spring,Summer,Autumn,Winter</param-value>

</init-param></servlet>

:ServletConfig

seasons-list="Spring,Summer, Autumn,Winter"

Application Server

AddLeagueFormServlet

SEASONS : String[]

init() doPost(request,response)

<<interface>> ServletConfig

getInitParameter(name:String):StringgetInitParameterNames():EnumerationgetServletContext():ServletContext

VenderServletConfigImpl

getInitParameter(name:String):StringgetInitParameterNames():EnumerationgetServletContext():ServletContext

GenericServlet{abstract}

init(config:ServletConfig)init() service(request,response) destroy() getInitParameter(name:String):StringgetInitParameterNames():EnumerationgetServletContext():ServletContext

<<interface>> Servlet

init(config:servletConfig) service(request,response) destroy()

HttpServlet{abstract}

ServletConfig API

This is the no-argument init method

that you override in your servlet classes.

Every web container vendor must implement the ServletConfig

interface.

As a convenience, the GenericServlet class

also implements the ServletConfig

interface.

delegate

service Lifecycle Method

Web Container

<XML>

</XML>

AddLeagueForm

web.xml

<servlet-mapping><servlet-name>AddLeagueForm</servlet-name><url-pattern>/admin/add_league.view</url-pattern>

</servlet-mapping>

Servlet

service

service

service

http://localhost:8080/soccer/admin/add_league.view

http://localhost:8080/soccer/admin/add_league.view

http://localhost:8080/soccer/admin/add_league.view

Admin1

Admin2

Admin3

Application Server

Web Container

Servlet

AddLeagueForm

destroy()

destroy Lifecycle Method

The web container can choose to destroy any servlet at any time.

Application Server

QuizTypically, in which path do you place third-party or utility JAR files in a web application?

a. /META-INF/lib/

b. The application’s context root

c. /WEB-INF/lib/

d. /META-INF/resources

Quiz> For a given servlet definition, the first three steps (load

class, create instance, call the init method) of the servlet life cycle occur only once.

a.True

b.False

Topics• HTTP Revisited

• Request and Response Process

• Servlet Life Cycle: Overview

• Servlet Life Cycle and Annotations

• Servlets and Threading

• Developing a Simple HTTP Servlet

Servlet Life Cycle and Annotations> Java EE 5 introduced annotations for container-managed

objects.

– Servlets

– Filters

– Listeners

> Dependency injection is applied before any lifecycle methods, and before the application sees the object.

– Under WEB-INF/classes or WEB-INF/lib

Injection Annotations> @EJB: For EJBs

> @Inject: For JavaBeans or EJBs

> @Resource: For data sources, JMS destinations, and environment entries

> @PersistenceContext and @PersistenceUnit:For JPA managers and factories

> @WebServiceRef: For web services

Lifecycle Method Annotations> @PostConstruct and @PreDestroy are required by

the Java EE specification.

> The methods target may be:

– Zero-argument– Return void

– Throw no checked exceptions– Non-final

> The @PostConstruct method is guaranteed to be called after the injection and before the init() method.

> If any exception is thrown from @PostConstruct, the object is abandoned.

> @PostConstruct and @PreDestroy are more general than init() and destroy(), because they allow nonpublic/non-interface methods.

Topics• HTTP Revisited

• Request and Response Process

• Servlet Life Cycle: Overview

• Servlet Life Cycle and Annotations

• Servlets and Threading

• Developing a Simple HTTP Servlet

Servlets and Threading> Multiple threads can respond to concurrent user requests.

> This might cause difficulties with the consistency of shared data and resources.

> Servlet instance variables are suitable for shared read-only data.

> Data that should not be shared between threads should be stored as instance variables in doXxx() methods.

Data Shared Between Invocations by a Single Client

> HttpSession saves data between successive calls.

> Concurrent calls are also possible:

– From multiple browser windows or tabs

– As a result of a malicious user

> Concurrent calls should be handled correctly, or at least they should fail cleanly to avoid a security lapse.

Sharing Data Between Multiple Clients> Careful design is needed for concurrent data access.

> Arbitration is necessary, and the database might provide this.

> Arbitration must not block threads for an unnecessarily long time.

> Beware of sharing data by using instance variables; older containers created multiple servlet instances.

Topics– HTTP Revisited

– Request and Response Process

– Servlet Life Cycle: Overview

– Servlet Life Cycle and Annotations

– Servlets and Threading

– Developing a Simple HTTP Servlet

Time Servlet: Example

HttpServlet API

<<interface>> ServletRequest

<<interface>> Servlet

service(req,resp)

<<interface>> ServletResponse

getWriter():PrintWritergetOutputStreamsetContentType(MIME)setContentLength(int)

<<interface>> HttpServletResponse

setHeadersetDateHeadersetIntHeader

<<interface>> HttpServletRequest

getHeader(name)getHeaders(name):EnumgetHeaderNames():EnumgetIntHeader(name)getDateHeader(name)

HttpServlet{abstract}

servicedoGetdoPost

TimeServlet

doGetdoPost

The service method

dispatches the call to either the doGet or doPost

method based on the HTTP method of the request.

Your servlet class should override either the doGetor doPost method based

on the expected HTTP request method.

HTTP Method to Servlet Method Mapping

HTTP Method Corresponding HttpServlet Method

OPTIONS doOptions

GET doGet

HEAD doHead

POST doPost

PUT doPut

DELETE doDelete

TRACE doTrace

CONNECT doConnect

HttpServletRequest API> getHeaderNames

> getHeader

> getIntHeader

> and so on…

1 boolean displayXHTML = false;2 String userAgent = request.getHeader("User-Agent");3 if((userAgent != null) && 4 (userAgent.startsWith("Mozilla/5.0"))) {5 // browser can handle XHTML content6 displayXHTML = true;7 }8 if(displayXHTML) {9 // XHTML content output here10 } else {11 // regular HTML content output here12 }

HttpServletResponse API> When a response is sent back to the browser from a

servlet, one or more response headers provide information about the response.

– setHeader

– setIntHeader etc.

– getWriter

– getOutputStream

– setContentType

> The most common is Content-Type, which is the MIME type of the document included in the response.response.setContentType("text/html;charset=UTF-8");

TimeServlet Class

1 package com.examples.lesson03;

2

3 import java.io.IOException;

4 import java.io.PrintWriter;

5 import java.text.SimpleDateFormat;

6 import java.util.Date;

7 import javax.servlet.ServletException;

8 import javax.servlet.annotation.WebServlet;

9 import javax.servlet.http.HttpServlet;

10 import javax.servlet.http.HttpServletRequest;

11 import javax.servlet.http.HttpServletResponse;

12

13 @WebServlet(name = "TimeServlet",

14 urlPatterns = {"/servlets/timeServlet"} )

15 public class TimeServlet extends HttpServlet {

16

17

TimeServlet Class 18 protected void processRequest(HttpServletRequest request,

19 HttpServletResponse response)

20 throws ServletException, IOException {

21 response.addHeader("Content-Type", "text/html);

22 PrintWriter out = response.getWriter();

23 try {

24 out.println("<html>");

25 out.println("<head>");

26 out.println("<title>Servlet TimeServlet</title>");

27 out.println("</head>");

28 out.println("<body>");

29 out.println("Welcome. The current time is:");

30 Date currentDate = new Date();

31 SimpleDateFormat formatter = new SimpleDateFormat();

32 out.println(formatter.format(currentDate));

33 out.println("</body>");

34 out.println("</html>");

35 } finally {

36 out.close();

37 }

TimeServlet Class

38

39 @Override

40 protected void doGet(HttpServletRequest request,

41 HttpServletResponse response)

42 throws ServletException, IOException {

43 processRequest(request, response);

44 }

45

46 @Override

47 protected void doPost(HttpServletRequest request,

48 HttpServletResponse response)

49

50 throws ServletException, IOException {

51 processRequest(request, response);

52 }

53

54

Quiz> Given a header in an HTTP request:

X-Retries: 4

> Which two of the following retrieve the value of the header from a given HttpServletRequest request? (Choose two.)

a. request.getHeader("X-Retries")

b. request.getIntHeader("X-Retries")

c. request.getRequestHeader("X-Retries")

d. request.getHeaders("X-Retries").get(0)

e. request.getRequestHeaders("X-Retries").get(0)

HANDLING FORM REQUESTS IN SERVLETS

Module 2

Web Application Essentials

Objectives> After completing this lesson, you should be able to:

– Use HTML forms to collect data from users and send it to a servlet

– Understand how form data is sent in an HTTP request

– Develop a servlet that retrieves form parameters

– Understand and use HttpSession objects

– Use cookies for session management

– Use URL rewriting for session management

Topics> Collecting Data from the User

> How Form Data Is Sent in an HTTP Request

> Developing a Servlet That Retrieves Form Parameters

> Developing Web Applications Using Session Management

> Using Cookies for Session Management

> Using URL Rewriting for Session Management

Collecting Data from the User> A form uses the request-response cycle.

form Tag> Partial structure of an HTML form:

> Example:

<form action='URL TO CONTROLLER' method='GET or POST'><!-- PUT FORM COMPONENT TAGS HERE --></form>

<form action=’HelloSvlt’ method=’POST’>What's your name?: [textfield tag]What's your role: [drop-down list tag][submit button tag]</form>

The form action defines the target URL.

Input Types for Use with Forms> Text input

What's your name?:<input type="text" name="username"/>

Input Types for Use with Forms> Drop-down list

What's your role: <select name="role"><option value="student">Student</option><option value="instructor">Instructor</option><option value="adm">Administrator</option>

</select>

Each option tag provides a single element in

the drop-down list.

Similar to the input tag, the select tag uses the name

attribute to specify the name of the form field.

Input Types for Use with Forms> Submit button

<input type="submit" value="Submit"/>

Example HTML Form

1 <html>2 <head>3 <title>Hello</title>4 <meta http-equiv="Content-Type" content="text/html;">5 <link rel="stylesheet" href="res/styles.css" 6 type="text/css"/>7 </head>8 <body>9 <h1>Hello!</h1> 10 <form action="HelloSvlt" method="POST">11 <table>12 <tr>13 <td>What's your name? </td>14 <td><input type="text" name="username"/></td>15 </tr>16 17

17 <tr>18 <td>What's your role:</td>19 <td>20 <select name="role"> 21 <option value="student">Student</option>22 <option value="instructor">Instructor</option>23 <option value="adm">Administrator</option>24 </select>25 </td>26 </tr>27 <tr>28 <td colspan="2">29 <input type="submit" value="Submit">30 </td>31 </tr>32 </table> 33 </form>34 </body>35 </html>

Example HTML Form

Example HTML Form

QuizYou are creating a web form with this HTML:

11. <form action="sendOrder.jsp">

12. <input type="text" name="creditCard">

13. <input type="text" name="expirationDate">

14. <input type="submit">

15. </form>

> Which HTTP method is used when sending this request from the browser?

a. GET

b. PUT

c. POST

d. SEND

e. FORM

Topics> Collecting Data from the User

> How Form Data Is Sent in an HTTP Request

> Developing a Servlet That Retrieves Form Parameters

> Developing Web Applications Using Session Management

> Using Cookies for Session Management

> Using URL Rewriting for Session Management

How Form Data Is Sent in an HTTP Request> Syntax:

> Examples:

fieldName1=fieldValue1&fieldName2=fieldValue2&...

username=weblogic&role=studentseason=Winter&year=2013&title=Westminster+Indoor+Soccer

GET /lesson04/HelloSvlt?username=jackb&role=student HTTP/1.1Host: localhost:7001User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.1)

Gecko/20100101 Firefox/10.0.1Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip, deflateConnection: keep-aliveReferer: http://localhost:8080/lesson04/helloForm.html

HTTP GET Method Request> Request stream

HTTP GET Method Request> Parameters defined

Parameter Name Parameter Value

username jackb

role student

HTTP POST Method Request> Request stream

POST /lesson04/HelloSvlt HTTP/1.1Host: localhost:7001User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.1)

Gecko/20100101 Firefox/10.0.1Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip, deflateConnection: keep-aliveReferer: http://localhost:7001/lesson04/helloForm.htmlContent-Length: 30Content-Type: application/x-www-form-urlencoded

username=jackb&role=student

GET and POST Requests

GET Request POST Request

Type of Use Default Form submission

Method of Sending Form Data

• Sent with the URI

• Size limited (8 K)

• Request processing is idempotent.

• Sent in the request body

• Size unlimited (2 G)

• Request processing is not idempotent.

Benefits and Drawbacks

• Form data is viewable in the browser's address bar

• A form can be resubmitted with a bookmark.

• Form data is not displayed in the browser's address bar (suitable for passwords).

• A form cannot be resubmitted with a bookmark.

Quiz> When you access a page using your web browser address

bar, which HTTP method is used?

a. OPTIONS

b. HEAD

c. POST

d. GET

e. TRACE

f. CONNECT

g. PUT

h. DELETE

Topics> Collecting Data from the User

> How Form Data Is Sent in an HTTP Request

> Developing a Servlet That Retrieves Form Parameters

> Developing Web Applications Using Session Management

> Using Cookies for Session Management

> Using URL Rewriting for Session Management

Developing a Servlet That Retrieves Form Parameters

> Form-processing servlets usually perform the following tasks:

– Retrieve form parameters from the HTTP request

– Perform any data conversion on the form parameters

– Verify the form parameters

– Execute the business logic

– Dispatch to the next view components based on the results of the previous steps

Servlet API to Retrieve Form Parameters

<<interface>> ServletRequest

<<interface>> Servlet

service(req,resp)

<<interface>> ServletResponse

<<interface>> HttpServletResponse

<<interface>> HttpServletRequest

HttpServlet{abstract}

servicedoGetdoPost

HelloServlet

doPost

Your servlet can access parameters from the HTML form by using the request object.

getParameter(name)getParameterValues(name)getParameterNames():Enum

HelloServlet Class 1 package com.examples.lesson04;

2 import java.io.IOException;

3 import java.io.PrintWriter;

4 import javax.servlet.ServletException;

5 import javax.servlet.annotation.WebServlet;

6 import javax.servlet.http.HttpServlet;

7 import javax.servlet.http.HttpServletRequest;

8 import javax.servlet.http.HttpServletResponse;

9

10 @WebServlet(name = "HelloServlet" ,

11 urlPatterns = {"/HelloSvlt"})

12 public class HelloServlet extends HttpServlet {

13

14 @Override

15 protected void doPost(HttpServletRequest request,

16 HttpServletResponse response)

17 throws ServletException, IOException {

18 response.setContentType("text/html;charset=UTF-8");

19 PrintWriter out = response.getWriter();

20 out.println("<html>");

HelloServlet Class 21 out.println("<head>");

22 out.println("<title>Hello</title>");

23 out.println("<link rel=\"stylesheet\"

24 href=\"../res/styles.css\"

25 type=\"text/css\"/>");

26 out.println("</head>");

27 out.println("<body>");

28

29 String username = request.getParameter("username");

30 String role = request.getParameter("role");

31

32 out.println("<h1>Hello " + username + "</h1>");

33 out.println("<h3>You are a " + role + "</h3>");

34

35 out.println("<a href=\"helloForm.html\">Go Back</a> ");

36 out.println("<a href=\"index.html\">Go Home</a>");

37 out.println("</body>");

38 out.println("</html>");

39 }

40 }

Quiz> Given an object HttpServletRequest request,

which methods can you use to get the form data parameters? (Choose two.)

a. request.getAttribute

b. request.getParameter

c. request.getAttributeValues

d. request.getParameterValues

e. request.getHeader

Topics> Collecting Data from the User

> How Form Data Is Sent in an HTTP Request

> Developing a Servlet That Retrieves Form Parameters

> Developing Web Applications Using Session Management

> Using Cookies for Session Management

> Using URL Rewriting for Session Management

HTTP Sessions> HTTP is stateless and therefore is good for clustering.

> Sessions are not directly supported.

> The browser must return identification data with every request.

– The HttpSession class addresses this need.

HttpSession API

<<interface>> HttpServletRequest

getSession(create:boolean) getSession()

<<interface>> HttpSession

getID():stringisNew():booleangetAttribute(name):ObjectsetAttribute(name,value)removeAttribute(name)

session

javax.servlet.http

The session object can hold any number of objects using the xyzAttribute

methods.

HttpSession API> getSession

> getSession(boolean)

> s.setAttribute("key", value)

> s.getAttribute("key")

> invalidate

> setMaxInactiveInterval

Calling the getSession()

method is equivalent to calling getSession(true).

Specifies the time between client requests before the container invalidates this session.

HttpSession session = request.getSession();session.setAttribute("league", league);

Because session is a map, a key must be used to identify this

particular object when it is later retrieved.

HttpSession API

HttpSession session = request.getSession();League theLeague= (League)session.getAttribute("league");

Notice that the return type of getAttribute is Object, so a cast must be

used before assigning the returned value to a reference variable.

<<interface>> HttpSession

invalidate()getCreationTime():longgetLastAccessedTime():longgetMaxInactiveInterval():intsetMaxInactiveInterval(int)

QuizGiven an HttpServletRequest request and an HttpServletResponse response:

41. HttpSession session = null;

42. // insert code here

43. if(session == null) {

44. // do something if session does not exist

45. } else {

46. // do something if session exists

47. }

> To implement the design intent, which statement must be inserted at line 42?a. session = response.getSession();b. sesion = request.getSession();

c. session = request.getSession(true);

d. session = request.getSession(false);e. session = request.getSession("jsessionid");

Topics> Collecting Data from the User

> How Form Data Is Sent in an HTTP Request

> Developing a Servlet That Retrieves Form Parameters

> Developing Web Applications Using Session Management

> Using Cookies for Session Management

> Using URL Rewriting for Session Management

Using Cookies for Session Management> Cookies are key-value data pairs stored on the browser.

> Cookies are created and updated in a server response to the browser.

> Cookies are stored by the browser in the client system.

> Cookies can be partitioned by server and path.

> All relevant cookies are sent by the browser to the server with every request.

> Cookies can have lifespan limits.

> HTTP-Only cookies are not available to script code.

Cookie API

> Create cookies with new Cookie(name, value).

> Use response.addCookie to set the stored value.

> Use request.getCookies to read cookies.

> Cookie.setHttpOnly(true) sets the HTTP-Only mode.

cookies

<<interface>> HttpServletResponse

addCookie(Cookie)

Cookie

<<properties>>name : string <<RO>>

value : string <<RW>>comment : string <<RW>>domain : string <<RW>>

path : string <<RW>>maxAge : int <<RW>>

<<constructors>>Cookie(name,value)

cookies

javax.servlet.http

A Cookie object

has accessorsand mutators for each property.

<<interface>> HttpServletRequest

getCookies(): Cookie[]

Using Cookies> To store a username from a form for future use:

String name = request.getParameter("firstName");

Cookie c = new Cookie("yourname", name);

response.addCookie(c);

> To retrieve the username on a subsequent request:

Cookie[] allCookies = request.getCookies();

for ( int i=0; i < allCookies.length; i++ ) {

if ( allCookies[i].getName().equals("yourname") ) {

name = allCookies[i].getValue();

}

}

Performing Session Management Using Cookies

Client soccer.comWeb container

Web Browser

JSESSIONID=1234

Cookie file

sessionID=1234leagueAplayerA

SelectDivisionAction

soccer.com

car.comdot.com

cookies cookies

cookies

Quiz> A web application uses a cookie to track a client as it

navigates through the pages that constitute the application.

> Which code snippet can be used by the web application to reduce the chance of a cross-site scripting attack by setting some property of the cookie before returning it to the client?

a. cookie.setHttpOnly(true)

b. cookie.setMaxAge(3600)

c. cookie.setPath("/")

d. cookie.setSecure(true)

Topics> Collecting Data from the User

> How Form Data Is Sent in an HTTP Request

> Developing a Servlet That Retrieves Form Parameters

> Developing Web Applications Using Session Management

> Using Cookies for Session Management

> Using URL Rewriting for Session Management

Using URL Session Management> HttpSession uses cookies by default.

> The cookie name (session ID) must be JSESSIONID.

> URL rewriting is provided as a fallback.

> URL encoding must be used for URL rewriting to work properly:out.println("<form action=’"+

response.encodeURL("enter_player.do") +

"‘ method=’POST’>");

User Workstation

WebBrowser

request

response

Application Server

Web Container

http://host/file;jsessionid=1234

All URLs in the text of the HTML response must include the JSESSIONID path info.

Cookies Versus URL Rewriting

Session Binding Technique

Advantages Disadvantages

CookiesThe container reads and writes cookies, so there is no additional work for you.

Not all browsers support cookies.

URL rewritingThe URL rewriting technique works without cookie support.

You must ensure that the session ID is appended to every URL that the browser sees.

Session Configuration> web.xml can specify default session timeout and

preferred session tracking:

<web-app ...>

<session-config>

<session-timeout>30</session-timeout>

<tracking-mode>SSL</tracking-mode>

</session-config>

</web-app>


Recommended