Introduction to Java Server Pages (.jsp)
What is JSP?
- JSP is a combination of HTML web page formatting tags and Java
code. The basic components include:
- HTML Code
- JSP tags (scriplets,
expressions, declartaions, etc.)
- JSP implicit objects (request, response, session, config)
- JavaBeans
- Used to create dynamic web pages, that is, web pages that could
have different content each time they are viewed.
- How does it work?
- A user requests a .JSP page to be viewer in their browser.
- The browser passes the request to the web server
- The web server compiles the JSP file into a Servlet then
executes the servlet. The output of the servlet is HTML content
to be viewed by the browser.
- What can it do?
- access databases and files on the server, track transactions,
process forms and queries.
Basic JSP Tags
- Most JSP tags are paired tags, ie they have a staring tag
begining with <% and an
ending tag %>
- declation tags <%!
...... %>
- used to declare variables and methods used within the JSP file
(note, a JSP file is sort of analogous to a class file).
- typically they are placed in the begining of the body
section of the html code.
- In the example below, the dark green is the declaration tag
secion. It starts with the <%!
tag and ends with the %>
tag.
- Variables can have any of the standard Java data types (float,
int, long, double, char, String, boolean, etc.)
- Arrays are defined the same as in Java
- Note: you do not use the import statement in JSP,
instead, declare library objects using their full package
specification or use the directive tag (see below), e.g.
- java.util.Vector v = new java.util.Vector(10,5);
- java.text.DecimalFormat currency = new
java.text.DecimalFormat("$0.00");
- Caution: You
should take special care with variables defined in declartion tags as
they are shared by each instance of the page (running in separate
threads on the server). That is, if two users have a web page open,
then the jsp/servet for that page is shared between the users
processes, thus data in the variables are used by both processes.
Conflicts and inconsistencies
can result!
- scriplet tags <% .... %>
- used to include java logic within the web page. typically
this consists for control structures (if, for, while) statements used
to determine if and how much html to generate.
- they can occur anywhere in the JSP file betwen the <body>
and </body> tags
- scriptlet code is in red in the example below
- expression tags <%= .... %>
- used to format output from java code to the web page.
- inside this tag is a single java expression (not a statement)
that evaluates to a String. This string is output with the rest
of the html.
- expression tags are in purple below.
- comment tags <%-- ... -->
- comments are hidden from the user (unlike html comments)
- you can also add regular java style comments to your
declaration, and scriplet tags.
- directive tags <%@ .....
%>
- used to import libraries and setup error pages,
instead of using the import statement, use the import
directive,
e.g.
<%@
page import="java.text.*"%> or <%@ page
import="java.text.DecimalFormat"%>
- used to insert/include lines of code, the following statement
inserts lines of code from common.jsp.
<%@
include file="common.jsp" %>
Creating a JSP project in NetBeans:
- First, be sure that the Java
Web Applications plug in is installed
- to do this, open netbeans, then select Tools-Plugins from the menu
- click on the "Installed tab", if Java Web Applications is not
there, then follow the procedures in the "Getting started with Netbeans
Tab"
- Create a new project, this time select Web as the category and Web Application as the project type
- On the next screen select your project name and location.
use the defaults for all other settings
- press Finish
- Your project will be created with the following file structure
- nbproject (netbeans project information)
- src (java source)
- test (test procedures)
- web (html and jsp pages)
- web-inf and meta-inf are directories to setup the
webserver
- Inside the web folder will be index.jsp, your root file for the
web pages.
- Now create your JSP files
- Right click on the web folder
- Select New-Jsp
- Enter name of your jsp and press finish. .
- Netbeans will create a sample jsp file. You can change the title
tag
contents, note the two lines begining <%-- are jsp comment lines
suggesting
how to setup the jsp session and access to java beans. More on
this
later.
<%--
Document : index
Created on : Oct 24, 2011, 11:42:23 AM
Author : Mark Pendergast
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP
Page</title>
</head>
<body>
<h1>Hello
World!</h1>
</body>
</html>
Entering and testing a simple JSP.
- You can now edit the JSP file as you would any text file.
- At the begining of the body section you should put your
declaration
tags (tags containing variables and methods)
- Throughout the HTML code you can add scriplet tags and expression
tags.
- To test your JSP file, right click on the file in the file
systems window and press "run file". Netbeans will then load the tomcat
server (if this is the first time you've pressed execute), then tell
the server to process the jsp. Your default browser will receive
the output (or compile error messages).
- Notes:
- Make sure that your html tags are correct, ie a missing or
broken tag can cause server errors.
- Syntax errors in your code will be reported on the web
browser.
- Your jsp code can use System.out.println() as you do in other
applications to help track progress and debug your work.
- Also, don't use the import statement, instead, either
fully quailify
your library objects, e.g. java.text.DecimalFormat, or use the
page directive (more on directives later).
<%@
page import="java.util.*" %>
- If the tomcat server has trouble loading, exit NetBeans and try
again.
Exporting your work to a real server.
- JSPs and Servlets are packaged into Web Archive Files so that
they can be deployed (made available) on web servers.
- The War file contains all the JSP files, images, Javabeans, Html
files necessary to run the application (e.g. everthing in your web
module).
- War files are created whenever you perform a build of the
project. They are stored in the dist directory.
A first example - creating a table of Mortgage payments (basic1.jsp)
- Declarations are in green
- Scriplets are in red
- Expressions are in purple
- HTML is in blue
- In the declarations are
- variables to hold the run parameters
- method to calculate monthly payments
- The scriplets generate the data appearing in the table cells
- The expressions transfer data from the scriplets to the html code.
- One of the difficult parts of creating the page is to get all the
staring and ending JSP tags in the proper place. Netbeans colors the
background of JSP light yellow to help.
JSP
Page that displays a mortgage payment calculation table
<%@page
contentType="text/html"%>
<%@page
pageEncoding="UTF-8"%>
<html>
<head><title>JSP
Page</title></head>
<body>
<%--
<jsp:useBean id="beanInstanceName" scope="session"
class="beanPackage.BeanClassName" /> --%>
<%--
<jsp:getProperty name="beanInstanceName"
property="propertyName" /> --%>
<%!
java.text.DecimalFormat currency = new
java.text.DecimalFormat("$#,###,###,##0.00");
java.text.DecimalFormat interest = new java.text.DecimalFormat("0.0%");
/*
* Compute monthly payment given principle, yearly interest rate
* and number of years for the loan
*/
double computeMonthlyPayment(double principle, double rate, double
years)
{
double monthlyRate = rate/12.0;
double payment = principle * monthlyRate / (1 - 1 /
Math.pow(1+monthlyRate,years * 12));
return payment;
}
%>
<h2>Monthly
Payment Calculation Table </h2>
<table
border = 1>
<%
double beginingRate = .01;// first rate to use in the table
double endingRate = .10; // last rate to use in the table
double rateIncrement = .01; // amount to increment rate each time
double beginingPrinciple = 100000.0; // first principle in table
double endingPrinciple = 500000.0; // last principle in
table
double principleIncrement =100000.0; // amount to increment principle
each time
double years = 30;
//
// output a row of column headers
//
%>
<tr><th>30 years</th>
<%
for(double principle = beginingPrinciple; principle <=
endingPrinciple;
principle += principleIncrement)
{
%>
<th><%=
currency.format(principle) %>
</th>
<%
}
%>
</tr>
<%
for(double rate = beginingRate; rate <= endingRate; rate +=
rateIncrement)
{
%>
<tr>
<th> <%=
interest.format(rate) %>
</th>
<%
for(double principle = beginingPrinciple; principle <=
endingPrinciple;
principle +=
principleIncrement)
{
double payment = computeMonthlyPayment(principle, rate, years);
%>
<td> <%=
currency.format(payment) %> </td>
<%
}
%>
</tr>
<%
}
%>
</table>
</body>
</html>