Chapter6 Java Server Page Notes JSP Overview A

  • Slides: 36
Download presentation
Chapter-6 Java Server Page Notes

Chapter-6 Java Server Page Notes

JSP Overview A Java. Server page (JSP) is a template for a Web page

JSP Overview A Java. Server page (JSP) is a template for a Web page that uses Java code to generate an HTML document dynamically. JSPs are run in a server-side component known as a JSP container, which translates them into equivalent Java servlets. For this reason, servlets and JSP pages are intimately related. What’s possible in one is, in large part, also possible in another, although each technology has its individual strengths. Because they are servlets, JSP pages have all the advantages of servlets: ■ They have better performance and scalability than CGI scripts because they are persistent in memory and multithreaded. ■ No special client setup is required. ■ They have built-in support for HTTP sessions, which makes application programming possible.

■ They have full access to Java technology–network awareness, threads, and database connectivity—without the

■ They have full access to Java technology–network awareness, threads, and database connectivity—without the limitations of client-side applets. But, in addition, JSP pages have advantages of their own: ■ They are automatically recompiled when necessary. ■ Because they exist in the ordinary Web server document space, addressing JSP pages is simpler than addressing servlets. ■ Because JSP pages are HTML-like, they have greater compatibility with Web development tools.

How JSP Works A JSP page exists in three forms: ■ JSP source code

How JSP Works A JSP page exists in three forms: ■ JSP source code This is the form the developer actually writes. It exists in a text file with an extension of. jsp, and consists of a mix of HTML template code, Java language statements, and JSP directives and actions that describe how to generate a Web page to service a particular request. ■ Java source code The JSP container translates the JSP source code into the source code for an equivalent Java servlet as needed. This source code is typically saved in a work area and is often helpful for debugging. ■ Compiled Java class Like any other Java class, the generated servlet code is compiled into byte codes in a. class file, ready to be loaded and executed.

The JSP container manages each of these forms of the JSP page automatically, based

The JSP container manages each of these forms of the JSP page automatically, based on the timestamps of each file. In response to an HTTP request, the container checks to see if the. jspsource file has been modified since the. javasource was last compiled. If so, the container retranslates the JSP source into Java source and recompiles it. Figure 5 -1 illustrates the process used by the JSP container. When a request for a JSP page is made, the container first determines the name of the class corresponding to the. jspfile. If the class doesn’t exist or if it’s older than the. jspfile (meaning the JSP source has changed since it was last compiled), then the container creates Java source code for an equivalent servlet and compiles it. If an instance of the servlet isn’t already running, the container loads the servlet class and creates an instance. Finally, the container dispatches a thread to handle the current HTTP request in the loaded instance.

Components of a JSP Page • A. jsp file can contain JSP elements, fixed

Components of a JSP Page • A. jsp file can contain JSP elements, fixed template data, or any combination of the two. JSP elements are instructions to the JSP container about what code to generate and how it should operate. These elements have specific start and end tags that identify them to the JSP compiler. Template data is everything else that is not recognized by the JSP container. Template data (usually HTML) is passed through unmodified, so the HTML that is ultimately generated contains the template data exactly as it was coded in the. jsp file.

Elements of JSP Three types of JSP elements exist 1. 2. 3. Directives Scripting

Elements of JSP Three types of JSP elements exist 1. 2. 3. Directives Scripting elements, including expressions, scriptlets, and declarations Actions

Directives are instructions to the JSP container that describe what code should be generated.

Directives are instructions to the JSP container that describe what code should be generated. They have the general form <%@ directive-name [attribute="value". . . ] %> The JSP 1. 1 specification describes three standard directives available in all compliant JSP environments: ü page ü include ü Taglib

The page Directive The page directive is used to specify attributes for the JSP

The page Directive The page directive is used to specify attributes for the JSP page as a whole. It has the following syntax: <%@ page [attribute="value". . . ] %> where the attributes are any of those listed in Table

page Directive Example <%@page import ="java. util. Date"%> <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE

page Directive Example <%@page import ="java. util. Date"%> <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Todays Date</title> </head><%Date date = new Date(); %> <body> <h 1>Todays Date</h 1> <p>Todays date : <%=date %></p> </body> </html>

Attributes of the Page Directive Attribute Value language The language used in scriptlets, expressions,

Attributes of the Page Directive Attribute Value language The language used in scriptlets, expressions, and declarations. In JSP 1. 1, the only valid value for this attribute is java. extends The fully qualified name of the superclass of this JSP page. This must be a class that implements the Http. Jsp. Page interface. The JSP specification warns against the use of this attribute without fully understanding its implications. Import A comma-separated list of one or more package. * names and/or fully qualified class names. This list is used to create corresponding import statements in the generated Java servlet. The following

The include Directive The include directive merges the contents of another file at translation

The include Directive The include directive merges the contents of another file at translation time into the. jsp source input stream, much like a #include. C preprocessor directive. The syntax is <%@ include file="filename" %> where filename is an absolute or relative pathname interpreted according to the current servlet context. Examples would be <%@ include file="/header. html" %> <%@ include file="/doc/legal/disclaimer. html" %> <%@ include file="sortmethod" %>

The taglib Directive The taglib directive makes custom actions available in the current page

The taglib Directive The taglib directive makes custom actions available in the current page through the use of a tag library. The syntax of the directive is <%@ taglib uri="tag. Library. URI" prefix="tag. Prefix" %> where the attributes are those listed here:

tag. Library. URI tag. Prefix The URL of a Tag Library Descriptor. A unique

tag. Library. URI tag. Prefix The URL of a Tag Library Descriptor. A unique prefix used to identify custom tags used later in the page

Expressions JSP provides a simple means for accessing the value of a Java variable

Expressions JSP provides a simple means for accessing the value of a Java variable or other expression and merging that value with the HTML in the page. The syntax is <%= exp %> where exp is any valid Java expression. The expression can have any data value, as long as it can be converted to a string. This conversion is usually done simply by generating an out. print()statement. For example, the JSP code The current time is <%= new java. util. Date() %>

Scriptlets A scriptlet is a set of one or more Java language statements intended

Scriptlets A scriptlet is a set of one or more Java language statements intended to be used to process an HTTP request. The syntax of a scriptlet is <% statement; [statement; . . . ] %>

Scriptlet Example <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>IP Address</title> </head> <body> <%out. println("Your

Scriptlet Example <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>IP Address</title> </head> <body> <%out. println("Your IP Address: "+request. get. Remote. Addr()); %> </body> </html>

Declarations Like scriptlets, declarations contain Java language statements, but with one big difference: scriptlet

Declarations Like scriptlets, declarations contain Java language statements, but with one big difference: scriptlet code becomes part of the _jsp. Service()method, whereas declaration code is incorporated into the generated source file outside the _jsp. Service()method. The syntax of a declaration section is <%! statement; [statement; . . . ] %>

Implicit Objects Although scriptlets, expressions, and HTML template data are all incorporated into the

Implicit Objects Although scriptlets, expressions, and HTML template data are all incorporated into the _jsp. Service()method, the JSP container writes the skeleton of the method itself, initializing the page context and several useful variables. These variables are implicitly available inside scriptlets and expressions (but not declarations). They can be accessed like any other variable, but do not have to be declared first. For example, the Http. Servlet. Requestobject passed to _jsp. Service()is available under the name request, as shown in the following scriptlet: <% String account. Number = request. get. Parameter("acct"); if (account. Number == null) { //. . . handle the missing account number problem }%>

Implicit Variables Variable Name Value request The Servlet. Requestor Http. Servlet. Request being serviced.

Implicit Variables Variable Name Value request The Servlet. Requestor Http. Servlet. Request being serviced. response The Servlet. Responseor Http. Servlet. Response that will receive the generated HTML output. page. Context The Page. Contextobject for this page. This object is a central repository for attribute data for the page, request, session, and application. session If the JSP page uses an Http. Session, it is available here under the name session. application The servlet context object.

Implicit Variables Variable Name Value out The character output stream used to generate the

Implicit Variables Variable Name Value out The character output stream used to generate the output HTML. config The Servlet. Configobject for this servlet context. page A reference to the JSP page itself. exception An uncaught exception that causes the error page to be invoked. This variable is available only to pages with is. Error. Page="true".

Standard Actions are high-level JSP elements that create, modify, or use other objects. Unlike

Standard Actions are high-level JSP elements that create, modify, or use other objects. Unlike directives and scripting elements, actions are coded using strict XML syntax <tagname [attr="value". . . ] >. . . </tag-name> or, if the action has no body, an abbreviated form: <tagname [attr="value". . . ] /> XML syntax requires the following: Every tag must have matching end tag or use the short form /> previously shown Attribute values must be placed in quotes Tags must nest properly: <A><B>. . . </B></A> is legal, but <A><B>. . . </A></B> is not.

Standard Actions Tag Name Description <jsp: use. Bean> Declares a Java Bean instance and

Standard Actions Tag Name Description <jsp: use. Bean> Declares a Java Bean instance and associates it with a variable name. Syntax is<jsp: use. Bean id="name"[ type="type" ][ class="class" ][ bean. Name="bean. Name" ][scope="page|request|session|application"]>. . . </jsp: use. Bean> <jsp: set. Property> Sets the values of one or more properties of a bean previously declared with <jsp: use. Bean>. Syntax is <jsp: set. Property name="id"prop-expression/>where propexpression is one of the following: property="*"property="prop. Name"property=" prop. Name" param="parameter. Name" property="prop. Name" value="value"property="prop. Name" value=<%= expression %>

Standard Actions Tag Name Description <jsp: get. Property> Returns the value of the specified

Standard Actions Tag Name Description <jsp: get. Property> Returns the value of the specified property of a bean. Syntax is<jsp: get. Property name="id" property="name" /> <jsp: include> Invokes another resource and merges its output stream with the JSP page output stream. Syntax is <jsp: include page="URL" flush="true" /> or, if parameters need to be passed: <jsp: include page="URL" flush="true"><jsp: param … />. . . <jsp: param. . . /></jsp: include>

Standard Actions Tag Name Description <jsp: forward> Forwards this HTTP request to another JSP

Standard Actions Tag Name Description <jsp: forward> Forwards this HTTP request to another JSP page or servlet for processing. Syntax is<jsp: forward page="URL" />or, if parameters need to be passed: <jsp: forward page="URL"><jsp: param. . . />. . . <jsp: param. . . /></jsp: forward> <jsp: param> Binds a value to a name and passes the binding to another resource invoked with <jsp: include>or <jsp: forward>. Syntax is<jsp: param name="name" value="value" />

Standard Actions Tag Name Description <jsp: plugin> Used to generate the appropriate HTML linkage

Standard Actions Tag Name Description <jsp: plugin> Used to generate the appropriate HTML linkage for downloading the Java plugin: <jsp: plugintype="bean|applet"code="ob ject. Code"codebase="object. Codebase"{ align="alignment" }{ archive="archive. List" }{ height="height" }{ hspace="hspace" }{ jreversion="jreversion" }{ name="component. Name" }{ vspace="vspace" }{ width="width"}{ nspluginurl="url" }{ iepluginurl="url" } > { <jsp: params>{ <jsp: param name="name" value="value" />}+</jsp: params> }}</jsp: plugin>

JSP Example Login Verification (index. jsp) • • • • • <%@page content. Type="text/html"

JSP Example Login Verification (index. jsp) • • • • • <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h 1>User. Name Password verification </h 1> <form action="verify. jsp" method ="get"> Enter User. Name: <input type="text" name="uname" value="" /> Enter Password: <input type="text" name="pass" value="" /> <input type="submit" value="submit" /> </form> </body> </html>

verify. jsp <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%! String

verify. jsp <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%! String uname, pass; %> <% uname= request. get. Parameter("uname"); pass=request. get. Parameter("pass"); if (uname. equals("jazan")&& pass. equals("university")) {%> <jsp: forward page="welcome. jsp"/> <%} else {%> Wrong User. Name/Password, Try again!!! <jsp: include page ="index. jsp"/> <%}%> </body> </html>

welcome. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

welcome. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%! String uname, pass; %> <% uname= request. get. Parameter("uname"); pass=request. get. Parameter("pass"); %> Welcome, <%=uname%> Your password is : <%=pass %> </body> </html>

Jsp and javabeans What Is a Java. Bean? The definition of a bean is

Jsp and javabeans What Is a Java. Bean? The definition of a bean is purposely broad. A bean is simply a Java class that meets two requirements: • It has a zero-argument constructor. • It implements Serializable or Externalizable to make it persistent. Bean Properties In addition, most beans have properties. Properties are attributes of the bean for which the bean provides read and/or write methods. All access to the bean’s properties must be done through these methods; the underlying data field (if there is one) is private. Part of the Java. Beans programming model is the naming convention used for these methods. Unless you make special provision through a Bean. Infoclass, the read method for a property is a public method named get<Property. Name>(), where <Property. Name> is the name of the property with the first letter converted to uppercase. Similarly, the write method, if there is one, is named set<Property. Name>().

Example Using jsp & javabeans //index. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html>

Example Using jsp & javabeans //index. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form action="first. jsp" method ="get"> Enter Usn: <input type="text" name="usn" value="" /> Enter Name: <input type="text" name="name" value="" /> Enter Course: <input type="text" name="course" value="" /> <input type="submit" value="submit" /> </form> </body> </html>

Student. Bean. java package bean; public class Student. Bean { private String usn; public

Student. Bean. java package bean; public class Student. Bean { private String usn; public String get. Usn() { return usn; } public void set. Usn(String usn) { this. usn = usn; } private String name; public String get. Name() { return name; }

public void set. Name(String name) { this. name = name; } private String course;

public void set. Name(String name) { this. name = name; } private String course; public String get. Course() { return course; } public void set. Course(String course) { this. course = course; } }

first. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

first. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <jsp: use. Bean id="stud" scope="request" class="bean. Student. Bean"/> <jsp: set. Property name="stud" property="*"/> <jsp: forward page="display. jsp"/> </body> </html>

welcome. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

welcome. jsp <%@page content. Type="text/html" page. Encoding="UTF-8"%> <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <jsp: use. Bean id="stud" scope="request" class="bean. Student. Bean"/> Usn: <jsp: set. Property name="stud" property="usn"/> Name: <jsp: set. Property name="stud" property="name"/> Couse: <jsp: set. Property name="stud" property="course"/> </body> </html>