Вы находитесь на странице: 1из 45

JSP: Java Server Pages

Based on a presentation by Richard Cannings and Vicky Tsang


http://cannings.org/cpsc547

Also including slides from presentations by James D. Davidson for Sun Microsystems
http://java.sun.com/products/servlet/presentations/

24/05/2013

Presentation Purpose

The purpose of this presentation is:


To introduce JSP, To identify JSPs unique utility in dynamic web pages, To learn how to write JSP pages through examples.

24/05/2013

Assumptions

We assume you have introductory or peripheral knowledge of:


HTTP/1.0 (e.g. GET and POST) HTML 4.0 (e.g. simple tags) Java 1.1.x (syntax and structure)

24/05/2013

Topics

What is JSP? A Simple Hello, World. A Crash Course in JavaBeans More on Syntax. Internal JSP Architecture Overview of Servlets

24/05/2013

What is JSP?

http://java.sun.com/products/jsp, A way to create dynamic web pages, Server side processing, Based on Java Technology,
Large library base Platform independence

Separates the graphical design from the dynamic content.


5

24/05/2013

First Look at JSP Code


<html> <body> <b>Im HTML code.</b><br> <% out.println(Im Java code.) %> </body> </html>

24/05/2013

HelloWorld
<html> <head> <%-- JSP Declarations --%> <%! String world; %> <!-- JSP Code --> <% world = World; %> <title>Hello <%= world %></title> </head> <body> Hello, <%= world %>. </body> </html> Run Example: http://antares.math.tau.ac.il:6789/examples/jsp/HelloW orld.jsp
24/05/2013 7

JSP Syntax Comments

Two Types of Comments:

HTML Comments
For

HTML tags JSP tags

JSP Comments
For

24/05/2013

JSP Syntax

HTML Comment

Comment can be viewed in the HTML source file


<!-- comment <% expression%> --> Example:

<!-- this is just Html comment -->


<!-- This page was loaded on <%= (new java.util.Date()).toLocaleString()%> -->
View source: <!-- this is just Html comment --> <!-- This page was loaded on January 1, 2000 -->
24/05/2013 9

JSP Syntax

Hidden Comment

Comment cannot be viewed in the HTML source file


<% -- expression -- %> Example:
<html> <body> <h2>A Test of Comments</h2> <%--This comment will be invisible in page source --%> </body>
</html>

24/05/2013

10

JSP Syntax

Declaration

Declares a variable or method


<% ! declaration; %> Example:
<body> <%! String name; %> <% name = request.getParameter(name); if ( name == null ) name = World; %> <h1>Hello, <%= name %>. </h1> </body>

24/05/2013

11

JSP Syntax

Expression

Contains an expression
<% = expression %> Example:

<p>The map file has <%= map.size() %> entries. </p> <p> Good guess, but nope. Try <b> <% = numguess.getHint() %> </b></p>

24/05/2013

12

JSP Syntax

Scriptlet

Contains a code fragment


<% code fragment %> Example:
<% String name = null; if (request.getParameter(name) == null ) { %> Hello, World <% } else { println.out(Hello, + name); } %>

24/05/2013

13

JSP Syntax

Include Directive

Includes a static file


<%@ include file=relativeURL %> Example:
main.jsp: <html><body> Current date and time is: <%@include file=date.jsp %> </body></html> date.jsp: <%@page import =java.util.* %> <% =(new java.util.Date()).toLocaleString() %> Output : Current date and time is: Mar 5, 2000 4:56:50

24/05/2013

14

JSP Syntax

Page Directive

Defines attributes that apply to an entire page


<%@ page [ language=java ] [ extends=package.class ] [ import=package.class ] [ contentType=mimeType ] [ errorPage=relativeURL ] %>

Example:
<%@ page extends=myClass import=java.util.* contentType=text/html errorPage=error.jsp %>

24/05/2013

15

JSP Syntax

<jsp:forward>

Forwards request to another file (HTML, JSP, or Servlet) for processing


<jsp:forward page =relativeURL %>

Example:
<jsp:forward page=scripts/login.jsp /> or <jsp:forward page=scripts/login.jsp > <jsp:param name=username value=jsmith/> </jsp:forward>

24/05/2013

16

JSP Syntax

<jsp:include>

Includes a static or dynamic file


<jsp:include page =relativeURL %> Example:
<jsp:include page=scripts/login.jsp /> <jsp:include page=copyright.html />

24/05/2013

17

JavaBeans Interlude

http://java.sun.com/beans A component architecture for Java. Useful in JSP for encapsulating application logic and transferring data between pages. Beans are simply Java classes.

24/05/2013

18

JavaBeans for programmers


Beans must: Implement java.io.Serializable Have a constructor with no arguments Properties (a.k.a. alterable variables) must: Must have a get and set Must be private
24/05/2013 19

JavaBeans example
package mybeans; import java.io.Serializable;
public class NameBean implements Serializable { private String name; public NameBean() { super(); name = new String("World"); } public void setName( String name ) { this.name = name; } public String getName() { return name; } }
24/05/2013 20

JSP Syntax

<jsp:useBean>

Locates or instantiates a JavaBeans components.


<jsp:useBean id=beanInstanceName scope=page| request | session | application class=package.class />
Example: <jsp:useBean id=calendarscope=page class=employee.Calendar/>

24/05/2013

21

JSP Syntax

<jsp:setProperty>

Sets the value of one or more properties in a Bean, using the Beans setter methods. Declare the Bean with <jsp:useBean> first
<jsp:setProperty name=beanInstanceName property=propertyName value=string />
Example: <jsp:useBean id=calendarscope=page class=employee.Calendar/> <jsp:setProperty name=calendar property=username value=Steve/>

24/05/2013

22

JSP Syntax

<jsp:setProperty>

Setting the property attribute to the magic value * will automatically set properties according to the request parameters. You can also use the attribute param to set a specific parameter from the request value. Example:
<jsp:useBean id=calendar scope=session class=employee.Calendar/> <jsp:setProperty name=calendar property=username param=user/>

24/05/2013

23

JSP Syntax

<jsp:getProperty>

Gets a Bean property value, using the Beans getter methods. Declare the Bean with <jsp:useBean> first
<jsp:getProperty name=beanInstanceName property=propertyName />
Example: <jsp:useBean id=calendarscope=page class=employee.Calendar/> <H1>Calendar of <jsp:getProperty name=calendar property=username/> </H1>

24/05/2013

24

HelloWorld with Beans


<html> <head> <%-- START -- Included for nameBean calls --%> <%@ page import="mybeans.NameBean" %> <jsp:useBean id="nameBean" scope="request" class=mybeans.NameBean" /> <jsp:setProperty name="nameBean" property="*" /> <%-- END -- Included for nameBean calls --%> <title>Hello World with JavaBeans</title> </head> <body> Hello, <%= nameBean.getName() %>. </body> </html>

24/05/2013

25

HelloWorld execution
http://antares.math.tau.ac.il:6789/examples /jsp/HelloWorldBean.jsp http://antares.math.tau.ac.il:6789/examples /jsp/HelloWorldBean.jsp?name=Big+Wi de+World

24/05/2013

26

Web Application

JSP Web applications have a standard layout WEB-INF/web.xml: Deployment descriptor WEB-INF/classes: Local classpath

Beans are put here

WEB-INF/lib: Local .jar files

24/05/2013

27

How the JSP Engine Works: Overview

24/05/2013

28

How the JSP Engine Works: Internals

24/05/2013

29

What are Servlets?

Java objects which extend a HTTP server A Java Programming Language replacement for CGI, NSAPI, ISAPI, etc. A Java Platform Standard Extension Available and running on all major web servers
30

24/05/2013

Servlets in a URL Namespace

Servlets can hook into any part of a Webservers namespace A Servlet can hook into a single file A Servlet can hook into a directory tree A Servlet can hook into an entire servers namespace
31

24/05/2013

Servlets in the Server


Servlet Engine
GET /index.html

HelloServlet

GET /index.html

MapServlet

GET /map.html

24/05/2013

32

A Basic Servlet
public class ExampleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { out.setContentType(text/html); PrintWriter out = request.getWriter(); out.println(Hello NYC!<BR>); Date rightNow = new Date(); out.println(The time is: + rightNow); } 33 }

24/05/2013

Servlet Basics

Servlets have a well defined Lifecycle. Servlets load on demand and can be unloaded by the server at any time. Multiple threads of execution can run through a Servlet unless otherwise specified.
34

24/05/2013

Servlet Lifecycle

init method called exactly once upon load service method called 0-multiple times destroy method is called when Servlet is unloaded from host server

24/05/2013

35

Anatomy of a Servlet Request

24/05/2013

When a request is resolved to a servlet a Request and Response object are created and handed to the Servlet.service method. The Request Object contains all the information coming from the client. The Response Object encapsulates communication back the the client. 36

Servlet Request Illustration


Server
Request

Servlet
Response

24/05/2013

37

The Request Object

Access to request headers Access to an InputStream containing data from the client Access to CGI Like information Access to query parameters (form data) Access to server specific parameters such as SSL Cipher Suite
38

24/05/2013

Frequently Used Request Methods


javax.servlet.ServletRequest { Enumeration getParameterNames(); String getParameter(String parameterName); String getRemoteAddr(); }
javax.servlet.http.HttpServletRequest { String getRequestURI(); Enumeration getHeaderNames(); String getHeader(String headerName); HttpSession getSessiOn(); Cookie[] getCookies(); }

24/05/2013

39

The Response Object

Access to response headers such as Content-Type, CharacterEncoding, etc. Access to an OutputStream for returning data to the client Access to setting cookies Convenience methods for sending errors, redirects, etc.
40

24/05/2013

Response Methods
javax.servlet.ServletResponse { PrintWriter getWriter(); ServletOutputStream getOutputStream(); void setContentType(String type); void setContentLength(int length); } javax.servlet.http.HttpServletResponse { void addCookie(Cookie cookie); void setStatus(int statusCode); void sendError(int statusCode); void sendRedirect(String url); }

24/05/2013

41

JSP versus Servlets

But JSP pages are converted to Servlets? Arent they the same? Similarities
Provide identical results to the end user JSP is an additional module to the Servlet Engine

24/05/2013

42

JSP versus Servlets (contd)

Differences

Servlets: HTML in Java code

HTML code inaccessible to Graphics Designer Everything very accessible to Programmer HTML code very accessible to Graphics Designer Java code very accessible to Programmer

JSP: Java Code Scriptlets in HTML

24/05/2013

43

Conclusion

Robust server side dynamic web page generator. Easy to Implement

Implemented on a variety of reliable servers and platforms Based on the Java language

Easy to Manage

Separates graphical design requirements and programming requirements.

Free
44

24/05/2013

References

Suns JSP Page:

http://java.sun.com/products/jsp/

Suns JSP Tutorial:

http://java.sun.com/products/jsp/docs.html

Servlet API:

http://java.sun.com/products/servlet/2.2/javadoc/

24/05/2013

45

Вам также может понравиться