1. Trang chủ
  2. » Công Nghệ Thông Tin

Web Programming with Java pptx

68 985 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 68
Dung lượng 891,65 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Processing Requestsƒ Read values from request • HttpServletRequest req ƒ Process and log as required ƒ Write response to client • HttpServletResponse res method ƒ Returns a PrintWriter t

Trang 1

Web Programming with Java

Servlets

Huynh Huu Viet

University of Information Technology Department of Information Systems

Email: viethh@uit.edu.vn

Trang 2

™ Introduction

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

™ Retrieving and Sending HTML

™ Servlet Sessions

Trang 3

™ Java networking capabilities:

Trang 4

™ Servlets: small Java programs that

run on a web server

™ Provide web-based applications

™ Extends functionality of web server

Trang 5

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

™ Retrieving and Sending HTML

™ Servlet Sessions

Trang 6

™ Generate the results

™ Send the explicit data back to client

(HTML or binary)

™ Send the implicit data back to client

(status codes and response headers)

Trang 7

Why Build Web Pages Dynamically?

™ The web page is based on data given

by the user

confirmation pages at on-line stores

™ The web page is derived from data

that changes frequently

™ The web page uses information from databases or other server-side

sources

availability

Trang 8

™ Servlet basics

™ The Servlet Lifecycle

™ Retrieving and Sending HTML

™ Servlet Sessions

Trang 9

Servlet Basics

™ Servlet container (or Servlet engine)

™ Web servers and application servers

Trang 10

Servlet Architecture

Trang 11

Creating a Servlet

ƒ Part of J2EE application server

ƒ Also come with Tomcat reference implementation

javax.servlet.GenericServlet

ƒ Seldom do this

javax.servlet.http.HttpServlet

ƒ Override doGet() or doPost() to handle GET and

ƒ POST requests from browser

Trang 12

Processing Requests

ƒ Read values from request

• HttpServletRequest req

ƒ Process and log as required

ƒ Write response to client

• HttpServletResponse res

method

ƒ Returns a PrintWriter to write data to client

ƒ Use setContentType() before writing any data

ƒ E.g res.setContentType("text/html");

Trang 13

Example

Trang 14

™ The Servlet Lifecycle

™ Retrieving and Sending HTML

™ Servlet Sessions

Trang 15

The Servlet Lifecycle

™ Init

ƒ Not called for each request.

ƒ

Trang 16

Why You Should Not Override service

™ The service method does other things besides just calling doGet

ƒ You can add support for other services

later by adding doPut, doTrace, etc.

ƒ You can add support for modification

dates by adding a getLastModified method

ƒ The service method gives you automatic support for:

Trang 17

™ Introduction

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

Trang 18

Creating Form Data: HTML Forms

<HTML>

<HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD>

<BODY BGCOLOR="#FDF5E6">

<H2 ALIGN="CENTER">A Sample Form Using GET</H2>

You normally use a relative URL for the ACTION This URL is just for testing because

<FORM ACTION="SomeProgram" >

<CENTER>

First name:

I am running a test server that echoes the data it receives.

<INPUT TYPE="TEXT" NAME="firstName " VALUE="J Random"><BR>

Last name:

<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>

<INPUT TYPE="SUBMIT"> <! Press this to submit form >

</CENTER>

</FORM>

</BODY>

</HTML>

Trang 20

Reading Form Data

ƒ Returns URL-decoded value of first occurrence of

name in query string

ƒ Works identically for GET and POST requests

ƒ Returns null if no such parameter is in query data

ƒ Returns an array of the URL-decoded values of all

occurrences of name in query string

ƒ Returns a one-element array if param not repeated

ƒ Returns null if no such parameter is in query

request.getParameterMap()

ƒ Returns Enumeration or Map of request params

ƒ Usually reserved for debugging

Trang 21

Reading All Parameters

Enumeration paramNames = request.getParameterNames();

}

}

Trang 22

Checking for Missing and Malformed Data

ƒ Field missing in form

• getParameter returns null

ƒ Field blank when form submitted

• getParameter returns an empty string (or possibly a

string with whitespace in it)

ƒ Must check for null before checking for empty string

• String param = request.getParameter("someName");

• if ((param == null) || (param.trim().equals(""))) {

Trang 23

Handling Missing and Malformed Data

ƒ Replace missing values with application-specific

standard values

ƒ Show the form again, with missing values flagged

ƒ Previously-entered values should be preserved

ƒ Four options to implement this

• Have the same servlet present the form, process the data, and present the results.

• Have one servlet present the form; have a second servlet process the data and present the results.

• Have a JSP page “manually” present the form; have a servlet

or JSP page process the data and present the results.

• Have a JSP page present the form, automatically filling in the fields with values obtained from a data object Have a servlet

or JSP page process the data and present the results

Trang 24

™ Introduction

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

Trang 27

Common HTTP 1.1 Request Headers (1)

ƒ Indicates MIME types browser can handle

ƒ Can send different content to different clients For

example, PNG files have good compression

characteristics but are not widely supported in

browsers

• A servlet could check to see if PNG is supported, sending

<IMG SRC="picture.png" > if it is supported, and <IMG SRC="picture.gif" > if not.

ƒ Warning: IE incorrectly sets this header when you hit the Refresh button It sets it correctly on original

request

ƒ Indicates encodings (e g gzip or compress) browser can handle

Trang 28

Common HTTP 1.1 Request Headers (2)

ƒ Servlets can't do this unilaterally; the best they can do is to give the server enough info to permit persistent connections So, they should set Content-Length with setContentLength (using

ByteArrayOutputStream to determine length of output).

™ Cookie

ƒ Gives cookies previously sent to client Use getCookies not

getHeader.

Trang 29

Common HTTP 1.1 Request Headers (3)

fact is important to know if you write a custom HTTP client or telnet to a server and use the HTTP/1.1 version.

™ User-Agent

• Web browser vs I-mode cell phone, etc

possible

Trang 30

Common HTTP 1.1 Request Headers (4)

™ Referer

servers

and then return to the page they came from

be sole means of deciding how much to pay sites that show your banner ads.

Washer), and personal firewalls (Norton)

Trang 31

public class WrongDestination extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException { String userAgent = request.getHeader("User-Agent");

if ((userAgent != null) && (userAgent.contains("MSIE")) {

Trang 32

HTTP Request/Response

Trang 33

™ Introduction

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

Trang 34

Setting Status Codes

™ response.setStatus(int statusCode)

Constants are in HttpServletResponse

SC_OK, SC_NOT_FOUND, etc.

™ response.sendError(int code,String

message)

™ response.sendRedirect(String url)

Trang 35

Common HTTP 1.1 Status Codes

ƒ Everything is fine; document follows

ƒ Default for servlets

ƒ Browser should keep displaying previous document

(indicated in Location header)

ƒ Browsers go to new location automatically

ƒ Browsers are technically supposed to follow 301 and

302 (next page) requests only when the incoming

request is GET, but do it for POST with 303 Either way, the Location URL is retrieved with GET

Trang 36

Common HTTP 1.1 Status Codes (2)

ƒ Requested document temporarily moved elsewhere (indicated in Location header)

ƒ Browsers go to new location automatically

ƒ Servlets should use sendRedirect, not setStatus,

when setting this header See example

ƒ Browser tried to access password-protected page

without proper Authorization header

Trang 37

™ Introduction

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

Trang 38

HTTP Response Headers

Trang 39

Setting Arbitrary Response Headers

ƒ Sets an arbitrary header

ƒ Adds new occurrence of header instead of replacing

Trang 40

Setting Common Response Headers

ƒ Sets the Content-Type header

ƒ Servlets almost always use this

ƒ Sets the Content-Length header

ƒ Used for persistent HTTP connections

ƒ See Connection request header

ƒ Adds a value to the Set-Cookie header

ƒ See separate section on cookies

Trang 41

Common MIME Types

Trang 42

™ Building Excel Spreadsheets

public class ApplesAndOranges extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

response.setContentType ("application/vnd.ms-excel");

PrintWriter out = response.getWriter();

out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");

out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)"); out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)"); }

Trang 43

Common HTTP 1.1 Response Headers (1)

ƒ A no-cache value prevents browsers from caching

page

ƒ Lets you request that the browser ask the user to

save the response to disk in a file of the given name

ƒ Content-Disposition: attachment; filename=file-name

ƒ The way document is encoded See earlier

compression example

ƒ The number of bytes in the response

ƒ See setContentLength on previous slide

ƒ Use ByteArrayOutputStream to buffer document

before sending it, so that you can determine size

Trang 44

Common HTTP 1.1 Response Headers (2)

ƒ The MIME type of the document being returned

ƒ Use setContentType to set this header

ƒ The time at which document should be considered

out-of date and thus should no longer be cached

ƒ Use setDateHeader to set this header

ƒ The time document was last changed

ƒ Don’t set this header explicitly; provide a

getLastModified method instead

Trang 45

Common HTTP 1.1 Response Headers (3)

ƒ The URL to which browser should reconnect

ƒ Use sendRedirect instead of setting this directly

Trang 46

™ Introduction

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

™ Retrieving and Sending HTML

ƒ Session tracking

Trang 47

ƒ Servlet sends a simple name and value to client

ƒ Client returns same name and value when it connects

to same site (or same domain, depending on cookie settings)

ƒ Identifying a user during an e-commerce session

ƒ Servlets have a higher-level API for this task

ƒ Customizing a site

ƒ Focusing advertising

Trang 48

Some Problems with Cookies

ƒ Servers can remember your previous actions

ƒ If you give out personal information, servers can link that information to your previous actions

ƒ Servers can share cookie information through use of acooperating third party like doubleclick.net

ƒ Poorly designed sites store sensitive information like credit card numbers directly in cookie

ƒ JavaScript bugs let hostile sites steal cookies (old

browsers)

ƒ If cookies are not critical to your task, avoid servlets that totally fail when cookies are disabled

ƒ Don't put sensitive info in cookies

Trang 49

Sending Cookies to the Client

ƒ Call the Cookie constructor with a cookie name and a cookie value, both of which are strings

– Cookie c = new Cookie("userID", "a1234");

ƒ To tell browser to store cookie on disk instead of just

in memory, use setMaxAge (argument is in seconds)

– c.setMaxAge(60*60*24*7); // One week

ƒ If you forget this step, no cookie is sent to the

browser!

Trang 50

Reading Cookies from the Client

ƒ This yields an array of Cookie objects

each entry until you find the cookie of

interest

ƒ Use the value (getValue) in application-specific way

String cookieName = "userID";

Cookie[] cookies = request.getCookies();

if (cookies != null) { for(Cookie cookie: cookies) {

if (cookieName.equals(cookie.getName())) {

doSomethingWith(cookie.getValue());

} }

Trang 51

Example: Using Cookies to detect First-Time Visitors

public class RepeatVisitor extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException { boolean newbie = true;

Cookie[] cookies = request.getCookies();

if (cookies != null) {

for(int i=0;i<cookies.length;i++) { Cookie c=cookies[i]

if ((c.getName().equals("repeatVisitor")) &&

(c.getValue().equals("yes"))) { newbie = false;

break;

} } }

String title;

if (newbie) {

Cookie returnVisitorCookie = new Cookie("repeatVisitor", "yes");

returnVisitorCookie.setMaxAge(60*60*24*365);

response.addCookie(returnVisitorCookie);

Trang 52

Using Cookie Attributes

ƒ Lets you specify domain to which cookie applies

Current host must be part of domain specified

ƒ Gets/sets the cookie expiration time (in seconds) If you fail to set this, cookie applies to current browsing session only See LongLivedCookie helper class

given earlier

ƒ Gets the cookie name There is no setName method; you supply name to constructor For incoming cookie array, you use getName to find the cookie of interest

Trang 53

Using Cookie Attributes

ƒ Lets you specify domain to which cookie applies

Current host must be part of domain specified

ƒ Gets/sets the cookie expiration time (in seconds) If you fail to set this, cookie applies to current browsing session only See LongLivedCookie helper class

given earlier

ƒ Gets the cookie name There is no setName method; you supply name to constructor For incoming cookie array, you use getName to find the cookie of interest

Trang 54

Using Cookie Attributes

ƒ Gets/sets flag indicating whether cookie should apply only to

SSL connections or to all connections.

™ getValue/setValue

ƒ Gets/sets value associated with cookie

ƒ For new cookies, you supply value to constructor, not to

setValue

ƒ For incoming cookie array, you use getName to find the cookie

of interest then call getValue on the result If you interest, result set the value of an incoming cookie, you still have to sendit back out with response.addCookie

Trang 55

Modifying Cookie Values

ƒ Send the same cookie name with a different cookie value

ƒ Reusing incoming Cookie objects

• Need to call response.addCookie; merely calling setValue is not sufficient.

• Also need to reapply any relevant cookie attributes by calling setMaxAge, setPath, etc.—cookie attributes are not specified for incoming cookies.

• Usually not worth the bother, so new Cookie object used

ƒ Use setMaxAge to assign a maximum age of 0

Trang 57

™ Introduction

™ Overview of Servlet technology

™ Servlet basics

™ The Servlet Lifecycle

™ Retrieving and Sending HTML

ƒ Cookies

ƒ Session tracking

Trang 58

Session Tracking

™ Why session tracking?

shopping cart, how does server know what’s already in cart?

how can server determine which previously created cart is theirs?

™ Sessions do not travel across network

Trang 59

Session Tracking in Java

client via cookies or URL-rewriting

ƒ Use request.getSession to get session

• Behind the scenes, the system looks at cookie or URL extra info and sees if it matches the key to some previously stored session object If so, it returns that object If not, it creates a new one, assigns a cookie or URL info as its key, and returns that new session object.

arbitrary objects inside session

ƒ setAttribute stores values

ƒ getAttribute retrieves values

Trang 60

Session Tracking Basics

ƒ Call request.getSession to get HttpSession object

• This is a hashtable associated with the user

session.

ƒ Call getAttribute on the HttpSession object, cast the return value to the appropriate type, and check

whether the result is null

ƒ Use setAttribute with a key and a value

ƒ Call removeAttribute discards a specific value

ƒ 10 Call invalidate to discard an entire session

Ngày đăng: 07/08/2014, 05:20