+ All Categories
Home > Documents > JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And...

JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And...

Date post: 20-Dec-2015
Category:
View: 217 times
Download: 0 times
Share this document with a friend
Popular Tags:
140
JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web
Transcript
Page 1: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JavaServer Pages

Some notes from: the Hans Bergen text

Hunter textSebesta text

JSP and XML textAnd from tutorial sites on the web

Page 2: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

What is a JSP?

• JSP are html pages which contain both static (like traditional html) and dynamic content. Content may vary with the client request, identity or browser type.

• JSP elements are executed by the server and merged with the page’s static contents and sent to the client.

• Accessing beans, sharing information between users and pages and requests are a few possible JSP actions.

• JSP syntax is also extensible to deal with application-specific concerns.

Page 3: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Why JSP?

• A number of technologies have arisen to challenge CGI programming – the only choice in the early 90s.

• CGI is not efficient. Each incoming request spawns a new server process. A script must be loaded, interpreted (executed) and then disposed. As traffic increases the problems inherent in this model worsen.

Page 4: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

CGI alternatives

• FastCGI• Mod_perl• NSAPI• ISAPI• Java servlets• All these improve on CGI performance but

at the cost of embedding html in the programming language. This means only programmers can develop server pages.

Page 5: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP

• JSP may contain java code embedded in the scripting elements, though this is rarely needed. Too much code in a JSP results in the same lopsided application modularization as placing the html in the servlet.

• Recent innovations in JSP are the Expression Language (EL) and the standard tag library (JSTL).

Page 6: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP- benefits

• JSP are compiled, not interpreted. Typically, they are compiled on the first load and, unless changed, available to subsequent requests without another compilation. In conjunction with a persistent JVM on a JSP-enabled server, JSP can be delivered very quickly.

Page 7: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Application modularization

• A good breakdown of an internet application is for JavaBeans to handle application logic (& datatypes), servlets can handle input processing, and JSP can provide the user interface.

Page 8: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP power

• JSP are built on the servlet api (they are actually compiled into servlets)

• consequently JSP can access1. JDBC2. RMI and CORBA3. JNDI (java naming and directory interface)4. JMS – java message service5. JavaMail6. Java API for XML registries (JAXR), java API

for XML-rpc (JAX-RPC) and SAAJ (SOAP with attachments api for java).

Page 9: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

ASP vs JSP

• ASP are Microsoft’s popular technology for developing dynamic sites. The page may include VB- and J-script. COM (ActiveX) components written in C++ can handle complex code. Database access components and more are included in ASP.

• ASP.NET, the newest version, provides for dynamic content to be delivered via XML.

• ASP are compiled.• Reliance on native COM-code components

makes ASP primarily an (MS) windows-platform solution.

Page 10: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Others

• PHP- an open source scripting language with C style syntax.

• ColdFusion –Macromedia’s product. XML-type elements provide active content following CFML (cold-fusion-markup-language). Database handling, mailservers, conditional elements (loops) and allows custom elements to be added using C++ or Java. CFML extensions are available from third-party vendors.

• Java servlet template engine: A number of template engines were developed when programmers realized that embedding the html in the code was not such a great idea. Web scripting handles the presentation and servlets handle processing.

Page 11: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP design• To stop your JSP code from becoming a maintenance

nightmare, you will need to think and ask yourself a few questions.

• What does this page actually do?• Should I have my JSP page doing the tasks for add, update and

delete? Would it be better to have them done by different JSPs?• How can I reduce the amount of Java code in the JSP so a web

designer can keep the front-end looking good?• How do I reuse code done by other developers in my team?• Has anyone on the Internet already done some of the things I need

to do in my JSP pages?• If something goes wrong in my application, how will I log the error?•  How can I make my JSP page display text in different languages?

Page 12: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

An example: Technologies to consider

• If you were writing a Message Board application, you would think of a front-end dynamically showing messages from registered posters, maybe sending emails to Message Board posters etc.

•  • J2EE technologies that you will probably consider should include:• JSP - used for designing the front end.• JDBC - as the pages for the Message Board are dynamically produced, it

would make sense to store them in a database table. You would use JDBC to connect and do queries on the database.

• JavaMail - used for sending emails via SMTP.•  • Now depending on the tasks of the Message Board, you might also what to

consider:•  • Servlets - alternative to JSP. When you want to carry out a task that does

not need a frontend. A Servlet is a special Java class which outputs HTML via print statements. You could use a Servlet to send the emails (by also using JavaMail).

Page 13: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP or Servlets when developing J2EE applications?

  • You will probably use Both. • JSP will be used for nearly all your front end web interface with minimal

Java code.

• When you have a form that sends a request to search for results that you display in an HTML table, you would use a JSP.

• However, if you were sending out an email, you would use a Servlet. Why?

• The process of sending an email does not require a fancy frontend. The sending email process is a reusable service that would be coded in Java with no need for HTML design.

Page 14: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Why not design the whole application as Servlets?

 •  To answer this question you need to understand the advantages of

using JSP. The whole point of using JSP was to quickly produce web front ends. If you wrote an entire web front end application using servlets, it would probably take you much longer than using JSP. This is because every element of the HTML page would need to be in print statements in a Servlet.

• How can we decide between JSP and Servlets?

• It really comes down to analysing and designing your application. You need to highlight areas that are more like services (without being fixed to a front end) and other parts that consist of the user's interface.

Page 15: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

The problem with servlets

• Servlets often contain request processing, business logic and code (println) to generate the html response.

• Servlet creators must be java programmers.• Changing look/feel of a web app or upgrading to

support new clients is hard if the GUI features are in the servlet.

• It is very hard to use web tools to develop an interface since the resulting html must still be manually hard-coded into the servlet.

Page 16: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

How JSP helps

• JSP can handle the presentation side and servlets can handle processing.

• One part of the application can be upgraded/changed without impact to other parts.

• This modularization enhances portability, maintainability and re-usability of the application and its components.

Page 17: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP advantage

• JSP supports both scripting and element-based dynamic content.

• JSP are compiled (efficient).• JSP can work with servlets which can handle the

logic and processing.• JSP is a specification, not a product.

Competition in providing JSP can improve performance and keep JSP around awhile.

• JSP is part of J2EE so JSP have the java API to back them up and are scalable.

Page 18: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

To run JSP text examples

• Install Tomcat• Examples from O’Reilly’s JSP text (source

code and directories) can be downloaded from: http://examples.oreilly.com/jserverpages3/

• Hall text has text website and jsp examples not included in this ppt so farCopy ORA directory of extraction into tomcat webapps --- mine is at http://CSCI345.oneonta.edu:8080/ora

Page 19: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

A JSP technology overview

• see Resources for links to additional JSP technology information.• In the traditional sense, JSP pages look very much like HTML

pages, with a few extra tags. These tags allow the designer to embed Java code (not merely JavaScript) in the page itself. A Web application server will intercept requests for JSP pages. It's tipped off to their existence by the page's extension: .jsp (not .html). The Web application server then preprocesses the JSP page, taking out the JSP tags and any embedded Java code, leaving only the HTML. The extracted JSP tags and embedded Java code are used to build a Java servlet (JSP page servlet) that runs the code and inserts the results back into the original page where the JSP tags used to be. The result is pure HTML. The Java is stripped out and run on the server before the requesting browser sees any result.

Page 20: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Steps to execute JSP1. The user goes to a web site made using JSP. The user goes to a

JSP page (ending with .jsp). The web browser makes the request via the Internet.

2. The JSP request gets sent to the Web server. 3. The Web server recognizes that the file required is special (.jsp),

therefore passes the JSP file to the JSP Servlet Engine. 4. If the JSP file has been called the first time, the JSP file is parsed,

otherwise go to step 7. 5. The next step is to generate a special Servlet from the JSP file.

All the HTML required is converted to println statements. 6. The Servlet source code is compiled into a class. 7. The Servlet is instantiated, calling the init and service methods. 8. HTML from the Servlet output is sent via the Internet. 9. HTML results are displayed on the user's web browser.

Page 21: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Some URLs with resources

• Some sites I found just searching:– http://java.sun.com/products/jsp/html/JSPXML

.html– http://www.onjava.com/pub/a/onjava/2001/11/

28/jsp_xml.html– http://www.visualbuilder.com/jsp/tutorial/

Page 22: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

where to put them

• put jsp into a webapp root directory.

• I copied them into a directory called my-jsp

• They need no servlet tags or url patterns in the web.xml and so are available for use as soon as they are copied

• They are compiled into a “workhorse” servlet, so the first call will be slow.

Page 23: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

File Structure: tag libraries and jar files

• Place jar files (if you’ve created these) in lib and place class files for compiled java in classes. Client browsers can’t see or access this code.

• Tag libraries can be placed in lib (in jar format).• Classes needed can go in classes, following the

same hierarchical/derivation structure they have.• Alternatively, these files can be zipped and

placed in a war file.

Page 24: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

File Structure and your own JSP

• Create your own jsp directory under webapps in Tomcat.

• Place the *.jsp in subdirectories or directly in this directory.

• Create a WEB-INF directory in this directory and a lib directory in here. Copy standard.jar, jstl.jar and other necessary tag libraries into lib.

Page 25: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Standard jsp/servlet File Structure

• Tomcat

• webapps– Your jsp/servlet directory

• Jsp files here or in subdirectories• WEB-INF directory

» lib (put jar files here, including standard.jar, jstl.jar,…)

» classes (put class files here)

Page 26: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Notes and examples from Hunter chapter 18 servlets text

Page 27: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

hello1.jsp<HTML><HEAD><TITLE>Hello</TITLE></HEAD><BODY><H1><%if (request.getParameter("name") == null) { out.println("Hello World");}else { out.println("Hello, " + request.getParameter("name"));}%></H1></BODY></HTML>

Page 28: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

hello1.jsp

Page 29: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

scriplets and other code in the jsp

• the request for a jsp causes a java compile creating a servlet which is returned for the response.

• scriptlets have <% open tag and %> close tag and contain servlet code.

• declarations begin with <%! and end with %>• comments have <%-- tags --%>• assignments/expressions have the form <%=foo

%>

Page 30: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

hello2

Page 31: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

hello2.jsp<%-- hello2.jsp --%><HTML><HEAD><TITLE>Hello</TITLE></HEAD><BODY><H1>Hello, <%= getName(request) %></H1></BODY></HTML>

<%!private static final String DEFAULT_NAME = "World";

private String getName(HttpServletRequest req) { String name = req.getParameter("name"); if (name == null) return DEFAULT_NAME; else return name;}%>

Page 32: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

declarations

• declarations should contain any code that goes outside a servlet’s service methods.

• you may declare static or instance variables or define new methods.

• hello2.jsp defines a getName() method and an expression to print it.

Page 33: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

directives

• directives enable a jsp to have the workhorse (background) servlet set content-type, import a package, set the buffer size, flush the buffer or throw an ioexception when the buffer is filled. Directives also enable a jsp to access user session information.

• Error-maker throws an exception, error-taker displays an error.

Page 34: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

errorMaker.jsp hands error info to errorTaker

Page 35: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Avoid java code in your jsp

• scriptlets, expressions and declarations allow the placement of java code in jsp.

• Text recommends AVOIDING their use

• tag libraries and java beans facilitate separation of presentation and content.

Page 36: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

beans – a slightly modified example from the text

package beanex.example;//note packagepublic class HelloBean { private String name = "World";

public void setName(String name) { this.name = name; }

public String getName() { return name; }}

Page 37: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

beans

• the bean will have to go in the appropriate file under classes.

• in this case classes/beanex/example

Page 38: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

hello3.jsp<%-- hello3.jsp --%>

<%-- page import="HelloBean“… note this is a comment --%>

<jsp:useBean id="hello" class="beans.HelloBean"> <jsp:setProperty name="hello" property="*" /></jsp:useBean>

<HTML><HEAD><TITLE>Hello</TITLE></HEAD><BODY><H1>Hello, <jsp:getProperty name="hello" property="name" /></H1></BODY></HTML>

Page 39: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

same as two previous examples

Page 40: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

and with a parameter

Page 41: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Another jsp/bean example running

Page 42: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

the form

<HTML><BODY><FORM METHOD=POST ACTION="SaveFormData.jsp">Enter your name : <INPUT TYPE=TEXT NAME=userName

SIZE=20><BR>Enter a password : <INPUT TYPE=PASSWORD

NAME=userPass SIZE=20><BR>Enter PIN : <INPUT TYPE=TEXT NAME=userPIN SIZE=4><P><INPUT TYPE=SUBMIT></FORM></BODY></HTML>

Page 43: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

saveform.jsp

Page 44: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

saveform.jsp<jsp:useBean id="user" class="certy.example.UserInfoBean"

scope="session" />

<jsp:setProperty name="user" property="*"/>

<HTML><BODY>

<A HREF="DisplayFormData.jsp">Display Entered Data.</A>

</BODY></HTML>

Page 45: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

DisplayForm.jsp

Page 46: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

DisplayForm.jsp<jsp:useBean id="user" class="certy.example.UserInfoBean"

scope="session"/>

<HTML><BODY>

You entered : <BR/>Name: <%= user.getUserName() %><BR/>Password: <jsp:getProperty name="user" property="userPass"

/><BR/>PIN: <%= user.getUserPIN() %><BR/>

</BODY></HTML>

Page 47: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

the beanpackage certy.example;

public class UserInfoBean { String username; String password; int pin;

public void setUserName( String value ) { username = value; } public void setUserPass( String value ) { password = value; } public void setUserPIN( int value ) { pin = value; } public String getUserName() { return username; } public String getUserPass() { return password; } public int getUserPIN() { return pin; }}

Page 48: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Creating another form(example off internet tutorial – I think)

• Here we show how to create and process an html form.Copy the code (next slide) and place in a file named: myform.jspGo to myform.jsp in your browserYou will see the form you just created.It won't do anything yet.

Page 49: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Myform.jsp<html> <head> <!-- Example --><title>A Form Example</title> </head> <body><form action="myformconfirm.jsp" method="post">Enter in a website name:<br><input type="text" name="website"><br><input type="submit" name="submit"></form></body></html>

Page 50: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Processing a Form

• Here we show how to process the html form your just created.Copy the code below and place in a file named: myformconfirm.jspGo to myform.jspFill in some details and submit the formYou should see the results of your submission

Page 51: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Myformconfirm.jsp processes myform<html> <head> <!-- Example4 --><title>myformconfirm</title> </head> <body><font face=verdana size=3>Your info has been received:<br><br><%String sName = request.getParameter("website");out.print(sName);%></font></body></html>

Page 52: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

myform

Page 53: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Processing myform

Page 54: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Fullform.jsp in notes

Page 55: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Fullformconfirm.jsp in notes

• When you run fullform, and fill in fields, fullformconfirm will acknowledge data entry

Page 56: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Beans

• The useBean action gives the bean a name and the getProperty action can be used to insert a property value directly into your JSP. Here it is the src attribute from an html <img> element. The way this bean works, a new cartoon is loaded on each access.

Page 57: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Beans & JSP, another example: The java (bean) class

package beanex;public class UserData { String username; String email; int age;public UserData(){username="xyz";email="[email protected]";age=21;}public void setUsername( String value ) { username = value; }

public void setEmail( String value ) { email = value; } public void setAge( int value ){age = value;} public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; }}

Page 58: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JavaBeans  A Javabean is a special type of class that has a number of methods. The JSP page can

call these methods so can leave most of the code in these Javabeans. For example, if you wanted to make a feedback form that automatically sent out an email. By having a JSP page with a form, when the visitor presses the submit button this sends the details to a Javabean that sends out the email. This way there would be no code in the JSP page dealing with sending emails (JavaMail API) and your Javabean could be used in another page (promoting reuse).

  To use a Javabean in a JSP page use the following syntax: <jsp : usebean id = " ...." scope = "application" class = "com..." />The following is a list of Javabean scopes: page - valid until page completes. request - bean instance lasts for the client request session - bean lasts for the client session. application - bean instance created and lasts until application ends.

Page 59: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

About the java

• It is a bean: – it has a default constructor – get/set methods for the fields

• Belongs to a package (beanex)

Page 60: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Index.html to get us started

<html>

<body>

Welcome, <A HREF="GetName.html">Start here</A>

</body>

</html>

Page 61: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Getname.html --- a form• <HTML>• <BODY>• <FORM METHOD=POST ACTION="SaveName.jsp">• What's your name? <INPUT TYPE=TEXT NAME=username

SIZE=20><BR>• What's your e-mail address? <INPUT TYPE=TEXT NAME=email

SIZE=20><BR>• What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>• <P><INPUT TYPE=SUBMIT>• </FORM>• </BODY>• </HTML>

Page 62: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

A savename.jsp which uses a bean

<jsp:useBean id="user" class="beanex.UserData" scope="session"/>

<jsp:setProperty name="user" property="*"/>

<HTML>

<BODY>

<A HREF="NextPage.jsp">Continue</A>

</BODY>

</HTML>

Page 63: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

The java beanpackage certy.example;public class UserInfoBean { String username; String password; int pin; public void setUserName( String value ) { username = value; }

public void setUserPass( String value ) { password = value; }

public void setUserPIN( int value ) { pin = value; } public String getUserName() { return username; } public String getUserPass() { return password; } public int getUserPIN() { return pin; }}

Page 64: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Nextpage.html which uses the same bean

<jsp:useBean id="user" class="beanex.UserData" scope="session"/>

<HTML><BODY>You entered<BR>Name: <%= user.getUsername() %><BR>Email: <%= user.getEmail() %><BR>Age: <%= user.getAge() %><BR></BODY></HTML>

Page 65: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

deployment

• In webapps place a directory for this application. (I called mine getnamebean).

Page 66: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Deployment continued

• Drop the html and jsp files into this directory.

• The directory images is empty and META-INF contains a manifest which can be omitted.

Page 67: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Deployment continued: WEB-INF contents

Page 68: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.
Page 69: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

SaveName

Page 70: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

NextPage

Page 71: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

More about deployment directories

• Src is optional, it contains the java bean source.

• Lib is empty, but could contain the jar file for the class(es) needed.

• Classes contains a directory called beanex which contains UserData.class

Page 72: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Web.xml is also optional

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">

<web-app>

<!– this is a comment: no special configuration required -->

</web-app>

Page 73: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

FormBean:display form• <HTML>• <BODY>• <FORM METHOD=POST

ACTION="SaveFormData.jsp">• Enter your name : <INPUT

TYPE=TEXT NAME=userName SIZE=20><BR>

• Enter a password : <INPUT TYPE=PASSWORD NAME=userPass SIZE=20><BR>

• Enter PIN : <INPUT TYPE=TEXT NAME=userPIN SIZE=4>

• <P><INPUT TYPE=SUBMIT>• </FORM>• </BODY>• </HTML>

Page 74: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

A do-nothing jsp<jsp:useBean id="user"

class="certy.example.UserInfoBean" scope="session" />

<jsp:setProperty name="user" property="*"/>

<HTML><BODY>

<A HREF="DisplayFormData.jsp">Display Entered Data.</A>

</BODY></HTML>

Page 75: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Displaying the data stored in the bean

• <jsp:useBean id="user" class="certy.example.UserInfoBean" scope="session"/>

• <HTML>• <BODY>

• You entered : <BR/>• Name: <%= user.getUserName()

%><BR/>• Password: <jsp:getProperty

name="user" property="userPass" /><BR/>

• PIN: <%= user.getUserPIN() %><BR/>

• </BODY>• </HTML>

Page 76: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

A variation

Page 77: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Last jsp

Page 78: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

The same java beanpackage beanex;public class UserData { String username; String email; int age;public UserData(){username="xyz";email="[email protected]";age=21;}public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; }}

Page 79: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Helloworld.jsp(in root directory of tomcat)

<html> <head> <title>My first JSP page </title> </head> <body> <%@ page language="java" %> <% out.println("Hello World"); %> </body> </html>

Page 80: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Running Hello.jsp

• Place it in an appropriate directory, like tomcat/root

Page 81: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Text examples page off your Tomcat server

Page 82: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Click on examples links to run

• http://localhost:8080/ora/ch5/easy.jsp

JSP is as easy as ...1 + 2 + 3 = 6

Page 83: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Easy.jsp source

<%@ page contentType="text/html" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html>

<head>

<title>JSP is Easy</title>

</head> <body bgcolor="white">

<h1>JSP is as easy as ...</h1>

<%-- Calculate the sum of 1 + 2 + 3 dynamically --%>

1 + 2 + 3 =

<c:out value="${1 + 2 + 3}" />

</body>

</html>

Page 84: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP elements

• There are 3 types of elements: directive, action and scripting. EL (expression language) might be treated as a fourth type.

Page 85: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Directives

• JSP begin with a directive indicating page content type:

<%@ page contentType="text/html" %> • Text/html, text/plain and text/xml are some

possible attributes.• The next line of easy.jsp specifies a custom tag

library:<%@ taglib prefix="c"

uri="http://java.sun.com/jsp/jstl/core" %>• Jsp directives have format <%@ content%> and

are processed at translation time.

Page 86: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Comments

• Comments have the form:

<%-- put comment here --%>

• JSP elements like directives and comments do not go to the browser.

Page 87: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Template text

• Besides JSP elements, a JSP page may contain html, xml or any markup language content. This is called template text and it is sent to the browser (after compilation of JSP elements and re-assembly) as is.

• The JSP container doesn’t process or parse this content.

Page 88: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Action Elements

• A JSP may display shopping cart, search results, personalized news or bulletin board messages which are dynamically generated and specific to a client.

• An action is executed when the page is requested. (Request processing phase).

• The only action element in easy.jsp is

<c:out value=“${1+2+3}” />

Page 89: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Action Elements

• If the action element has a body, then it will have an opening tag (possibly with attribute/value pairs), a body, and a closing tag.

• If there is no body, then shorthand notation can be used as in the previous example, in a syntax equivalent to xml.

• The action element has no spaces, and consists of a prefix:name pair. The prefix is defined in the tag library directive and is the prefix that will be used for this library.

• The taglib’s URI is used by the container to find the information needed for processing.

Page 90: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Action Elements

• There are standard, custom and JSTL actions.• Standard actions are part of the jsp specification

and require no tag library. (text pg 53 has a table).

• JSP specification allows for definition of custom actions as well.

• JSTL is meant to obviate the need for custom actions for mundane tasks and includes categories Core (control processing and imports), XML processinf, internationalization and ofrmatting, SQL database actions, and functions.

Page 91: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSTL EL

• EL start with ${ delimiter and end with }

• Literals, booleans, strings, null keyword and variables are supported.

• There are a number of EL implicit variables, too, like pageScope, param, header. (pg 56 table.)

• Special characters must appear in quotes.

• Variables are typed, as in Java.

Page 92: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Standard operators may appear.

These have some variations:• / or div• % or mod• <= or le• == or eq• && or and• ! or not• And so on (table in text pg 56-57)

Page 93: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Implicit ObjectsSo far we know that the developer can create Javabeans and interact

with Java objects. There are several objects that are automatically available in JSP called implicit objects.

  The implicit objects are   Variable Of type Request Javax.servlet.http.httpservletrequest

Response Javax.servlet.http. httpservletresponse Out Javax.servlet.jsp.JspWriter Session Javax.servlet.http.httpsession PageContent Javax.servlet.jsp.pagecontext Application Javax.servlet.http.ServletContext Config Javax.servlet.http.ServletConfig Page Java.lang.Object  

Page 94: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

objects

Page object  Represents the JSP page and is used to call any methods defined by

the servlet class.   Config object  Stores the Servlet configuration data.   Request object  Access to information associated with a request. This object is

normally used in looking up parameter values and cookies.   <% String devStr = request.getParameter("dev"); %> Development language = <%= devStr %>   This code snippet is storing the parameter "dev" in the string devStr.

The result is displayed underneath.

Page 95: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Some examples from text and tutorials: a loop example

• For the next example, we will make use of the different tags we have learnt. This example will declare two variables; one string used to stored the name of a website and an integer called counter that displays the number of times the page has been accessed. There is also a private method declared to increment the counter. The website name and counter value are displayed.

Page 96: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Jsp example 2<HTML> <HEAD> <!-- Example2 --><TITLE> JSP loop</TITLE> </HEAD> <BODY> <font face=verdana color=darkblue>JSP loop<BR> <BR> <%!public String writeThis(int x){ String myText=""; for (int i = 1; i < x; i++) myText = myText + "<font size=" + i + " color=darkred face=verdana>JSP

Tutorial</font><br>" ; return myText;}%> This is a loop example from the <br><%= writeThis(8) %> </font></BODY> </HTML>

Page 97: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Running loop.jsp

Page 98: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Get client’s computer information

<html>  <head> <!-- Example5 --><title>clientinfo.jsp</title>  </head> <body>Client computer details:<br><br><b>Ip address</b>:<br><%=request.getRemoteAddr()%><br><br><b>Computer name</b>:<br><%=request.getRemoteHost()%><br><br></body></html>

Page 99: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Clientinfo.jsp

Page 100: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Tomcat’s example jsp files

Tomcat comes with a number of JSP examples in a directory:

Web-apps/jsp-examples

These can be run by entering

http://IP:port/jsp-examples/subdir/file.jsp

On my IP/tomcat server, it would be

http://csci345.oneonta.edu:8080/jsp-examples/file.jsp

Page 101: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JSP examples on Tomcat

• http://localhost:8080/jsp-examples/checkbox/check.html

Page 102: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

submit

Page 103: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

A get date example:http://localhost:8080/jsp-examples/dates/dat

e.jsp

Page 104: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

http://localhost:8080/jsp-examples/colors/colrs.jsp

Page 105: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Using Javabeans in J2EE Design.

 If you thought that Javabeans were only useful in doing Swing Java applications then you are wrong. To minimise the (presentation logic) code in your JSP, Javabeans are used to produce reusable methods. The JSP specification provides clear ways of using Javabeans in JSP pages.

Page 106: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JavaBeans

• JavaBeans are java classes satisfying the bean specification:

• Must have a no argument constructor

• Package name is recommended

• Properties (fields) are accessed via get() and set() methods

• Should implement serializable interface

Page 107: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

JavaBeans –an example

package something;

public class Name implements java.io.Serializable {

private String theName;

public Name(){theName=“Bob”;}

public void setName(String n){theName=n;}

public String getName(){return theName;}

}

Page 108: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Cartoon JSP using a bean:http://localhost:8080/ora/ch6/cartoon.jsp

<html> <head> <title>A dose of Dilbert</title> </head> <body bgcolor="white"> <h1>A dose of Dilbert</h1> <jsp:useBean id="cartoon"

class="com.ora.jsp.beans.motd.CartoonBean" /> <img src="images/<jsp:getProperty name="cartoon" property="fileName" />"> </body>

</html>

Page 109: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.
Page 110: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Cartoon.jsp source<html> <head> <title>A dose of Dilbert</title> </head> <body bgcolor="white"> <h1>A dose of Dilbert</h1>

<jsp:useBean id="cartoon" class="com.ora.jsp.beans.motd.CartoonBean" />

<img src="images/<jsp:getProperty name="cartoon" property="fileName" />">

</body></html>

Page 111: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Stealing a JSP example from the text

• http://localhost:8080/my-jsp/cartoon.jsp• Need to copy images directory and tags from this

chapter examples to my-jsp directory structure.

Page 112: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Using JSP tags There are four main tags:

• Declaration tag

• Expression tag

• Directive tag

• Scriptlet tag

• Action tag

Page 113: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Declaration tag( <%! %> ) This tag allows the developer to declare variables or methods. Before the declaration you must have <%! At the end of the declaration, the developer must have %>   Code placed in this tag must end in a semicolon ( ; ).   Declarations do not generate output so are used with JSP expressions or scriptlets.   For Example,   <%!   private int counter = 0 ;

private String get Account ( int accountNo) ; %>

Page 114: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Expression tag

( <%= %>)   This tag allows the developer to embed any Java

expression and is short for out.println().   A semicolon ( ; ) does not appear at the end of the code

inside the tag.   For example, to show the current date and time.     Date : <%= new java.util.Date() %>

Page 115: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Directive tag( <%@ directive ... %>) A JSP directive gives special information about the page to the JSP

Engine. There are three main types of directives: 1)     page - processing information for this page.2)     Include - files to be included.3)     Tag library - tag library to be used in this page. Directives do not produce any visible output when the page is

requested but change the way the JSP Engine processes the page.

Page 116: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Directives

• 1.     Page directive

• This directive has 11 optional attributes that provide the JSP Engine with special processing information. The following table lists the 11 different attributes with a brief description:

•  

Page 117: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

   Include directive

 Allows a JSP developer to include contents of a file inside another.

Typically include files are used for navigation, tables, headers and footers that are common to multiple pages.

  Two examples of using include files:  This includes the html from privacy.html found in the include directory

into the current jsp page. <%@ include file = "include/privacy.html" %> or to include a naviagation menu (jsp file) found in the current

directory. <%@ include file = "navigation.jsp" %> Include files are discussed in more detail in the later sections of this

tutorial.

Page 118: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

     Tag Lib directive 

A tag lib is a collection of custom tags that can be used by the page. <%@ taglib uri = "tag library URI" prefix = "tag Prefix" %> Custom tags were introduced in JSP 1.1 and allow JSP developers to hide complex server side code from web designers. This topic will be covered in the Advanced JSP tutorial at visualbuilder.com

Page 119: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Scriptlet tag

( <% ... %> )

Between <% and %> tags, any valid Java code is called a Scriptlet. This code can access any variable or bean declared.

For example, to print a variable.

<%

String username = "visualbuilder" ;

out.println ( username ) ;

  %>

Page 120: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Action tag

    There are three main roles of action tags :   1)     enable the use of server side Javabeans 2)     transfer control between pages 3)     browser independent support for applets.        

Page 121: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Text chapter 7

Page 122: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Custom Action for a bean:classpath environment variable to compile

javax.servlet.jsp classes

C:\xerces-j-bin.2.7.0\xerces-2_7_0\xercesimpl.jar;C:\xerces-j-bin.2.7.0\xerces-2_7_0\resolver.jar;C:\jakarta-tomcat-5.5.10\common\lib\activation.jar;C:\jakarta-tomcat-5.5.10\common\lib\mail.jar;c:\program files\java\jdk1.5.0_03\bin;c:\progra~1\java\jdk1.5.0_03\lib;C:\Progra~1\Java\jdk1.5.0_03\bin;c:\soap\soap\lib\soap.jar;C:\jakarta-tomcat-5.5.10\webapps\ROOT\WEB-INF\classes;c:\jakart~1.10\common\lib;c:\jakart~1.10\common\lib\jsp-api.jar;c:\jakart~1.10\common\lib\servle~1.jar

Page 123: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Custom Action for a bean:a simple bean

package beanex2;public class SomeBean{

String field;String message;public SomeBean(){message="Hello";field="nobody";}

public void setField(String x){field=x;}

public String getMessage(){return message+field;}}

Page 124: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Custom Action for a bean:java TagHandler class

package beanex2;import java.io.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class TagExample extends SimpleTagSupport{private SomeBean sb= new SomeBean();

private String field;public void setField(String fvalue){field=fvalue;}

public void doTag() throws IOException{sb.setField(field);JspWriter out =getJspContext().getOut();out.println(sb.getMessage());}}

Page 125: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Compile the java files

• C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>javac beanex2\TagExample.java

• C:\PROGRA~1\JAVA\JDK15~1.0_0\BIN>

Page 126: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

sample tld files from ora (in notes below also)<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"

"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"><taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>examples</short-name> <uri>C:\jakarta-tomcat-5.5.10\webapps\myfolder\WEB-INF\examples</uri> <description>

A simple tab library for the examples </description><!-- A simple Tag --> <!-- foo tag --> <tag> <name>foo</name> <tag-class>examples.FooTag</tag-class> <tei-class>examples.FooTagExtraInfo</tei-class> <body-content>JSP</body-content> <description>

Perform a server side action; uses 3 mandatory attributes </description> <attribute> <name>att1</name> <required>true</required> </attribute> <attribute> <name>att2</name> <required>true</required> </attribute> <attribute> <name>att3</name> <required>true</required> </attribute> </tag> </taglib>

Page 127: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Chapter 15 JSP & XML

• You’ll need to copy jstl.jar plus the text’s tags directory and mytags.tld to appropriate places in your jsp directory.

Page 128: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

A jsp containing xml

• Remember, jsp may contain any markup language, not just html

• In this example, the jsp contains names, ids and emails in xml.

• We use an xsl file (import) to generate an html page from the xml.

Page 129: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Emails_html.jsp<%@ page contentType="text/html" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %><html> <head> <title>Email List</title> </head> <body bgcolor="white"> <c:import url="emailtable.xsl" var="stylesheet" /> <x:transform xslt="${stylesheet}"> <?xml version="1.0" encoding="ISO-8859-1"?> <students> <student id="123"> <first-name>Katie</first-name> <last-name>Higgins</last-name> <email>HigginKM</email> </student>…. </students> </x:transform> </body></html>

Page 130: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Emailtable.xsl (in notes,too)<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="students"> <table border="1" width="100%"> <tr> <th>ID</th> <th>Student Name</th> <th>Email</th> </tr> <xsl:for-each select="student"> <tr> <td> <xsl:value-of select="@id"/> </td> <td> <xsl:value-of select="last-name"/>, <xsl:value-of select="first-name"/> </td> <td> <xsl:value-of select="email"/> </td> </tr> </xsl:for-each> </table> </xsl:template></xsl:stylesheet>

Page 131: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

In tomcat

Page 132: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Another xml/xsl example in jsp

• In the notes I placed a jsp containing xml markup for the courses I teach (titles, numbers, and texts)

• I created a stylesheet to traverse this xml and return course titles, numbers and so on to populate an html table

Page 133: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Xsl in notes

• See notes below for the stylesheet

Page 134: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

http://csci345.oneonta.edu:8080/myfolder/schedule.jsp

Page 135: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Scriptlets: chapter 16

• A random color function:String randomColor() { java.util.Random random = new java.util.Random(); int red = (int) (random.nextFloat() * 255); int green = (int) (random.nextFloat() * 255); int blue = (int) (random.nextFloat() * 255); return "#" + Integer.toString(red, 16) + Integer.toString(green, 16) + Integer.toString(blue, 16); }

Page 136: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

A random color jsp: generates an html table with random colors: entire jsp in notes

<html> <head> <title>Random Color</title> </head> <body bgcolor="white"> <h1>Random Color</h1> <table border="1" width="100%"> <tr>

<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>

</tr> <tr><td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> </tr> <tr>

<td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>

</tr> <tr> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td> <td bgcolor="<%= randomColor() %>" width="100" height="100">&nbsp;</td>

</tr> </table> </body></html>

Page 137: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

In tomcat: http://csci345.oneonta.edu/myfolder/colors.jsp

Page 138: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

Init and destroy (see servlet notes) used in a jsp<%@ page language="java" contentType="text/html" %><%@ page import="java.util.Date" %><%!Date orig;int globalCounter = 0; public void jspInit(){orig=new Date();}public void jspDestroy(){ServletContext context=getServletConfig().getServletContext();context.log("greeting.jsp visited"+globalCounter+"times between" +orig+"and"+(new

Date()));} private String getGreeting() { Date now = new Date(); String greeting = now.toString(); if (now.getHours() < 12) { greeting +="Good morning"; } else if (now.getHours() < 18) { greeting += "Good day"; } else { greeting += "Good evening"; } return greeting; }%>

Page 139: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

The rest of greeting.jsp<html> <head> <title>Using several techniques</title> </head> <body bgcolor="white"> <%= getGreeting() %> <% if (request.getParameter("name") == null) { %> stranger! <% } else { %> partner! <% } %> <p>How are you?</p> <% String userAgent = request.getHeader("User-Agent"); if (userAgent.indexOf("MSIE") != -1) { %> You're using Internet Explorer. <% } else if (userAgent.indexOf("Mozilla") != 1) { %> You're probably using Netscape. <% } else { %> You're using a browser I don't know about. <% } %> <p>This page has been visited: <%= ++globalCounter %> times since <%= orig %>.</p>

</body></html>

Page 140: JavaServer Pages Some notes from: the Hans Bergen text Hunter text Sebesta text JSP and XML text And from tutorial sites on the web.

csci345.oneonta.edu:8080/myfolder/greeting.jsp


Recommended