Download Introduction - About Krypton

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Antonio Ko
Introduction to JSP
Introduction
Java Server Page (JSP) is Sun Microsystems’ answer to Microsoft’s Active Server Page
(ASP). Like ASP, it lets you mix regular, static HTML with dynamically-generated HTML.
A JSP page is simply a normal HTML page with special tags most of which start with <%
and end with %>. Instead of file extension with “.html”, JSP files ends with “.jsp”. Before
head on JSP, let us go over quickly on servlet. The reason is that JSP is based on servlet
technology.
Servlet and JSP
Servlets are Java files that compiled into .class files to generate dynamic HTML outputs.
Similar to CGI-like programming, they run on a Web server and build Web pages on the fly
depend on the context of client’s actions. Servlets have better advantages on efficiency,
convenience, cost, and portability over other rival technologies. However, servlet
programming could be lengthy and cumbersome to debug. Also modifying the output HTML
would be difficult, since there are countless print line statements. These drove the
development of JSP. Comparing to servlets, JSPs are much easier to program and to deploy.
So, does easier means less powerful than regular servlets? The answer is no. There is not a
servlet task that JSP could not do. Basically a JSP is a servlet. Servers internally convert JSP
pages into servlets during the first request. There are plenty JSP Web servers either free or
commercial. The most common one is Jakarta Tomcat, which is free to download. Plug-ins
are also available for servers (such as IIS) that don’t know how to handle JSP/servlet.
JSP Syntax
1/19
Antonio Ko
Aside from the regular HTML, there are three main types of JSP constructs: scripting
elements, directives, and actions. Scripting elements enable the insertion of Java code into
HTML. Directives can control the overall structure of the servlet. Actions control the
behavior of the servlet engine or specify existing components to be used.
Scripting Element
The inserted Java code will become part of the servlet that is generated from the current JSP
page. There are three forms:
1. Expressions of the form <%= expression %> that are evaluated and inserted into the
HTML.
2. Scriptlets (or known as Java scriptlets) of the form <% code %> that contains blocks
of Java code.
3. Declarations of the form <%! Code %> contains the declaration of parameters that
can be used through out the JSP page.
Note: the followings are equivalent.
 <%= new java.util.Date() %>
 <% out.println(new java.util.Date()) %>
Directive
A JSP directive affects the overall structure of the resultant servlet. The form is
<%@ directive attribute = “value” %>. The most common directive is page. Below is its
sample code.
<%@ page contentType="text/html; charset=iso-8859-1" language="java"
import="java.sql.*" errorPage="" %>
Note that import imports required classes or packages. errorPage states the where to redirect
when error occurs.
Action
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. With
2/19
Antonio Ko
actions, programmers can insert a file, reuse JavaBeans components, forward the user to
another page and etc. The most interesting actions are listed below:





jsp:include – Include a file at the time the page is requested.
jsp:useBean – Find or instantiate a JavaBean.
jsp:setProperty – Set the property of a JavaBean
jsp:getProperty –Insert the property of a JavaBean into the output.
jsp:forward –Forward the requester to a new Page.
Predefined Variables
Like any other language, JSP has of list predefined variables. There are a total of eight
variables (or called implicit objects). They are request, response, out, session, page
application, config, and pageContext. Request is the HttpServletRequest object that
associated with the request. Response is the HttpServletResponse object that associated with
the response to the client. Out is the PrintWriter object that send output to the client. Session
is the HttpSession object that is bound to the client’s session. Page works like this in Java.
Sample Code
Below is the sample code that demonstrates mixing scriptlets and HTML. Here is a Boolean
variable named “happy”. Output of ether “Hello World” or
“Goodbye Word” is depends on “happy”. Notice that each of the
expression is not enclosed in the Java scriptlets. Like ASP, JSP has a
variable name session that associated with a visitor. Data can be put
in the session and retrieve from it. Below is session example that
consists of GetText.html, SaveText.jsp, and ShowText.jsp.
The session is kept around until a timeout period.
3/19
<%
if ( hello ) {
%>
<P>Hello, world
<%
} else {
%>
<P>Goodbye, world
<%
}
%>
Antonio Ko
<!—This is ShowText.jsp -->
<HTML>
<BODY>
The text is <%= session.getAttribute( "myText" ) %>
</BODY>
</HTML>
<!--This is GetText.html -->
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveText.jsp">
Your text <INPUT TYPE=TEXT NAME=myText SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM></BODY></HTML>
<!--This is SaveText.jsp -->
<%
String sText = request.getParameter( "myText" );
session.setAttribute( "myText", sText );
%>
<HTML>
<BODY><A HREF="ShowText.jsp">Continue</A></BODY>
</HTML>
Use of JavaBean
It is easy to use JavaBean to associate data with each visitor. This is a very useful capability
because of reusability of Java classes. The syntax for specifying a bean should be used is:
<jsp:useBean id="name" class="package.class" />
The jsp:useBean action above instantiates an object of the class specified and binds it to a
variable with the name specified by id. It is also possible to specify a scope attribute that
makes the bean associated with more than just the current page. Below is a simple bean class
public class SimpleBean {
private String message = "No message specified";
that stores visitor’s name and email. For
public String getMessage() {
return(message);
}
each variable there must be a setter and a
getter. Variables must be in lower case and
public void setMessage(String message) {
this.message = message;
}
setter/getter begins with set/get with the
}
variable which has the first character
from user into a bean, it is lengthy to specify all
<HTML>
<BODY>
<jsp:useBean id="test" class="package.myBean" />
<jsp:setProperty name="test"
property="message"
value="Hello World" />
the setters. There is a little trick when setting
Message: <jsp:getProperty name="test"
property="message" />
bean parameters by using
</BODY>
</HTML>
uppercased. Imagine entering all input variables
4/19
Antonio Ko
<jsp: setProperty name “id” property =”*” />
This would automatically set all input variables into the bean (variable names must be both
equal). One would question about type casting, like what if the bean variable is int. JSP
automatically convert strings into the appropriate type. User will need to handle exceptions if
casting failed.
Tag Libraries
Since JSP 1.1, there is a new capability of extending JSP tags. This gives the developers the
ability to define custom JSP tags. After defining a tag, its attribute, and its body, it can be
grouped with other tags into collections or called tag libraries that can be used in any number
of JSP files. Each tag library requires a tag library descriptor XML file which has the
extension “.tld”. The purpose of the file is to describe the purposes of the tags, paths of their
corresponding classes and their attributes descriptions.
This tag ability permits Java developers to simplify complex server-side behaviors into
simple and easy-to-use elements that content developers can easily incorporate into their JSP
pages. To use custom tag in JSP pages, tag libraries must be first initiated using the taglib
directive. The following line initiates a tag library. Uri would be the corresponding name that
described in Web.xml under the application folder. Prefix would be the name of the library
used through out the JSP page. <%@ taglib uri="mytags" prefix ="mytaglib" %>
After this line, tags in the library mytaglib can be called and used. Tags may have zero or
more attributes and also the optional tag body.
Below is an example. The tag get_name has
one attribute and has no body.
<mytaglib:get_name username = "joedoe" />
5/19
<!—TagExample -->
<html>
<head>
<title>Get Name and Course with DropList tag</title>
</head>
<body>
<%@ taglib uri="mytags" prefix ="mytag" %>
<mytag:tagExample name = "Joe " lname="Doe" />
</body>
</html>
Antonio Ko
In the example, the HTML page
// This is myTagExample.java
package tony;
declares the library and use the tag
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
tagExample with two attributes name
and lname which are specified in its
descriptor file. The corresponding tag
file (the Java file) has two methods
setName and setLname for the defined
/**
* SimpleTag handler that prints "Hello, world!"
*/
public class myTagExample.java extends SimpleTagSupport {
protected String name="";
protected String lastName="";
public void doTag() throws JspException, IOException {
getJspContext().getOut().write(name+
" :Hello world: “ +lastName);
}
public void setName(String name){
this.name = name;
attributes. Same rule that applied to
}
public void setLname(String lname){
this.lastName = lname;
JavaBean applies to the methods as well.
}
Naming of the method would be “set”
}
concatenate with the name of the attribute
(defined in the descriptor file) with first letter
<!—TagLibraryDescriptor -->
<?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/webjsptaglibrary_1_2.dtd">
<taglib>
uppercased. An output is shown below.
<tlib-version>1.0</tlib-version>
<jsp-version>1.1</jsp-version>
<short-name>simple</short-name>
<urn></urn>
<description>
A simple tab library for the examples
</description>
<!-- Display a dropdownlist using sql query string -->
<tag>
<name>tagExample</name>
<tag-class>tony.myTagExample </tag-class>
<body-content>EMPTY</body-content>
<description>
perform
</description>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
<attribute>
<name>lname</name>
<required>true</required>
</attribute>
</tag>
</taglib>
6/19
Antonio Ko
Conclusion
JSP is the answer to Microsoft ASP. It enables the mixing and integrating Java code with
static HTML pages. There are several benefits of JSP over other technologies. The most of
beneficial advantage for Web developers are portability and not tied into a particular server
product.
Five Questions
1. What are the differences between all the Java scriptlet forms?
 Expressions of the form <%= expression %> that are evaluated and inserted into
the HTML.
 Scriptlets (or known as Java scriptlets) of the form <% code %> that contains
blocks of Java code.
 Declarations of the form <%! Code %> contains the declaration of parameters
that can be used through out the JSP page.
2. Define servlet and JavaBean.
 JavaBean is an object that holds data with their setter and getter methods. The
bean object can live through out the session. It’s easy to use to store form
information.
 Servlet is a java class that produces dynamic HTML according to client’s actions.
3. What are the three main constructs of JSP? Define each.
 Scripting elements enables insertion of Java code.
 Directive controls the behavior of the JSP page.
 Action controls the behavior of the JSP engine.
4. What is a tag library descriptor?
 Describes tags of the tag library file. It describes their class paths, attributes and if
tag bodies are required.
5. What are the differences between servlet and JSP?
 JSP pages are HTML page but with Java codes built-in to control HTML behavior.
JSP pages have “.jsp” extension.
 Servlets are Java classes that produce HTML pages.
Multiple Choice
1. Which is/are the main requirement(s) of JavaBean?
a) Extend JavaBean class
b) Implementation setters and getters of the variables
c) Requires to implement a servlet
d) a and b
7/19
Antonio Ko
2. Which below is not a predefined JSP variable?
a) request
b) out
c) config
d) pageTags
3. Which below is/are advantage of JSP?
a) JSP is in Java
b) JSP creates dynamic HTML pages
c) JSP pages are portable
d) All the above
4. What does JSP action construct do?
a) Define actions of HTML forms
b) Control servlet engine
c) Creates new Java tag
d) Define new JSP construct
5. What does JSP directive construct do?
a) Define new redirect page
b) Control servlet engine
c) Control JSP page
d) Control HTML output
8/19
Antonio Ko
References
Hall, M. “Servlets and JavaServer Pages” 1st ed. Prentice Hall, Upper Saddle River NJ
JSP Tutorial, http://www.jsptut.com/ Nov 15, 05
Holzner, Steve., Holzner, Steven, “Getting Started with JSP”, Sams Publishing,
http://www.samspublishing.com/articles/article.asp?p=31072&seqNum=6 , Nov 15, 05
9/19
Antonio Ko
GetCourse.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage=""
%>
<%@ page import = "tony.sqlUtil"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Get Name and Course</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form method=POST action="Welcome.jsp">
<table width="716" border="0">
<tr>
<td width="58" height="40"></td>
<td width="268">What's your name?
<input type=TEXT name="username" size=20></td>
<td width="376"></td>
</tr>
<tr>
<td height="34"></td>
<td>Select a course
<%
try{
String mysql = "select * from Course";
ResultSet rsDatabase = sqlUtil.query DB(mysql);
out.println("<select name=\"droplist\">");
out.println("<option value =\"No course selected\">"+
"Please select course</option>");
while (rsDatabase.next()) {
out.println("<option value="+rsDatabase.getObject(1)+">"+
rsDatabase.getObject(2)+"</option>");
}
out.println("</select>");
}catch(Exception e){System.out.println(e);}
%></td>
<td></td>
</tr>
<tr>
<td height="68"></td>
<td><input name="Input" type=SUBMIT value="Submit"></td>
<td></td>
</tr>
</table></Form>
</body>
</html>
10/19
Antonio Ko
sqlUtil.jsp
Used by GetCourse.jsp for the database connection.
package tony;
import java.sql.*;
public class sqlUtil{
public static ResultSet queryDB(String mysql){
Connection conDatabase;
Statement qryDatabase;
ResultSet rsDatabase;
try{
//open connection to database
/* set up DriverManager to let it know we want to communicate with
ODBC data sources. Calling the static forName() method of the Class class*/
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to connection string to the database
String sURL = "jdbc:odbc:Driver={Microsoft Access Driver
(*.mdb)};DBQ=C:\\Tomcat 5.5\\webapps\\jsp_test\\sqlpractice.mdb";
//sURL += getConnectionData().trim() + ";DriverID=22;READONLY=true}";
//System.out.println("url: "+sURL);
// create connection to database using connection string
conDatabase = DriverManager.getConnection(sURL, "", "");
// setup java.sql.Statement to run queries
qryDatabase = conDatabase.createStatement();
//System.out.println("hell Antonio2");
//String mysql = "select * from Course";
rsDatabase = qryDatabase.executeQuery(mysql);
return rsDatabase;
}catch(Exception e){System.out.println(e);}
return null;
}
}
11/19
Antonio Ko
GetCourseWithTag.jsp
This jsp page uses dropdownlist tag to create the dropdownlist. The
underlying code of the tag creates the list.
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage=""
%>
<%@ page import = "tony.sqlUtil"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Get Name and Course with DropList tag</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form method=POST action="Welcome.jsp">
<%@ taglib uri="mytags" prefix ="mytag" %>
<table width="716" border="0">
<tr>
<td width="58" height="40"></td>
<td width="268">What's your name?
<input type=TEXT name="username" size=20></td>
<td width="376"></td>
</tr>
<tr>
<td height="34"></td>
<td>Select a course <mytag:dropdownlistquery query = "select * from Course" listname="droplist" />
</td>
<td>
</td>
</tr>
<tr>
<td height="68"></td>
<td><input name="Input" type=SUBMIT value="Submit"></td>
<td></td>
</tr>
</table></Form>
</body>
</html>
12/19
Antonio Ko
DropDownList.java
Tag that creates dropdownlist.
package tony;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.sql.*;
public class DropDownList extends SimpleTagSupport {
protected String query="";
protected String listName="";
public void doTag() throws JspException, IOException {
Connection conDatabase;
Statement qryDatabase;
ResultSet rsDatabase;
try{
//open connection to database
// set up DriverManager to let it know we want to communicate with
// ODBC data sources. Calling the static forName() method of the Class class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to connection string to the database
String sURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};"+
"DBQ=C:\\Tomcat 5.5\\webapps\\jsp_test\\sqlpractice.mdb";
// create connection to database using connection string
conDatabase = DriverManager.getConnection(sURL, "", "");
// setup java.sql.Statement to run queries
rsDatabase = conDatabase.createStatement().executeQuery(query);
getJspContext().getOut().write("<select name="+listName+">");
//ResultSetMetaData rsmd=rsDatabase.getMetaData();
getJspContext().getOut().write("<option value =\"No course selected\">"+
"Please select course</option>");
while (rsDatabase.next()) {
getJspContext().getOut().write("<option value="+rsDatabase.getObject(1)+">"
+rsDatabase.getObject(2)+"</option>");
}
getJspContext().getOut().write("</select>");
}catch(Exception e){System.out.println(e);}
}
public void setQuery(String query){
this.query = query;
}
public void setListname(String listname){
this.listName = listname;
}
}
13/19
Antonio Ko
mytag-taglib.tld
Decriptor file of the library.
<?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.1</jsp-version>
<short-name>simple</short-name>
<urn></urn>
<description>
A simple tab library for the examples
</description>
<!-- Display a dropdownlist using sql query string -->
<tag>
<name>dropdownlistquery</name>
<tag-class>tony.DropDownList</tag-class>
<body-content>EMPTY</body-content>
<description>
perform
</description>
<attribute>
<name>query</name>
<required>true</required>
</attribute>
<attribute>
<name>listname</name>
<required>true</required>
</attribute>
</tag>
</taglib>
14/19
Antonio Ko
Welcome.jsp
jsp pageThis JSP page get called by GetCourse.jsp or
GetCourseWithTag.jsp. This JSP page puts necessary data into
session. It has a link to the last page NextPage.jsp.
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage=""
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
String myCourse = request.getParameter( "droplist" );
session.setAttribute( "course", myCourse );
%>
<html>
<head>
<title>Welcome <%=request.getParameter( "username")%></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!-.style1 {color: #0033CC}
-->
</style>
</head>
<body>
<form method=POST action="NextPage.jsp">
<table width="650" border="0">
<tr>
<td width="102" height="58"></td>
<td width="408"><h1>Welcome <span class="style1">
<%= session.getAttribute( "theName")%>
</span> </h1></td>
<td width="126">
</tr>
<tr>
<td height="214"></td>
<td><input name="Input" type=SUBMIT value="Continue"></td>
<td></td>
</tr>
</table></Form>
</body>
</html>
15/19
Antonio Ko
NextPage.jsp
This page creates a table of the selected course from the dropdownlist.
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage=""
%>
<%@ page import = "tony.sqlUtil" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World!</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
</title>
<table width="650" border="0">
<tr>
<td width="102" height="58"></td>
<td width="408"><h1><span class="style1"><%=session.getValue("theName")%></span>
<span class="style2">says "Hello World"</span> </h1></td>
<td width="126"></td>
</tr>
<tr>
<td height="214"></td>
<td>
<table border="1" width="100%" id="table1" style="border-collapse: collapse">
<%
try{
String mysql = "select Course.name As courseName, Student.lname, Student.fname,
CourseStudent.grade, Student.Email";
mysql+= " FROM Student INNER JOIN (Course INNER JOIN CourseStudent ON ";
mysql+= "Course.Course = CourseStudent.Course) ON Student.ID = CourseStudent.ID ";
mysql+= "WHERE Course.Course = " + session.getAttribute("course");
ResultSet rsDatabase = tony.sqlUtil.queryDB(mysql);
ResultSetMetaData rsmd=rsDatabase.getMetaData();
String tempString="";
//display column names
String titleFont = "<font face=\"Arial\" size=\"4\" color=\"#FFFFFF\">";
for(int i=1; i<=rsmd.getColumnCount();i++){
tempString += "<TD bgcolor=\"#0066FF\">"+titleFont
+ rsmd.getColumnName(i)+"</font></TD>";
}
out.println("<TR>"+tempString+"</TR>");
tempString = "";
int j=0;
String styleColor = "bgcolor=\"#CCFFFF\"";
while (rsDatabase.next()) {
for(int i=1; i<=rsmd.getColumnCount();i++){
if(j%2==1)
tempString += "<TD "+styleColor+">" + rsDatabase.getObject(i)+"</TD>";
else
16/19
Antonio Ko
tempString += "<TD>" + rsDatabase.getObject(i)+"</TD>";
}
out.println("<TR>"+tempString+"</TR>");
j++;
tempString = "";
}
out.println("</Table>");
}catch(Exception e){out.println("</Table>No course selected");}
%>
</td>
<td>
</tr>
</table>
</body>
</html>
17/19
Antonio Ko
GetName.html
This is an example that uses JavaBean. Data are saved in
SaveName.jsp.
<HTML>
<head>
<title>JavaBean Example</title>
</head>
<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>
SaveName.jsp
It initiates a bean and stores information in it.
<%@page language="java"%>
<jsp:useBean id="myData" class="tony.UserData" scope="session"/>
<jsp:setProperty name="myData" property="*"/>
<HTML>
<head>
<title>Saved to a bean</title>
</head>
<BODY>
<A HREF="NextPage1.jsp">Continue</A>
</BODY>
</HTML>
NextPage1.jsp
Display bean content.
<jsp:useBean id="myData" class="tony.UserData" scope="session"/>
<HTML>
<head>
<title>Retrieve from bean</title>
</head>
<BODY>
You entered<BR>
Name: <%= myData.getUsername() %><BR>
Email: <%= myData.getEmail() %><BR>
Age: <%= myData.getAge() %><BR>
</BODY>
</HTML>
18/19
Antonio Ko
UserData.java
This is the implementation of UserData bean.
public class UserData {
private String username;
private String email;
private int age;
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; }
}
Tomcat Application Folder
19/19