Introduction - Minnesota State University, Mankato



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 . 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

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 that are evaluated and inserted into the HTML.

2. Scriptlets (or known as Java scriptlets) of the form that contains blocks of Java code.

3. Declarations of the form contains the declaration of parameters that can be used through out the JSP page.

Note: the followings are equivalent.





Directive

A JSP directive affects the overall structure of the resultant servlet. The form is

. The most common directive is page. Below is its sample code.

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 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.

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:

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 that stores visitor’s name and email. For

each variable there must be a setter and a getter. Variables must be in lower case and setter/getter begins with set/get with the variable which has the first character uppercased. Imagine entering all input variables from user into a bean, it is lengthy to specify all the setters. There is a little trick when setting bean parameters by using

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.

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.

In the example, the HTML page declares the library and use the tag 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 attributes. Same rule that applied to 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 uppercased. An output is shown below.

[pic]

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 that are evaluated and inserted into the HTML.

• Scriptlets (or known as Java scriptlets) of the form that contains blocks of Java code.

• Declarations of the form 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

1. Which below is not a predefined JSP variable?

a) request

b) out

c) config

d) pageTags

2. 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

3. 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

4. What does JSP directive construct do?

a) Define new redirect page

b) Control servlet engine

c) Control JSP page

d) Control HTML output

References

Hall, M. “Servlets and JavaServer Pages” 1st ed. Prentice Hall, Upper Saddle River NJ

JSP Tutorial, Nov 15, 05

Holzner, Steve., Holzner, Steven, “Getting Started with JSP”, Sams Publishing, , Nov 15, 05

GetCourse.jsp

Get Name and Course

What's your name?

Select a course

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;

}

}

GetCourseWithTag.jsp

This jsp page uses dropdownlist tag to create the dropdownlist. The underlying code of the tag creates the list.

Get Name and Course with DropList tag

What's your name?

Select a course

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("");

//ResultSetMetaData rsmd=rsDatabase.getMetaData();

getJspContext().getOut().write(""+

"Please select course");

while (rsDatabase.next()) {

getJspContext().getOut().write(""

+rsDatabase.getObject(2)+"");

}

getJspContext().getOut().write("");

}catch(Exception e){System.out.println(e);}

}

public void setQuery(String query){

this.query = query;

}

public void setListname(String listname){

this.listName = listname;

}

}

mytag-taglib.tld

Decriptor file of the library.

1.0

1.1

simple

A simple tab library for the examples

dropdownlistquery

tony.DropDownList

EMPTY

perform

query

true

listname

true

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.

Welcome

Welcome

NextPage.jsp

This page creates a table of the selected course from the dropdownlist.

Hello World!

says "Hello World"

[pic]

GetName.html

This is an example that uses JavaBean. Data are saved in SaveName.jsp.

JavaBean Example

What's your name?

What's your e-mail address?

What's your age?

SaveName.jsp

It initiates a bean and stores information in it.

Saved to a bean

Continue

NextPage1.jsp

Display bean content.

Retrieve from bean

You entered

Name:

Email:

Age:

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

-----------------------

Hello, world

Goodbye, world

Your text

Continue

The text is

public class SimpleBean {

private String message = "No message specified";

public String getMessage() {

return(message);

}

public void setMessage(String message) {

this.message = message;

}

}

Message:

Get Name and Course with DropList tag

1.0

1.1

simple

A simple tab library for the examples

tagExample

tony.myTagExample

EMPTY

perform

name

true

lname

true

// This is myTagExample.java

package tony;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.SimpleTagSupport;

import java.io.IOException;

/**

* 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;

}

public void setLname(String lname){

this.lastName = lname;

}

}

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download