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

Web Programming with JavaJava Server PagesHuynh Huu Viet University of Information Technology docx

106 202 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề Web Programming with JavaJava Server Pages
Trường học University of Information Technology
Chuyên ngành Web Programming
Thể loại Tài liệu hướng dẫn
Năm xuất bản 2008
Thành phố Hồ Chí Minh
Định dạng
Số trang 106
Dung lượng 2,19 MB

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

Nội dung

JSP Frameworkƒ Use regular HTML for most of page ƒ Mark servlet code with special tags ƒ Entire JSP page gets translated into a servlet once, and servlet is what actually gets invoked f

Trang 1

Web Programming with Java

Java Server Pages

Huynh Huu Viet

University of Information Technology Department of Information Systems

Email: viethh@uit.edu.vn

Trang 2

Controller (MVC) Architecture

Trang 3

The Need for JSP

™ With servlets, it is easy to

ƒ Read form data

ƒ Read HTTP request headers

ƒ Set HTTP status codes and response headers

ƒ Use cookies and session tracking

ƒ Share data among servlets

ƒ Remember data between requests

ƒ Get fun, high-paying jobs

™ But, it sure is a pain to

ƒ Use those println statements to generate HTML

ƒ Maintain that HTML

Trang 4

JSP Framework

ƒ Use regular HTML for most of page

ƒ Mark servlet code with special tags

ƒ Entire JSP page gets translated into a servlet (once), and servlet

is what actually gets invoked (for each request)

Trang 5

Benefits of JSP

™ Although JSP technically can't do anything servlets can't do, JSP makes it easier to:

ƒ Write HTML

ƒ Read and maintain the HTML

™ JSP makes it possible to:

ƒ Use standard HTML tools such as Macromedia

DreamWeaver or Adobe GoLive

ƒ Have different members of your team do the HTML layout than do the Java programming

™ JSP encourages you to

ƒ Separate the (Java) code that creates the content

from the (HTML) code that presents it

Trang 6

Advantages of JSP Over Competing Technologies (1)

™ Versus ASP or ColdFusion

ƒ Better language for dynamic part

ƒ Portable to multiple servers and operating systems

™ Versus PHP

ƒ Better language for dynamic part

ƒ Better tool support

™ Versus pure servlets

ƒ More convenient to create HTML

ƒ Can use standard tools (e.g., DreamWeaver)

ƒ Divide and conquer

ƒ JSP programmers still need to know servlet

programming

Trang 7

Advantages of JSP Over Competing Technologies (2)

™ Versus client-side JavaScript (in browser)

ƒ Capabilities mostly do not overlap with JSP, but

• You control server, not client

Trang 8

<HTML>

<HEAD>

<TITLE>JSP Expressions</TITLE>

<META NAME="keywords" CONTENT="JSP,expressions,JavaServer Pages">

<META NAME="description“ CONTENT="A quick example of JSP expressions.">

<LINK REL=STYLESHEET HREF="JSP-Styles.css“ TYPE="text/css">

<LI>Session ID: <%= session.getId() %>

<LI>The <CODE>testParam</CODE> form parameter:

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

</UL>

</BODY>

</HTML>

Trang 9

JSP Lifecycle

Trang 10

JSP/Servlets in the Real World

Web sites [1]

ƒ 1) Google

• Custom technology,some Java

Trang 11

Some webpages using JSP

Trang 12

Controller (MVC) Architecture

Trang 13

framework like Struts or JSF

Simple

Application

Complex

Application

Trang 14

Design Strategy: Limit Java code in JSP Pages

™ You have two options

ƒ Put 25 lines of Java code directly in the JSP page

ƒ Put those 25 lines in a separate Java class and put 1 line in the JSP page that invokes it

™ Why is the second option much better?

ƒ Development You write the separate class in a

Javaenvironment (editor or IDE), not an HTML

environment

ƒ Debugging If you have syntax errors, you see

themimmediately at compile time Simple print

statements can be seen

ƒ Testing You can write a test routine with a loop that

does 10,000 tests and reapply it after each change

ƒ Reuse You can use the same class from multiple

pages

Trang 17

JSP Expressions

ƒ <% =Java Expression %>

ƒ Expression evaluated, converted to String, and placed into

HTML page at the place it occurred in JSP page

ƒ That is, expression placed in _jspService inside out.print

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

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

ƒ <jsp:expression> Java Expression </jsp:expression>

ƒ You cannot mix versions within a single page You must page

use XML for entire page if you use jsp:expression.

• See slides at end of this lecture

Trang 18

JSP/Servlet Correspondence

ƒ <H1>A Random Number</H1>

ƒ <%= Math.random() %>

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

HttpSession session = request.getSession();

JspWriter out = response.getWriter();

out.println("<H1>A Random Number</H1>");

out.println(Math.random());

}

Trang 19

ƒ The Writer (a buffered version of type JspWriter) used

to send output to the client

Trang 21

String queryData = request.getQueryString();

out.println("Attached GET data: " + queryData);

Trang 22

public void _jspService(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

HttpSession session = request.getSession();

JspWriter out = response.getWriter();

out.println("<H2>foo</H2>");

out.println(bar());

baz();

Trang 23

JSP Scriptlets Example

customize the background color of a page

<BODY BGCOLOR=

"<%= request.getParameter("bgColor") %>">

Trang 25

Make Parts of the JSP File Conditional

ƒ Scriplets are inserted into servlet exactly as written

ƒ Need not be complete Java expressions

ƒ Complete expressions are usually clearer and easier to maintain, however

Trang 26

JSP Declarations

™ Format

ƒ <%!Java Code %>

™ Result

ƒ Code is inserted verbatim into servlet's class

definition, outside of any existing methods

™ Examples

ƒ <%! private int someField = 5; %>

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

™ Design consideration

ƒ Fields are clearly useful For methods, it is usually

better to define the method in a separate Java class

™ XML-compatible syntax

ƒ <jsp:declaration> Java Code</jsp:declaration>

Trang 28

JSP/Servlet Correspondence (2)

public class xxxx implements HttpJspPage {

private String randomHeading() {

return("<H2>" + Math.random() + "</H2>");

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html");

HttpSession session = request.getSession();

JspWriter out = response.getWriter();

Trang 29

<%! private int accessCount = 0; %>

<H2>Accesses to page since server reboot:

<%= ++accessCount %></H2>

</BODY></HTML>

Trang 30

jspInit and jspDestroy Methods (1)

™ JSP pages, like regular servlets, sometimes want to use init and destroy

™ Problem: the servlet that gets built from the JSP page might already use init and destroy

ƒ Overriding them would cause problems

ƒ Thus, it is illegal to use JSP declarations to declare init or destroy

™ Solution: use jspInit and jspDestroy.

ƒ The auto-generated servlet is guaranteed to call

these methods from init and destroy, but the standard versions of jspInit and jspDestroy are empty

(placeholders for you to override)

Trang 31

jspInit and jspDestroy Methods (2)

out.println("The number is " + num + "<br>");

out.println("The counter is " + count + "<br>");

%>

</body>

</html>

Trang 32

Predefined Variables

ƒ The predefined variables (request, response, out, session, etc.)

are local to the _jspService method Thus, they are not available

to methods defined by JSP declarations or to methods in helper classes What can you do about this?

ƒ And they are usually preferred over JSP declarations

ƒ

Trang 33

When to use Expressions, Scriptlets or Declarations

ƒ Output a bulleted list of five random ints from 1 to 10.

ƒ Since the structure of this page is fixed and we use a separate helper class for the randomInt method,

ƒ JSP expressions are all that is needed.

ƒ Generate a list of between 1 and 10 entries (selected at

random), each of which is a number between 1 and 10.

ƒ Because the number of entries in the list is dynamic, a

Trang 34

™ RanUtilities Class

/** Simple utility to generate random integers */ public class RanUtilities {

/** A random int from 1 to range (inclusive) */

public static int randomInt(int range) {

return(1 + ((int)(Math.random() * range))); }

public static void main(String[] args) { int range = 10;

Trang 36

%>

</UL>

</BODY></HTML>

Trang 39

JSP Pages with XML Syntax

™ Why Two Versions

ƒ Classic syntax is not XML-compatible

• <%= %>, <% %>, <%! %> are illegal in XML

• HTML 4 is not XML compatible either

• So, you cannot use XML editors like XML Spy

ƒ You might use JSP in XML environments

• To build xhtml pages

• To build regular XML documents

– You can use classic syntax to build XML documents, but it is sometimes easier if you are working in XML to start with

» For Web services

» For Ajax applications

ƒ So, there is a second syntax

Trang 40

Sample HTML 4 Page: Classic Syntax (sample.jsp)

Trang 41

Sample XHTML Page: XML Syntax (sample.jspx)

Trang 42

Controller (MVC) Architecture

Trang 43

Purpose of the page Directive

servlet that will result from the JSP

page

ƒ If the servlet participates in sessions

Trang 44

The import Attribute

ƒ Although JSP pages can be almost anywhere on

server, classes used by JSP pages must be in normal servlet dirs

Trang 45

The Importance of Using Packages

™ What package will the system think that SomeHelperClass and SomeUtilityClass are in?

public class SomeClass {

public String someMethod( ) {

SomeHelperClass test = new SomeHelperClass( );

String someString = SomeUtilityClass.someStaticMethod( );

Trang 46

The contentType and pageEncoding Attributes

ƒ Attribute value cannot be computed at request time

ƒ See section on response headers for table of the

most common MIME types

Trang 47

Example: Conditionally Generating Excel Spreadsheets

™ You cannot use the contentType attribute

for this task, since you cannot make

Trang 48

Example: Conditionally Generating Excel Spreadsheets

<BODY>

<CENTER>

<H2>Comparing Apples and Oranges</H2>

<%

String format = request.getParameter("format");

if ((format != null) && (format.equals("excel"))) { response.setContentType("application/vnd.ms-excel"); }

Trang 49

The session Attribute

ƒ By default, it is part of a session

ƒ Saves memory on server if you have a high-traffic site

ƒ All related pages have to do this for it to be useful

Trang 50

The buffer Attribute

ƒ Servers are allowed to use a larger size than you ask for, but not a smaller size

ƒ Default is system-specific, but must be at least 8kb

Trang 51

The errorPage Attribute

™ Format

ƒ <%@ page errorPage="Relative URL" %>

™ Purpose

ƒ Specifies a JSP page that should process any

exceptions thrown but not caught in the current page

™ Notes

ƒ The exception thrown will be automatically available

to the designated error page by means of the

"exception“ variable

ƒ The web.xml file lets you specify application-wide

error pages that apply whenever certain exceptions or certain HTTP status codes result

• The errorPage attribute is for page-specific error pages

™ Example: ComputeSpeed.jsp

Trang 52

The extends Attribute

ƒ Use with extreme caution

ƒ Can prevent system from using high-performance

custom superclasses

ƒ Typical purpose is to let you extend classes that

come from the server vendor (e.g., to support

personalization features), not to extend your own

classes

Trang 53

The isThreadSafe Attribute

™ A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads

ƒ To tell the system when your code is not threadsafe,

so that the system can prevent concurrent access

• Normally tells the servlet to implement SingleThreadModel

™ Notes

ƒ Avoid this like the plague

• Causes degraded performance in some situations

• Causes incorrect results in others

Trang 54

Non-Threadsafe Example Code (1)

<%! private int idNum = 0; %>

Trang 55

Non-Threadsafe Example Code (2)

™ Is isThreadSafe Needed Here?

ƒ No! It is not needed Synchronize normally:

<%! private int idNum = 0; %>

Trang 56

Controller (MVC) Architecture

Trang 57

jsp:include:Including Pages at Request Time

™ Format

ƒ <jsp:include page="Relative address" />

™ Purpose

ƒ To reuse JSP, HTML, or plain text content

ƒ To permit updates to the included content without

changing the main JSP page(s)

™ Notes

ƒ JSP content cannot affect main page: only outputof

included JSP page is used

™ Don’t forget that trailing slash

™ Relative URLs that starts with slashes are

interpreted relative to the Web app, not

relative to the server root.

™ You are permitted to include files from INF

Trang 58

it has only the tags appropriate to the place that it

will be inserted

Trang 59

jsp:param: Augmenting Request Parameters

Trang 60

<%@ include %>:Including Files at Page Translation Time

™ Format

ƒ <%@ include file="Relative address" %>

™ Purpose

ƒ To reuse JSP content in multiple pages, where JSP

content affects main page

™ Notes

ƒ Servers are not required to detect changes to the

included file, and in practice they don’t

ƒ Thus, you need to change the JSP files whenever the included file changes

ƒ You can use OS-specific mechanisms such as the

Unix “touch” command, or

• <% Navbar.jsp modified 10/ %>

Trang 61

jsp:include vs <%@ include …>

Trang 62

Which Should We Use?

™ Use jsp:include whenever possible

ƒ Changes to included page do not require any manual updates

ƒ Speed difference between jsp:include and the include directive (@include) is insignificant

ƒ The include directive (<%@ include …%>) has

additional power, however

Trang 63

Understanding jsp:include vs <%@ include … %>

(instance variable)

would have to use @include

not use accessCount

Trang 64

Controller (MVC) Architecture

Trang 65

Uses of JSP Constructs

code directly

code indirectly (by means of utility classes)

™ Beans

framework like Struts or JSF

Simple

Application

Complex

Application

Trang 66

What Are Beans?

™ Java classes that follow certain conventions

ƒ Must have a zero-argument (empty) constructor

• You can satisfy this requirement either by explicitly defining such a constructor or by omitting all constructors

ƒ Should have no public instance variables (fields)

• I hope you already follow this practice and use accessor methods instead of allowing direct access to fields

ƒ Persistent values should be accessed through

methods called getXxx and setXxx

• If class has method getTitle that returns a String, class is said

to have a String property named title

• Boolean properties use isXxx instead of getXxx

ƒ For more on beans, see

• http://java.sun.com/beans/docs/

Trang 67

Why Use Beans?

• Can manipulate Java objects using only compatible syntax: no parentheses, semicolons, or curly braces

XML-• Promote a stronger separation between the content and the presentation

parameters and object properties

Trang 68

Why You Should Use Accessors, Not Public Fields (1)

™ To be a bean, you cannot have public fields

™ So, you should replace

public double speed;

private double speed;

public double getSpeed() {

Trang 69

Why You Should Use Accessors, Not Public Fields (2)

™ You can put constraints on values

public void setSpeed(double newSpeed) {

™ If users of your class accessed the fields

directly, then they would each be

responsible for checking constraints.

Trang 70

Why You Should Use Accessors, Not Public Fields (3)

™ You can change your internal representation without changing interface

// Now using metric units (kph, not mph)

public void setSpeed(double newSpeed)

Trang 71

Why You Should Use Accessors, Not Public Fields (4)

public double setSpeed(double newSpeed) {speed = newSpeed;

updateSpeedometerDisplay();

}

fields directly, then they would each

be responsible for executing side

effects

having display inconsistent from

actual values.

Ngày đăng: 27/06/2014, 21:20

TỪ KHÓA LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm