Beruflich Dokumente
Kultur Dokumente
Table of Contents
Chapter 1: JSP Basics Chapter 2: JSP Syntax Chapter 3: JSP and Java Beans
Chapter 1
JSP Basics
Chapter 1 Outline
What is Java Server Page (JSP)? What is wrong with servlets? What is the difference between servlets and JSP? Advantages of JSP Ad t f JSP. How JSP look like? How JSP works? javax.servlet.jsp package.
JspPage interface HttpJspPage Interface JSP Classes
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 4
What is Java Server Page (JSP) ? An extension of the servlet technology created to support authoring of HTML and XML pages pages. What is wrong with servlets ?
Most Web pages are HTML. Every single change will require the involvement of the servlet programmer. No clear separation of presentation and logic. Little bit difficult for web programmers.
Servlets: Are Java programs with embedded HTML HTML. Generate dynamic content. Do not separate static and dynamic content content. JavaServer Pages: Are HTML pages with embedded Java code or they can be pure XML. Generate dynamic content content. Separate static and dynamic content.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 6
Benefits of JSP Easier to author (Web-site development tools). Separating the development team responsibilities. responsibilities Business and presentation logic are separated. Simplify development with JSP J Si lif d l t ith JSP, JavaBeans and B d custom tags. Supports software reuse through the use of components. Recompile automatically when change are made to the source file. Platform independent. independent
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 7
First time No
http://host/date.jsp
Example
</BODY> </HTML>
public void _jspService(..) { out.write("<HTML>\r\n"); out.write( <HEAD>\r\n ); out write("<HEAD>\r\n"); out.write("</HEAD>\r\n"); out.write("<BODY>\r\n"); out.println("JSP i easy"); t i tl ("JSP is ") out.write("\r\n"); out.write("</BODY>\r\n"); out.write("</HTML>"); }
* Source: Core Servlets and Javaserver Pages By Marty Hall, Larry Brown ISBN 0130092290
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 11
Why JSP developers need servlets? 1. JSP pages are translated into servlets. 2. 2 JSP consists of static HTML, JSP tags, and i t f t ti HTML t d Java code (Servlet code). 3. Some tasks are better accomplished b servlets 3 S t k b tt li h d by l t than by JSP. 4. 4 Combination of servlets and JSP JSP.
javax.servlet.jsp.*
Exceptions:
JspException JspError.
JspPage interface
The JspPage is the interface that must be implemented by all JSP servlet classes. y It contains two methods:
public void jspInit() public void j p p jspDestroy() y() Example:
<% ! (Note it is <%! JSP Declaration Not <%) public void jspInit() { System.out.println("Init"); } public void jspDestroy() { System.out.println("Destroy"); } %>
HttpJspPage Interface
It extends the JspPage interface. It has got only one method : public void _jspService ( HttpServletRequest request,HttpServletResponse response ) throws ServletException, IOException. Its called by the JSP container, to generate the content of the JSP page. you can't include this method in a JSP page, because the page content itself represents this method method.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 16
JSP Classes
The JspFactory class The JspEngineInfo class The PageContext class Implicit objects Implicit objects The JspWriter class
The following code is p of the _ j p g part jspService method that is generated by the JSP container:
JspFactory _jspxFactory = null; jspxFactory PageContext pageContext = null; _jspxFactory =JspFactory.getDefaultFactory(); pageContext = _jspxFactory.getPageContext ( this, request, response,"", "" true, 8192, true);
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 19
The JspEngineInfo class is an abstract class that provides information on the JSP container. It has only one method, getSpecificationVersion, returns the JSP container's version number.
3-The PageContext Class PageContext represents a class that provides methods that are implementation-dependent. implementation dependent. The PageContext class itself is abstract so in abstract, the _ jspService method of a JSP servlet class, a PageContext object is obtained by calling the getPageContext method of the JspFactory class.
The PageContext Class (cont.) The PageContext class provides methods that are used to create other objects. j
getOut method returns a JspWriter object that is used to send strings to the web browser. getRequest, returns a S tR t t ServletRequest object. l tR t bj t getResponse, returns a ServletResponse object. getServletConfig returns a ServletConfig object getServletConfig, object. getServletContext, returns a ServletContext object. getSession, returns an HttpSession object. getSess o , etu s a ttpSess o object
4-The JspWriter Class The JspWriter class is derived from the java.io.Writer class and represents a Writer that you can use to write to the client browser. Of its many methods, the most important are the print and println methods.
javax.servlet.http.HttpServletRequest javax.servlet.http.HttpServletResponse javax.servlet.jsp.JspWriter javax servlet jsp JspWriter javax.servlet.http.HttpSession javax.servlet.ServletContext javax servlet ServletContext javax.servlet.ServletConfig
Review
Revisiting the generated Servlet out of a JSP file If the code written in the JSP page was only : p g y
<% out.println("JSP is easy"); %>
Advanced
Lab Exercise
Assignments
Make a simple JSP displaying the time. Make an html page that redirect a request to an JSP
Chapter 2
JSP Syntax
Chapter 2 Outline
JSP tags : Directive elements Scripting elements Action elements Converting into XML syntax
JSP tags
JSP tags Directive Scripting Action
page
Scriptlets
include
Declarations
taglib
Expressions
1-Directive Elements They are messages to the JSP container containing information on how the JSP container must translate a JSP page into a corresponding servlet. They are actually instructions to the container not a code. Directives Types :
Page directives Include directives Tag library directives (used with custom tags )
Example
<%@ page buffer="16384" session="false" %> <%@ include file=footer.html" %> <%@ talib uri=. prefix =c%> Advanced
Examples
<%@ page import="java.util.Enumeration" %> <%@ page session="false" %> @p g <%@ page buffer="16384" %> <%@ page autoFlush="false" %> <%@ page errorPage="ErrorPage.jsp" %>
Its not allowed to repeat assigned attributes except for import attribute tf i t tt ib t
1-Directive Elements (contd) a-Page Directive Attributes Notes on import attribute 1st and 2nd strategy for invoking dynamic code. Utility classes should always be in packages and the JSP page should use the import attribute. By default the generated servlet imports java.lang.*, default, java lang * javax.servlet.*, javax.servlet.jsp.*, javax.servlet.http.*. The only page attribute that is allowed to appear multiple yp g pp p times. The utility classes should be placed in /WEB-NF/classes/ Note: <%@ page import="package.class1,...,package.classN" %>
It enables JSP page authors to include the contents of other files in the current JSP page. We can include static page like html or another JSP page. p g Include Syntax:
<%@ include file="relativeURL" %> @
Example:
<%@ include file=header.html" %> @
2-Scripting Elements
It allows you to insert Java code in your JSP pages. 1st and 2nd strategy for invoking dynamic code. gy g y There are three types:
Scriptlets p Declarations Expressions
E Example: l
<% out.println("Current Time: " + getSystemTime()) ; t i tl ("C t Ti tS t Ti ()) %>
I used to d l Its d declare methods or variables. h d i bl Inserted into the body of the servlet class, outside any existing methods. i ti th d Can not access the implict objects of _jspService method Syntax:
<%! //// put your code here //// %>
Examples:
<%! String getSystemTime() { return Calendar.getInstance().getTime().toString(); }% }%> <%! int x; %>
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 42
Its used to evaluate expressions and print them to the user. Its used instead of out.println() Syntax:
<%= put the variable here %> % %
Example:
<%= java.util.Calendar.getInstance().getTime() %> % % The same result of : out.print( java.util.Calendar.getInstance().getTime() );
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 43
Assignment Write a utility class that generates a random number within a given range range. Invoke methods of this utility class from jsp page using scripting elements elements.
They got the same effect of RequestDispatcher include and forward Syntax:
<jsp:include page="relativeURL> page relativeURL > ( <jsp:param . . . /> )* </jsp:include> j p <jsp:forward page="relativeURL"> ( <jsp:param . . . /> )* </ jsp:forward >
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 46
3-Standard Action Elements(cont) Include, forward and param Notes on jsp:include The included pages can be - HTML files, plain text files, JSP pages, S l t fil l i t t fil Servlets - With JSP pages and servlets, only the output of the page is included, not the actual code. Do not use complete HTML documents for the included pages. The included page uses the same request object as the originally requested page and sees the same request parameters. The main page can add to or replace the request parameters using jsp:param.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 47
3-Standard Action Elements(cont) Include, forward and param Notes on jsp:forward Using jsp:forward obtain the complete output from the destination page page. The main page must not have any output. The main page can add to or replace the request parameters using jsp:param.
Insert JSP code into the main page before that main page is translated into a servlet. The main page must be updated whenever any of the included pages p g change. The included code can contain JSP constructs such as field definitions and content-type settings that affect the main page as a whole.
JavaTM Education & Technology Services
http://jets.iti.gov.eg 49
No change needed in the main page when the included pages change change. The included pages p g cannot use any JSP constructs that affect the main page as a whole.
Assignment Use both jsp:include and include directive to include header to your jsp and Note the difference.
3-Standard Action Elements(cont.) Plugin, Fallback and params Sun developed a browser plug-in for Netscape and Internet Explorer that lets you use the Java 2 platform in a variety of browser versions. i t fb i In some browsers, the normal APPLET tag will not work with the plug-in. Instead, use OBJECT tag for Internet plug in. Explorer and EMBED tag for Netscape. The <jsp: plugin> is used to generate HTML <OBJECT> or <EMBED> t EMBED tags that instruct the browser to download th t i t t th b t d l d the Java Plugin software, if required, and initiate the execution of the Java applet specified. pp p Note: The applet .class files must not be placed in WEBINF/classes, as the browser, not the server, uses them.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 51
< jsp:plugin type="applet code="MyApplet class width="475" height="350"> type= applet code= MyApplet.class width= 475 height= 350 > <jsp:params> <jsp:param name="PARAM1" value="VALUE1" /> </jsp:params> </jsp:plugin>
Comment tag
HTML comments <! <!-- HTML Comment --> >
Benefits:
The content of the JSP page can be validated against a set of descriptions. The JSP page can be manipulated using an XML tool. The JSP page can be generated from a textual representation by applying an XML transformation
Examples:
<jsp:directive.page attr=value /> j p p g <jsp:scriptlet> String s; s = request.getParameter("user"); </jsp:scriptlet> <jsp:text>.</jsp:text> <jsp:text> </jsp:text>
Chapter 3
JSP and Java Beans
Chapter 3 Outline
What is a Bean? <useBean> Tag Structure. Structure How to use a request parameter to feed the value of a bean variable ?
What is a Bean? A bean is a java class with certain rules defined by the JavaBeans specification. Beans extend no particular class and use no particular interface. The 3rd strategy for invoking dynamic code.
Java Beans Rules A bean class must have a default constructor ( (which will be called when JSP elements or servlets create beans). A bean class should have no public instance variables. Persistent values (properties) should be accessed through methods called getXxx and setXxx. Or isXxx and setXxx for bolean properties.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 63
<useBean> Tag Structure <j jsp:useBean ( ib B (attribute="value")+ / " l ") /> Main attributes :
id class scope (page request, session, application) (page, request session
Example: <jsp:useBean id=beanName" scope="session" id= beanName" class=" com.mybeans.MyFirstBean"/> This element can either build a new bean or access a preexisting one in the specified scope scope.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 66
<useBean> Tag Structure (cont) You must use the fully qualified class name for the class attribute regardless of whether you use <%@ page import... %> to import packages. <jsp:useBean id=bookBean class=" com.mybeans.MyBookBean"/>
Syntax: <jsp:getProperty name=" beanName " property="propertyName"/> This element reads and outputs the value of a bean property. Reading a property means calling its getXxx method.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 68
<jsp:setProperty name=" beanName " jsp:setProperty name property=propertyName" value="value"/> This element modifies a bean property (i.e., calls its setXxx method). method)
JSP expression could be used to call a method on the object with the variable specified by the id j y attribute. <%= bookBean.getIsbn() %> <jsp:getProperty name=" bookBean " j pg p y property=isbn"/> It is not advisable but can be useful with loops, conditional statements, and methods not represented as properties.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 70
JSP scriptlet could be used to explicitly call methods on the bean object. j <% bookBean.setIsbn (1234567890); %> <jsp:setProperty name=" bookBean" p p y property=isbn" value=1234567890"/> It is not advisable but can be useful in setting the g value conditionally or calling methods other than getXxx or setXxx on the object.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 71
Example
package com mybeans; com.mybeans; public class MyFirstBean { private String firstName; public String getFirstName() { return firstName; } public void setFirstName(String name) { firstName=name; firstName name } } Note:In beans terminology the class is said to have a String property called firstName.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 72
Example (cont.)
<jsp:useBean id= myBean jsp:useBean id myBean class=com.mybeans.MyFirstBean /> <jsp:setProperty name= myBean p p y property=firstName value= Ali /> The First Name is <jsp:getProperty e st a e s jsp get ope ty name=myBean property=firstName />
Example (cont.) Note You can access the bean methods using scripting tags g g
<jsp:useBean id= myBean class=com.mybeans.MyFirstBean /> <% St i name = Ali % String ; myBean.setFirstName (name); %> The First Name is <%= myBean.getFirstName()%> Note: Whenever possible, avoid mixing the XMLcompatible jsp:useBean tags with JSP scripting elements containing explicit J t i i li it Java code. d
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 74
How to use a request parameter to feed the value of a bean variable ? Consider this case: <% int isbn = 1; try { y isbn = Integer.parseInt(request.getParameter(isbNum")); } catch(NumberFormatException nfe) { } %> <jsp:setProperty name=bookBean property=isbn" <j tP t b kB t i b " value="<%= isbn %>" />
How to use a request parameter to feed the value of a bean variable ? (cont) JSP offers a better solution: <jsp:setProperty name="BeanName" property= PropertyName param= parameterName /> property="PropertyName param="parameterName"/> For Example: <jsp:setProperty name=bookBean property=" isbn" param= isbNum/>
isbNum is the name of the request parameter. The value of the request parameter isbNum is automatically used as the value of the bean property isbn. p p y Type conversions from String to primitive types (byte, int, double, etc.) and wrapper classes (Byte, Integer, Double, etc.) are automatically p performed. If the specified parameter is missing from the request, no action is taken
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 76
How to use a request parameter to feed the value of a bean variable ? (cont)
If the request parameter name and the bean property name are the same the param attribute could be omitted
Example: p If the request parameter has the name isbn <jsp:setProperty name=bookBean property=" isbn />
Lab Exercise
Assignment Write a jsp page that populates a Java bean with the data from the user and forward to another jsp page or servlet that displays the data.
Chapter 4
MVC Frameworks
Chapter 4 Outline
MVC Design Pattern. Why MVC? MVC Frameworks. Implementing MVC with RequestDispatcher. I l ti ith R tDi t h
MVC Design Pattern Model-View-Controller (MVC) is an architectural design pattern used to build complex computer applications. It aims to separate data (model) and user interface (view). i t f ( i ) The MVC architecture divides applications into three layers : th l
Model: The data and business logic View: The presentation and User Interface Controller: The flow control
1. 1 Dividing responsibilities:
2. Ease of maintenance. 3. 3 Pre and Post Processing (sec rit logging etc ) (security, logging, etc)
MVC Frameworks
The 4th strategy for invoking dynamic code. The original request is handled by a servlet. g q y The servlet invokes the business-logic and data-access code and creates beans to represent the results , decides which JSP page present those results and forwards the request to it. This servlet is the Controller. The beans representing the results are the Model. The jsp that presents the results are the View. The most popular MVC f C framework is Apache S Struts.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 89
1-request
Controller (Servlet) 2 3
Client browser
5-response
View (JSP)
Servlet Container
To share JAR files across Web applications, put JAR files in /common/lib.
JavaTM Education & Technology Services
Copyright Information Technology Institute http://jets.iti.gov.eg 93
Project After the user correctly log in to the Application, a specified home page is displayed according to g y g the priviliges of the user. Only the managers can add, edit or delete another employee. Implement the MVC architecture and avoid using direct java code in the jsp pages as much as you can.
References & Recommended Reading Core Servlets and JSP. Java for the Web with Servlets, JSP, and EJB. J f th W b ith S l t JSP d EJB Sun presentations. Oracle presentations. SCJWD study guide.