+ All Categories
Home > Documents > JSP – Java Server Page

JSP – Java Server Page

Date post: 21-Jan-2016
Category:
Upload: damia
View: 62 times
Download: 0 times
Share this document with a friend
Description:
JSP – Java Server Page. DBI – Representation and Management of Data on the Internet. What is JSP. http://java.sun.com/products/jsp A way to create dynamic web pages Based on Java Technology Large library base Platform independence Server side processing - PowerPoint PPT Presentation
58
JSP – Java Server Page DBI – Representation and Management of Data on the Internet
Transcript
Page 1: JSP – Java Server Page

JSP – Java Server Page

DBI – Representation and Management of Data on the Internet

Page 2: JSP – Java Server Page

What is JSP

• http://java.sun.com/products/jsp• A way to create dynamic web pages• Based on Java Technology

– Large library base– Platform independence

• Server side processing• Separates the graphical design from the

dynamic content

Page 3: JSP – Java Server Page

Relationships

• In servlets,– HTML code is printed from java code

• In JSP pages– Java code is embadded in HTML code

Java

HTMLJava

HTML

Page 4: JSP – Java Server Page

In General Lines

• JSP-enabled server – picks up .jsp page

– parses it

– converts it to runnable form

– runs it

• Converts page to a Java servlet (JspPage), with your code inside the _jspService() method– compiles it

– runs servlet protocol

Page 5: JSP – Java Server Page

Separating Graphical Design and Dynamic Content

• Not a new idea (e.g. PHP, mod_perl, shtml, ASP)• Graphical Design and System Design are two

separate and distinct specialities:– Different languages (HTML vs. Java) – Different goals– Different Training

• Should be separated for optimal project management

• JSP does this by allowing special Java tags in HTML

Page 6: JSP – Java Server Page

An Example

<html>

<body>

<b>I’m HTML code.</b><br>

<% out.println(“I’m Java code.”) %>

</body>

</html>

Page 7: JSP – Java Server Page

Sending a Request

Page 8: JSP – Java Server Page

Translating and Executing JSP Pages• A JSP page is executed in a JSP container,

generally installed in a Web server

– Think of a “JSP container” as a JVM with suitable software installed

• The underlying semantic model is that of a servlet

• A typical JSP container will translate the JSP page to a Java servlet

• By default translation and compilation of a JSP page is likely to occur the first time it is accessed– With Tomcat 3.1, you can find the generated Java and the class files

in a subdirectory under jakarta-tomcat/work.

Page 9: JSP – Java Server Page
Page 10: JSP – Java Server Page

Compilation

Page 11: JSP – Java Server Page

Translation

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

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

public void _jspService(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setContentType("text/html");HttpSession session = request.getSession(true);JspWriter out = response.getWriter();out.println("<H1>A Random Number</H1>");out.println(Math.random());...

}

public void _jspService(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setContentType("text/html");HttpSession session = request.getSession(true);JspWriter out = response.getWriter();out.println("<H1>A Random Number</H1>");out.println(Math.random());...

}

Page 12: JSP – Java Server Page

JSP Features

• Standard directives guiding translation of a JSP page to a servlet

• Standard actions in the form of predefined JSP tags

• Script language declarations, scriptlets, and expressions for including Java (or other language) fragments that embed dynamic content

• A portable tag extension mechanism, for building tag libraries—effectively extending the JSP language

Page 13: JSP – Java Server Page

JSP vs. Javascript

• Javascript– Client side– Less secure– Browser Dependent– Unstable

Page 14: JSP – Java Server Page

JSP vs. ASP

• Active Server Pages (ASP)– Similarities:

• Server side dynamic web page generators

• Share similar syntax <% %>

• Modular programming (e.g. ActiveX, JavaBeans)

• Focus on database connectivity

– Differences:• ASP is a product while JSP is a specification

Page 15: JSP – Java Server Page

JSP vs. ASP (cont.)

• JSP– Based on Java Technology– Platform independence

• Unix, AS400, VMS, Windows

– More vendors choice

• ASP– Microsoft programming languages– Near Monopoly

Page 16: JSP – Java Server Page

JSP vs. Servlets

• But JSP pages are converted to Servlets? Aren’t they the same?

• Similarities– Provide identical results to the end user– JSP is an additional module to the Servlet

Engine

Page 17: JSP – Java Server Page

JSP versus Servlets (cont.)

• Differences– Servlets: “HTML in Java code”

• HTML code inaccessible to Graphics Designer

• Everything very accessible to Programmer

– JSP: “Java Code Scriptlets in HTML”• HTML code very accessible to Graphics Designer

• Java code very accessible to Programmer

(Seperating content from appearance)

Page 18: JSP – Java Server Page

More Details

Writing JSP Pages

Page 19: JSP – Java Server Page

Template HTML

• The HTML code that wraps the code is like a template

• Created as an ordinary HTML

• The dynamic parts are created on runtime and are inserted into the template

Page 20: JSP – Java Server Page

JSP Scripting Elements

• JSP scripting elements let you insert Java code into the servlet that will be generated from the JSP page.

• There are three forms: 1. Expressions of the form <%= expression %> that

are evaluated and inserted into the output, 2. Scriptlets of the form <% code %> that are inserted

into the servlet's service method, and 3. Declarations of the form <%! code %> that are

inserted into the body of the servlet class, outside of any existing methods

Page 21: JSP – Java Server Page

JSP Expressions

• A JSP expression is used to insert Java values directly into the output

• It has the following form: <%= Java Expression %>

• The Java expression is – evaluated, – converted to a string, and – inserted in the page

• This evaluation is performed at run-time (when the page is requested), and thus has full access to information about the request

Page 22: JSP – Java Server Page

Predefined Variables

• The following predefined variables can be used:– request, the HttpServletRequest– response, the HttpServletResponse – session, the HttpSession associated with the

request (if any)– out, the PrintWriter (a buffered version of

type JspWriter) used to send output to the client

• (more will be said later)

Page 23: JSP – Java Server Page

Examples

• For example, the following shows the date/time that the page was requested:

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

• For example, the following shows the hostname:

Your hostname:

<%= request.getRemoteHost() %>

Page 24: JSP – Java Server Page

<BODY><H2>JSP Expressions</H2><UL><LI>Current time: <%= new java.util.Date() %><LI>Your hostname: <%= request.getRemoteHost() %><LI>Your session ID: <%= session.getId() %><LI>The <CODE>testParam</CODE> form parameter:<%= request.getParameter("testParam") %></UL></BODY>

<BODY><H2>JSP Expressions</H2><UL><LI>Current time: <%= new java.util.Date() %><LI>Your hostname: <%= request.getRemoteHost() %><LI>Your session ID: <%= session.getId() %><LI>The <CODE>testParam</CODE> form parameter:<%= request.getParameter("testParam") %></UL></BODY>

Page 25: JSP – Java Server Page

JSP Scriplets

• JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page

• Scriptlets have the following form: <% Java Code %>

• Scriptlets have access to the same automatically defined variables as expressions

Page 26: JSP – Java Server Page

Producing Code

• Scriplets produce output HTML by printing into the out variable

• Example:

<% String queryData = request.getQueryString();

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

%>

Page 27: JSP – Java Server Page

HTML Code in Scriptlets• HTML code before and after the scriplets is

converted to print methods:

• <% if (Math.random() < 0.5) { %> Have a <B>nice</B> day! <% } else { %> Have a <B>lousy</B> day! <% } %>

<% if (Math.random() < 0.5) { %> Have a <B>nice</B> day! <% } else { %> Have a <B>lousy</B> day! <% } %>

if (Math.random() < 0.5) { out.println("Have a <B>nice</B> day!"); } else { out.println("Have a <B>lousy</B> day!"); }

if (Math.random() < 0.5) { out.println("Have a <B>nice</B> day!"); } else { out.println("Have a <B>lousy</B> day!"); }

Page 28: JSP – Java Server Page

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

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

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

request.setContentType("text/html");HttpSession session = request.getSession(true);JspWriter out = response.getWriter();out.println(foo());bar();...

}

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

request.setContentType("text/html");HttpSession session = request.getSession(true);JspWriter out = response.getWriter();out.println(foo());bar();...

}

Page 29: JSP – Java Server Page

Example of Using Scriplets (1)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE>Color Testing</TITLE></HEAD><%String bgColor = request.getParameter("bgColor");boolean hasExplicitColor;if (bgColor != null) {

hasExplicitColor = true;} else {

hasExplicitColor = false;bgColor = "WHITE";

}%>

Page 30: JSP – Java Server Page

Example of Using Scriplets (2)

<BODY BGCOLOR="<%= bgColor %>"><H2 ALIGN="CENTER">Color Testing</H2><%if (hasExplicitColor) {

out.println("You supplied an explicit background color of "+bgColor + ".");} else {

out.println("Using default background color of WHITE. " +"Supply the bgColor request attribute to try " +"a standard color, an RRGGBB value, or to see "+"if your browser supports X11 color names.");

}%></BODY></HTML>

Page 31: JSP – Java Server Page

JSP Declaration

• A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request)

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

• Declarations do not produce output• They are used, for example, to define variables

Page 32: JSP – Java Server Page

Example

• We want to print out the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded):

<%! private int accessCount = 0; %>

Accesses to page since server reboot:

<%= ++accessCount %>

Page 33: JSP – Java Server Page

JSP Directives• A JSP directive affects the overall structure of the

servlet class• It usually has the following form: <%@ directive attribute="value" %> • Multiple attribute settings for a single directive

can be combined: <%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %>

Page 34: JSP – Java Server Page

Directives

• There are three main types of directive: • page, which lets you do things like

– import classes – customize the servlet superclass

• include, which lets you – insert a file into the servlet class at the time the JSP file

is translated into a servlet

• taglib directive– indicates a library of custom tags that the page can

include

Page 35: JSP – Java Server Page

The page Directive

• The page directive lets you define the following attributes:– import="package.class“

<%@ page import="java.util.*" %>

– contentType="MIME-Type" <%@ page contentType="text/plain" %>(it is the same as <%response.setContentType("text/plain");

%>)

Page 36: JSP – Java Server Page

More Page Directives

• isThreadSafe=“true|false”– Normal servlet processing or implementing

SingleThreadModel

• session=“true|false”– Allowing/disallowing sessions

• buffer=“sizekb|none”– specifies the buffer size for the JspWriter out

• autoflush=“true|false”– Flush buffer when full or throws an exception when

buffer isfull

Page 37: JSP – Java Server Page

And More Directives

• extends=“package.class”• info=“message”

– A message for the getServletInfo method

• errorPage=“url”– Define a JSP page that handles uncaught

exceptions

• isErrorPage=“true|false”• language=“java”

Page 38: JSP – Java Server Page

The include Directive

• This directive lets you include files at the time the JSP page is translated into a servlet

• The directive looks like this:

<%@ include file="relative url" %>

Page 39: JSP – Java Server Page

Predefined Variables

• As we have seen before, there are variables that can be used in the code

• There are eight automatically defined variables, sometimes called implicit objects

• The available variables are request, response, out, session, application, config, pageContext, and page

Page 40: JSP – Java Server Page

request

• This is the HttpServletRequest associated with the request

• It lets you – look at the request parameters (via

getParameter), – the request type (GET, POST, HEAD, etc.),

and – the incoming HTTP headers (cookies, etc.)

Page 41: JSP – Java Server Page

response

• This is the HttpServletResponse associated with the response to the client

• Since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client

Page 42: JSP – Java Server Page

out

• This is the PrintWriter used to send output to the client

• However, in order to make the response object useful, this is a buffered version of PrintWriter called JspWriter

• Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive

• Usually out is used in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly

Page 43: JSP – Java Server Page

session

• This is the HttpSession object associated with the request

• Sessions are created automatically, so this variable is bound even if there was no incoming session reference (unless session was turned off using the session attribute of the page

directive)

Page 44: JSP – Java Server Page

application

• This is the ServletContext as obtained via getServletConfig().getContext()

Page 45: JSP – Java Server Page

config

• This is the ServletContext as obtained via getServletConfig().getContext()

Page 46: JSP – Java Server Page

pageContext

• JSP introduced a new class called PageContext

• It encapsulate use of server-specific features like higher performance JspWriters

• The idea is that, if you access the server-specific features through this class rather than directly, your code will still run on "regular" servlet/JSP engines

Page 47: JSP – Java Server Page

page

• This is simply a synonym for this• It is not very useful in Java

• It was created as a placeholder for the time when the scripting language could be something other than Java

Page 48: JSP – Java Server Page

Actions

• JSP actions use constructs in XML syntax to control the behavior of the servlet engine

• You can – dynamically insert a file, – reuse JavaBeans components, – forward the user to another page, or – generate HTML for the Java plugin

Page 49: JSP – Java Server Page

Available Actions

• Available actions include: – jsp:include - Include a file at the time the page is

requested– jsp:useBean - Find or instantiate a JavaBean– jsp:setProperty - Set the property of a JavaBean– jsp:getProperty - Insert the property of a JavaBean

into the output– jsp:forward - Forward the requester to a new page – jsp:plugin - Generate browser-specific code that

makes an OBJECT or EMBED tag for the Java plugin

Page 50: JSP – Java Server Page

The jsp:include Action

• This action lets you insert files into the page being generated

• The file inserted when page is requested

• The syntax looks like this: <jsp:include page="relative URL"

flush="true" />

Page 51: JSP – Java Server Page

The jsp:useBean Action

• This action lets you load in a JavaBean to be used in the JSP page

• The simplest syntax for specifying that a bean should be used is:

<jsp:useBean id="name“

class="package.class" />

Page 52: JSP – Java Server Page

Examplepackage dbiTests;

public class SimpleBean {

private String message="No message specified";

public String getMessage() { return(message);

}

public void setMessage(String message) { this.message = message;

} }

package dbiTests;

public class SimpleBean {

private String message="No message specified";

public String getMessage() { return(message);

}

public void setMessage(String message) { this.message = message;

} }

Page 53: JSP – Java Server Page

<HTML> <HEAD> <TITLE>Reusing JavaBeans in JSP</TITLE> </HEAD>

<BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE"> Reusing JavaBeans in JSP</TABLE> </CENTER> <P> <jsp:useBean id="test" class=“dbiTest.SimpleBean" /> <jsp:setProperty name="test" property="message" value="Hello WWW" /> <H1>Message: <I><jsp:getProperty name="test" property="message" /> </I></H1> </BODY> </HTML>

<HTML> <HEAD> <TITLE>Reusing JavaBeans in JSP</TITLE> </HEAD>

<BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE"> Reusing JavaBeans in JSP</TABLE> </CENTER> <P> <jsp:useBean id="test" class=“dbiTest.SimpleBean" /> <jsp:setProperty name="test" property="message" value="Hello WWW" /> <H1>Message: <I><jsp:getProperty name="test" property="message" /> </I></H1> </BODY> </HTML>

Page 54: JSP – Java Server Page

The jsp:forward Action

• Forwards request to another page• Syntax:

<jsp:forward page="relative URL"/>• It has a single attribute, page, which should consist of a

relative URL• This could be a static value, or could be computed at

request time• Examples: <jsp:forward page="/utils/errorReporter.jsp" /> <jsp:forward page="<%= someJavaExpression %>" />

Page 55: JSP – Java Server Page

Comments• <%-- comment --%>

– A JSP comment– Ignored by JSP-to-scriptlet translator– Any embedded JSP scripting elements,

directives, or actions are ignored

• <!-- comment -->– An HTML comment– Passed through to resultant HTML – Any embedded JSP scripting elements,

directives, or actions are executed normally

• /* comment */ or // comment– Java comment– Part of the Java code

Page 56: JSP – Java Server Page

Quoting Conventions

• <\% – Used in template text (static HTML)

and in attributes where you really want "<%"

• %\>– Used in scripting elements and in

attributes where you really want "%>“• \‘ \”

– For using quotes in attributes

Page 57: JSP – Java Server Page

Init and Destroy

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

Page 58: JSP – Java Server Page

Writing JSP in XML

• We replace – <% Java Expration %> with <jsp:expression> Java Expression

</jsp:expression> – <% Code %> with <jsp:scriptlet> Code </jsp:scriptlet>– <%! Code %> with <jsp:declaration> Code </jsp:declaration> – For directives we use <jsp:directive.directiveType attribute=value />


Recommended