Getting Familiar with your JSP server - Kanpur Institute Of ...

illinoiseggoΛογισμικό & κατασκευή λογ/κού

28 Οκτ 2013 (πριν από 3 χρόνια και 11 μήνες)

129 εμφανίσεις

ASP Introduction

An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed on the server.

What you should already know

Before you continue you should have some basic understanding of the following:



HTML / XHTML



A
scripting language like JavaScript or VBScript

What is ASP?



ASP stands for
A
ctive
S
erver
P
ages



ASP is a Microsoft Technology



ASP is a program that runs inside
IIS



IIS stands for
I
nternet
I
nformation
S
ervices



IIS comes as a free component with
Windows 2000



IIS is also a part of the
Windows NT 4.0 Option Pack



The Option Pack can be
downloaded

from Microsoft



PWS

is a smaller
-

but fully functional
-

version of IIS



PWS can be found on your
Windows 95/98 CD

ASP Compatibility



To run IIS you must have Windows NT 4
.0 or later



To run PWS you must have Windows 95 or later



ChiliASP is a technology that runs ASP without Windows OS



InstantASP is another technology that runs ASP without Windows

What is an ASP File?



An ASP file is just the same as an HTML file



An ASP file
can contain text, HTML, XML, and scripts



Scripts in an ASP file are executed on the server



An ASP file has the file extension ".asp"

How Does ASP Differ from HTML?



When a browser requests an HTML file, the server returns the file



When a browser requests an

ASP file, IIS passes the request to the ASP engine. The ASP engine
reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is
returned to the browser as plain HTML


What can ASP do for you?



Dynamically edit, change,
or add any content of a Web page



Respond to user queries or data submitted from HTML forms



Access any data or databases and return the results to a browser



Customize a Web page to make it more useful for individual users



The advantages of using ASP instead

of CGI and Perl, are those of simplicity and speed



Provide security
-

since ASP code cannot be viewed from the browser



Clever ASP programming can minimize the network traffic


Note:

Because ASP scripts are executed on the server, the browser that displays
the ASP file does
not need to support scripting at all!



Apache Tomcat

Apache Tomcat

(or
Jakarta Tomcat

or simply
Tomcat
) is an
ope
n source

servlet container

developed by the
Apache
Software Foundation

(ASF). Tomcat implements the
Java Servlet

and
the
JavaServer Pages

(JSP) spe
cifications from
Sun Microsystems
, and provides a "pure
Java
"
HTTP

web server

environment for
Java

code to run.

Tomcat should not be confused with the
Apache web server
, which is a
C

implementation of an
HTTP web server; these two web servers are not bundled together. Apache Tomcat includes
tools for configuration and management, but can also be co
nfigured by editing
XML

configuration files

Introduction to JSP

JavaServer Pages (JSP) is a technology based on the Java language and enables the development of
dynamic web sites. JSP was developed
by Sun Microsystems to allow server side development. JSP files
are HTML files with special Tags containing Java source code that provide the dynamic content.The
following shows the Typical Web server,different clients connecting via the Internet to a Web
server. In
this example,the Web server is running on Unix and is the very popular Apache Web server




First static web pages were displayed. Typically these were people?s

first experience with making web
pages so consisted of My Home Page sites and company marketing information. Afterwards Perl and C
were languages used on the web server to provide dynamic content. Soon most languages including
Visualbasic,Delphi,C and Jav
a could be used to write applications that provided dynamic content using
data from text files or database requests. These were known as CGI server side applications. ASP was
developed by Microsoft to allow HTML developers to easily provide dynamic content

supported as
standard by Microsoft?s free Web Server,Internet Information Server (IIS). JSP is the equivalent from
Sun Microsystems,a comparison of ASP and JSP will be presented in the following section.

The following diagram shows a web server that supp
orts JSP files. Notice that the web server also is
connected to a database.





JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet engine dynamically
generates the HTML and sends the HTML output to the client?s web browser.

Why use JSP?

JSP is easy to learn and allows developers to quickly produce web sites and applications in an open and
standard way. JSP is based on Java,an object
-
oriented language. JSP offers a robust platform for web
development.

Main reasons to use JSP
:

Multi platform

Component reuse by using Javabeans and EJB.

Advantages of Java.

You can take one JSP file and move it to another platform,web server or JSP Servlet engine.




This means you are never locked into one vendor or platform.

HTML and gra
phics displayed on the web browser are classed as the presentation layer. The Java code
(JSP) on the server is classed as the implementation.

By having a separation of presentation and implementation,web designers work only on the presentation
and Java de
velopers concentrate on implementing the application.

Steps required for a JSP request:

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.

The JSP request gets se
nt to the Web server.

The Web server recognises that the file required is special (.jsp),therefore passes the JSP file to the JSP
Servlet Engine.

If the JSP file has been called the first time,the JSP file is parsed,otherwise go to step 7.

The next step

is to generate a special Servlet from the JSP file. All the HTML required is converted to
println statements.

The Servlet source code is compiled into a class.

The Servlet is instantiated,calling the init and service methods.

HTML from the Servlet

output is sent via the Internet.

HTML results are displayed on the user's web browser.


JSP architecture



JSPs are built on top of SUN Microsystems' servlet

technology. JSPs are essential an HTML page with
special JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather
than .htm or .html. The JSP engine parses the .jsp and creates a Java servlet source file. It then comp
iles
the source file into a class file,this is done the first time and this why the JSP is probably slower the first
time it is accessed. Any time after this the special compiled servlet is executed and is therefore returns
faster.






JSP Implicit Objects





Implicit objects in jsp are the objects that are created by the container automatically and the
container makes them available to the developers, the developer do not need to create them
explicitly. Since these objects

are created automatically by the container and are accessed using
standard variables; hence, they are called implicit objects. The implicit objects are parsed by the
container and inserted into the generated servlet code. They are available only within th
e
jspService method and not in any declaration. Implicit objects are used for different purposes.
Our own methods (user defined methods) can't access them as they are local to the service
method and are created at the conversion time of a jsp into a servle
t. But we can pass them to our
own method if we wish to use them locally in those functions.


There are nine implicit objects. Here is the list of all the implicit objects:

Object

Class

application

javax.servlet.ServletContext

config

javax.servlet.ServletConfig

exception

java.lang.Throwable

out

javax.servlet.jsp.JspWriter

page

java.lang.Object

PageContext

javax.servlet.jsp.PageContext

request

javax.servlet.ServletRequest

response

javax.servlet.ServletResponse

session

javax.servlet.http.HttpSession



Application:

These objects has an application scope. These objects are available at the
widest context level, that allows to share the same information between the JSP page's
servlet and any Web components with in

the same application.



Config:

These object has a page scope and is an instance of javax.servlet.ServletConfig
class. Config object allows to pass the initialization data to a JSP page's servlet.
Parameters of this objects can be set in the deployment desc
riptor (web.xml) inside the
element <jsp
-
file>. The method getInitParameter() is used to access the initialization
parameters.



Exception:
This object has a page scope and is an instance of java.lang.Throwable class.
This object allows the exception data to

be accessed only by designated JSP "error
pages."



Out:

This object allows us to access the servlet's output stream and has a page scope. Out
object is an instance of javax.servlet.jsp.JspWriter class. It provides the output stream that
enable access to th
e servlet's output stream.



Page:
This object has a page scope and is an instance of the JSP page's servlet class that
processes the current request. Page object represents the current page that is used to call
the methods defined by the translated servlet
class. First type cast the servlet before
accessing any method of the servlet through the page.



Pagecontext:
PageContext has a page scope.

Pagecontext is the context for the JSP page
itself that provides a single API to manage the various scoped attributes
. This API is
extensively used if we are implementing JSP custom tag handlers. PageContext also
provides access to several page attributes like including some static or dynamic resource.



Request:

Request object has a request scope that is used to access th
e HTTP request data,
and also provides a context to associate the request
-
specific data. Request object
implements javax.servlet.ServletRequest interface. It uses the getParameter() method to
access the request parameter. The container passes this object t
o the _jspService()
method.



Response:

This object has a page scope that allows direct access to the
HTTPServletResponse

class object. Response object is an instance of the classes that
implements the javax.servlet.ServletResponse class. Container generates

to this object
and passes to the _jspService() method as a parameter.



Session:

Session object has a session scope that is an instance of
javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to
manage the state contexts. This o
bject persist information across multiple user
connection.

What is Function Tag Library in JSP?

Explanation

JSTL Function Tag Library lists set of functions that can be used with the JSP Expression
Language or EL.

The following table list all the functio
n in JSTL Function Library.

Syntax:



<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"


prefix="fn" %>

Functions Syntax

Description

fn:contains()

Returns true if string contains the substring

fn:containsIgnoreCase()

Returns true if string contains the substring,ignores
case

fn:endsWith()

Returns true if the string ends with a suffix

fn:escapeXml()

Returns strings as it is that have special meaning in
XML,converted to XML character entity code.

fn:indexOf()

Returns index for the first occurence of substring.

fn:join()

Returns strings from array with the given seperator.

fn:length()

Returns the number o
f elements from a array or a
collection,characters from a string.

fn:replace()

Returns a string with the before strings with the
after strings.

fn:split()

Returns an array with element got by separating the
string with the seperator.

fn:startsWith()

Returns true if the string starts with the prefix.

fn:substring()

Returns a string with begin index till the end index.

fn:substringAfter()

Returns the part of the string after the substring.

fn:substringBefore()

Returns the part of th
e string before the substring.

fn:toLowerCase()

Returns the allcharacter of a string in lowercase.

fn:toUppercase()

Returns the allcharacter of a string in uppercase.

fn:trim()

Returns the string removing trailing and leading
whitespaces.



Scriptlets

We have already seen how to embed Java expressions in JSP pages by putting them between the
<%=

and
%>

character sequences.

But it is difficult to do much programming just by putting Java expressions inside HTML.

JSP also allows you to write b
locks of Java code inside the JSP.


You do this by placing
your Java code between
<%

and
%>

characters (just like expressions, but without the
=

sign at
the start of the sequence.)

This block of code is known as a "scriptlet".


By itself, a scriptlet does
n't contribute any
HTML (though it can, as we will see down below.)


A scriptlet contains Java code that is
executed every time the JSP is invoked.



Here is a modified version of our JSP from previous section, adding in a scriptlet.

<HTML>

<BODY>

<%



// This is a scriptlet.


Notice that the "date"



// variable we declare here is available in the



// embedded expression later on.



System.out.println( "Evaluating date now" );



java.util.Date date = new java.util.Date();

%>

Hello!


The time is

now <%= date %>

</BODY>

</HTML>

If you run the above example, you will notice the output from the "
System.out.println
" on the
server log.


This is a convenient way to do simple debugging (some servers also have techniques of
debugging the JSP in the IDE.


See your server's documentation to see if it offers such a technique.)

By itself a scriptlet does not generate HTML.


If a scriptlet wants to generate HTML, it can
use a variable called "
out
".


This variable does not need to be declared.


It is already
p
redefined for scriptlets, along with some other variables.


The following example shows
how the scriptlet can generate HTML output.

<HTML>

<BODY>

<%



// This scriptlet declares and initializes "date"



System.out.println( "Evaluating date now" );



java.util.Date date = new java.util.Date();

%>

Hello!


The time is now

<%



// This scriptlet generates HTML output



out.println( String.valueOf( date ));

%>

</BODY>

</HTML>

Here, instead of using an expression, we are generating the HTML directly by

printing to the "
out
"
variable.


The "
out
" variable is of type
javax.servlet.jsp.JspWriter
.


Another very useful pre
-
defined variable is "
request
".


It is of

type
javax.servlet.http.HttpServletRequest


A "request" in server
-
side processing refers to the transaction between a browser and the
server.


When someone clicks or enters a URL, the browser sends a "request" to the server
for that URL, and shows the data returned.


As a part of this "request", var
ious data is
available, including the file the browser wants from the server, and if the request is coming
from pressing a SUBMIT button, the information the user has entered in the form fields.

The JSP "
request
" variable is used to obtain information fro
m the request as sent by the
browser.


For instance, you can find out the name of the client's host (if available, otherwise
the IP address will be returned.)


Let us modify the code as shown:

<HTML>

<BODY>

<%



// This scriptlet declares and initialize
s "date"



System.out.println( "Evaluating date now" );



java.util.Date date = new java.util.Date();

%>

Hello!


The time is now

<%



out.println( date );



out.println( "<BR>Your machine's address is " );



out.println( request.getRemoteHost());

%>

</BODY>

</HTML>

A similar variable is "response".


This can be used to affect the response being sent to the browser.


For instance, you can call
response.sendRedirect( anotherUrl );
to send a response to
the browser that it should load a different URL
.


This response will actualy go all the way to the
browser.


The browser will then send a different request, to "
anotherUrl
".


This is a little
different from some other JSP mechanisms we will come across, for including another page or
forwarding the brow
ser to another page.

JSP Sessions

On a typical web site, a visitor might visit several pages and perform several interactions.

If you are programming the site, it is very helpful to be able to associate some data with
each visitor.


For this purpose, "
session
"s can be used in JSP.

A session is an object associated with a visitor.


Data can be put in the session and retrieved
from it, much like a Hashtable.


A different set of data is kept for each visitor to the site.

Here is a set of pages that put a

user's name in the session, and display it elsewhere.


Try out
installing and using these.

First we have a form, let us call it GetName.html

<HTML>

<BODY>

<FORM METHOD=POST ACTION="SaveName.jsp">

What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>

<P><INPUT TYPE=SUBMIT>

</FORM>

</BODY>

</HTML>

The target of the form is "SaveName.jsp", which saves the user's name in the session.


Note
the variable


"
session
".


This is another variable that is normally made available in JSPs,
just like
out

and
reques
t

variables.


(In the @page directive, you can indicate that you do
not need sessions, in which case the "session" variable will not be made available.)

<%



String name = request.getParameter( "username" );



session.setAttribute( "theName", name );

%>

<HTML>

<BODY>

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

</BODY>

</HTML>

The SaveName.jsp saves the user's name in the session, and puts a link to another page,
NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.

<HTML>

<BODY>

Hello, <%=
session.getAttribute( "theName" ) %>

</BODY>

</HTML>

If you bring up two different browsers (not different windows of the same browser), or run
two browsers from two different machines, you can put one name in one browser and
another name in another browse
r, and both names will be kept track of.

The session is kept around until a timeout period.


Then it is assumed the user is no longer
visiting the site, and the session is discarded.

Beans and Form processing

Forms are a very common method of interactions in web sites.


JSP makes forms processing
specially easy.

The standard way of handling forms in JSP is to define a "bean".


This is not a full Java
bean.


You just need to define a class that has a field corr
esponding to each field in the
form.


The class fields must have "setters" that match the names of the form fields.


For
instance, let us modify our
GetName.html

to also collect email address and age.

The new version of
GetName.html

is

<HTML>

<BODY>

<FOR
M 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>

To collect this data, we define a Java class with fields "
username
", "
email
" and "
age
" and we
provide setter methods "
setUsername
", "
setEmail
" and "
setAge
", as shown.


A "setter"
method is just a method that starts with "
set
" followed by the name

of the field.


The first
character of the field name is upper
-
cased.


So if the field is "
email
", its "
setter
" method will be
"
setEmail
".


Getter methods are defined similarly, with "get" instead of "set".


Note that the
setters


(and getters) must be pu
blic.


package user;


public class UserData {



String username;



String email;



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

}

The method names must be exactly as sh
own.


Once you have defined the class, compile it and
make sure it is available in the web
-
server's classpath.


The server may also define special folders
where you can place bean classes, e.g. with Blazix you can place them in the "
classes
" folder.


If
yo
u have to change the classpath, the web
-
server would need to be stopped and restarted if it is
already running.


(If you are not familiar with setting/changing classpath, see
notes on changing
classpath
.)

Note that we are using the package name
user
, therefore the file
UserData.class

must be
placed in a folder named
user

under the classpath entry.

Now let us change "
SaveName.jsp
" to use a bean to collect the data.

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

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


<HTML>

<BODY>

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

</BODY>

</HTML>

All we need to do now is to add the
jsp:useBean

tag and the
jsp:setProperty

tag!


The
useBean tag will look for
an instance of the "
user.UserData
" in the session.


If the instance is
already there, it will update the old instance.


Otherwise, it will create a new instance of
user.UserData

(the instance of the
user.UserData

is called a bean), and put it in the sessio
n.

The setProperty tag will automatically collect the input data, match names against the bean
method names, and place the data in the bean!



Let us modify
NextPage.jsp

to retrieve the data from bean..

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


<HTML>

<BODY>

You entered<BR>

Name: <%= user.getUsername() %><BR>

Email: <%= user.getEmail() %><BR>

Age: <%= user.getAge() %><BR>

</BODY>

</HTML>

Notice that the same useBean tag is repeated.


The bean is available as the variable named "
user
"

of class "
user.UserData
".


The data entered by the user is all collected in the bean.

We do not actually need the "
SaveName.jsp
", the target of
GetName.html

could have been
NextPage.jsp
, and the data would still be available the same way as long as we ad
ded a
jsp:setProperty

tag.


But in the next tutorial, we will actually use
SaveName.jsp

as an
error handler that automatically forwards the request to
NextPage.jsp
, or asks the user to
correct the erroneous data.

Exercise:


1)


Write a JSP/HTML set that a
llows a user to enter the name of a system
property, and then displays the value returned by
System.getProperty

for that property
name (handle errors appripriately.)


2 )


G o b a c k t o t h e e x e r c i s e s w h e r e y o u ma n u a l l y
mo d i f i e d b o o l e a n v a r i a b l e s.


I n s t e a d o f
a b o o l e a n v a r i a b l e, ma k e t h e s e c o me f r o m a
H I D D E N f o r m f i e l d t h a t c a n b e s e t t o t r u e o r f a l s e.

Ta g l i b r a r i e s

J S P 1.1 i n t r o d u c e s a m e t h o d o f e x t e n d i n g J S P t a g s, c a l l e d "t a g l i b r a r i e s".


T h e s e l i b r a r i e s a l l o w
a d d i t i o n o f t a g s s i m i l a r t o
jsp:include

or
jsp:forward
, but with different prefixes other than
jsp:

and with additional features.

To introduce you to tag libraries, in this tutorial we use the Blazix tag library as an
example.


This tag library comes bundled with the
Blazix server
. If you are not using the
Blazix Server, you may just want to review the material to get familiar with the syntax, and
continue on to the next page.

Each tag
-
library will have its own tag
-
library specific
documentation.


In order to use the
tag library, you use the "taglib" directive to specify where your tag library's "description"
resides.


For the Blazix tag library,


the (recommended) directive is as follows

<%@ taglib prefix="blx" uri="/blx.tld" %>

Th
e "uri" specifies where to find the tag library description.


The "prefix" is unique for the tag
library.


This directive is saying that we will be using the tags in this library by starting them with
blx:


The Blazix tag library provides a blx:getPropert
y tag.


This tag can be used to allow the user
to edit form data.


In our GetName.jsp file, we will now add a jsp:useBean and place the
form inside blx:getProperty.

The new GetName.jsp is

<%@ taglib prefix="blx" uri="/blx.tld" %>

<jsp:useBean id="user" c
lass="user.UserData" scope="session"/>

<HTML>

<BODY>

<blx:getProperty name="user" property="*">

<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 S
IZE=20><BR>

What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>

<P><INPUT TYPE=SUBMIT>

</FORM>

</blx:getProperty>

</BODY>

</HTML>

Note that the blx:getProperty doesn't end with /> but is instead terminated by a separate
</blx:getProperty>

line.


This puts all the form input fields inside the blx:getProperty so they can be
appropriately modified by the tag library.

Try putting a link to GetName.jsp from the NextPage.jsp, and you will see that the bean's
data shows up automatically in the i
nput fields.

The user can now edit the data.

We still have a couple of problems.


The user cannot clear out the name field.


Moreover, if
the user enters a bad item in the "age" field, something which is not a valid integer, a Java
exception occurs.

We
will use another tag from the Blazix tag library to take care of this.


Blazix offers a
blx:setProperty tag that can be used to take care of these problems.


blx:setProperty

allows us to define an exception handler method.


If an exception occurs, we can c
ollect an
error message for the user and continue processing.

Following is a version of SaveName.jsp that processes any errors, and either shows the user
GetName.jsp again to user can enter the data correctly, or automatically forwards to
NextPage.jsp.

<
%@ taglib prefix="blx" uri="/blx.tld" %>

<%!



boolean haveError;



StringBuffer errors;




public void errorHandler( String field,



String value,



Exception ex )



{



haveError = tru
e;



if ( errors == null )



errors = new StringBuffer();



else



errors.append( "<P>" );



errors.append( "<P>Value for field
\
"" +



field + "
\
" is invalid." );



if ( ex instanceof
java.lang.NumberFormatException )



errors.append( " The value must be a number." );



}

%>

<%



// Variables must be initialized outside declaration!



haveError = false;



errors = null;

%>

<HTML>

<BODY>

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

<blx:setProperty name="user"



property="*"




onError="errorHandler"/>


<%



if ( haveError ) {



out.println( errors.toString());



pageContext.include( "GetName.jsp" );



} else



pageContext.fo
rward( "NextPage.jsp" );

%>

</BODY>

</HTML>

Note that
haveError

and
errors

must be re
-
initialized each time, therefore they are being
initialized outside of the declaration.

[Also notice the use of
pageContext.include

and
pageContext.forward
.


These are like
jsp:include

and
jsp:forward
, but are more convenient to use from within Java blocks.


p
ageContext

is another pre
-
defined variable that makes it easy to do certain operations
from within Java blocks.]

Here, if an error occurs during the
processing of
blx:setProperty
, we display the error
and then include the
GetName.jsp

again so user can correct the error.


If no errors occur, we
automatically forward the user to
NextPage.jsp
.

There is still a problem with the forms, the "age" shows up a
s zero initially rather than being
empty.


This can be fixed by adding "
emptyInt=0"

to both the
blx:getProperty

and
blx:setProperty

tags (bean fields should be initialized to 0.)


It happens that "0" is not a
valid value for age, so we can use "0" to mark empty strings.


If "0" were a valid value for
age, we could have added "
emptyInt=
-
1
" (and made sure to initialize the bean fields
to
-
1.)

Another small problem is that the "<HTML>" tag gets doubled if there is an error and we
end up including "GetName.jsp".


A more elegant solution is to remove the out.println, and
pass back the error as shown

<%



if ( haveError ) {



requ
est.setAttribute( "errors",



errors.toString());



pageContext.forward( "GetName.jsp" );



} else



pageContext.forward( "NextPage.jsp" );

%>

We can then do a "
request.getAttribute
" in the
GetName.jsp
, and if the returned valu
e
is non
-
null, display the error.


Techniques for form editing

A tag library such as the one that comes with the
Blazix server
, may not be available in your
environment.


How can you allow s
imilar features without using a tag library?

It is a little tedious, but it can be done.


Basically, you must edit each HTML tag yourself,
and put in a default value.


The following examples shows how we modify GetName.jsp to
provide features similar to
b
lx:getProperty

but with manual HTML tag editing:

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

<HTML>

<BODY>

<FORM METHOD=POST ACTION="SaveName.jsp">

What's your name? <INPUT TYPE=TEXT NAME=username



SIZE=20 VALUE="<%=
user.getUsername() %>"><BR>

What's your e
-
mail address? <INPUT TYPE=TEXT



NAME=email SIZE=20



VALUE="<%= user.getEmail() %>"><BR>

What's your age? <INPUT TYPE=TEXT NAME=age



SIZE=4 VALUE=<%= user.getAge() %>>

<P><INPUT TYPE=SUBMIT>

</FORM>

</BODY>

</HTML>

As you can see, this simply involves adding a "VALUE" field in the INPUT tags, and initializing the
field with an expression!

To handle exceptions during input processing, a simple approach is to use "
String
" fields
in the bean, an
d do the conversion to the target datatype yourself.


This will allow you to
handle exceptions.



Protecting your website with a login page

Some sites require that all users log
-
in using a username and password, before being able to
visit any page.

This can be done using JSP sessions or servlets, and in fact this was a common technique
for a while.


But starting with a new release of Servlets specifications (2.2) from Sun, this
feature is now very simple to implement.



I t i s n o l o n g e r n e c e s s a r y t o
u s e J S P t e c h n i q u e s t o p r o v i d e l o g i n/p a s s w o r d p r o t e c t i o n, b u t i t
i s s t i l l a v e r y c o mmo n r e q u i r e me n t o f w e b
-
s i t e s, t h e r e f o r e a b r i e f o v e r v i e w i s p r o v i d e d h e r e.

T o p a s s w o r d
-
p r o t e c t y o u r s i t e, y o u j u s t n e e d t o d e s i g n a l o g i n p a g e.


T h i s p a g e c a n b e a s
s i mp l e
o r c o mp l i c a t e d a s y o u n e e d i t t o b e.


I t mu s t c o n t a i n a
<FORM>

tag, with the
METHOD

set to
POST

and the
ACTION

set to "
j_security_check
".

<FORM METHOD=POST ACTION=j_security_check>


The target
j_security_check

is provided by the application server, and do
es not need to
be coded.

The form must contain two
<INPUT>

fields, named
j_username

and
j_password

respectively for the username and password.


Typically, the username field will be a
TEXT

input field, and the password field will be a
PASSWORD

input field
.

After this, you must tell your application server to password protect your pages using the
login page you have provided.


The details will vary from server to server, but a good
implementation will provide you hooks that you can use, for example, to mat
ch usernames
and passwords against a database.


(E.g., in Blazix you can supply an implementation of the
interface
desisoft.deploy.AuthCheck

to check usernames and passwords against a
database or other sources.)



Protecting your website with a login page

Some sites require that all users log
-
in using a username and password, before being able to
visit any page.

This can be done using JSP sessions or servlets, and in fact this was a common technique
for a while.


But starting with a new release of Servlet
s specifications (2.2) from Sun, this
feature is now very simple to implement.



I t i s n o l o n g e r n e c e s s a r y t o u s e J S P t e c h n i q u e s t o p r o v i d e l o g i n/p a s s w o r d p r o t e c t i o n, b u t i t
i s s t i l l a v e r y c o mmo n r e q u i r e me n t o f w e b
-
s i t e s, t h e r e f o r e a b r i e f o v e r v i e w i s p r
o v i d e d h e r e.

T o p a s s w o r d
-
p r o t e c t y o u r s i t e, y o u j u s t n e e d t o d e s i g n a l o g i n p a g e.


T h i s p a g e c a n b e a s
s i mp l e o r c o mp l i c a t e d a s y o u n e e d i t t o b e.


I t mu s t c o n t a i n a
<FORM>

tag, with the
METHOD

set to
POST

and the
ACTION

set to "
j_security_check
".

<FORM
METHOD=POST ACTION=j_security_check>


The target
j_security_check

is provided by the application server, and does not need to
be coded.

The form must contain two
<INPUT>

fields, named
j_username

and
j_password

respectively for the username and password.


Typically, the username field will be a
TEXT

input field, and the password field will be a
PASSWORD

input field.

After this, you must tell your application server to password protect your pages using the
login page you have provided.


The details will var
y from server to server, but a good
implementation will provide you hooks that you can use, for example, to match usernames
and passwords against a database.


(E.g., in Blazix you can supply an implementation of the
interface
desisoft.deploy.AuthCheck

to c
heck usernames and passwords against a
database or other sources.)



Getting Familiar with your JSP server

If you do not have a JSP capable web
-
server or
application server
, the first step is to download
one.


There are many such servers available, most of which can be downloaded for free evaluation
and/or development.


Some of them are:

Blazix

from Desiderata Soft
ware (
1.5 Megabytes, JSP, Servlets and EJBs
)

TomCat

from Apache (
Approx 6 Megabytes
)

WebLogic

from BEA Systems (
Approx 40 Megabytes, JSP, Servlets and EJ
Bs
)

WebSphere

from IBM (
Approx 100 Megabytes, JSP, Servlets and EJBs
)

To take the best advantage of this tutorial, it recommended that all the material should be
tried out with a real ser
ver.



Once you have a JSP capable web
-
server or applicat io n server, you need t o know t he
followi ng infor mat i o n about it:



Whe r e t o pl ace t he f i l e s



How t o acce s s t he f i l e s f r om your br ows e r ( wi t h an
http:

prefix, not as
file:
)

You should be able to create

a simple file, such as

<HTML>

<BODY>

Hello, world

</BODY>

</HTML>

know where to place this file and how to see it in your browser with an
http://

prefix.

Since this step is different for each web
-
server, you would need to see the web
-
server
documentatio
n to find out how this is done.


Once you have completed this step, proceed to
the next tutorial.

Your first JSP

JSP simply puts Java inside HTML pages.


You can take any existing HTML page and change its
extension to ".jsp
" instead of ".html".


In fact, this is the perfect exercise for your first JSP.

Take the HTML file you used in the
previous exercise
.


Change its extension from ".html"
to ".jsp".


Now load the new fi
le, with the ".jsp" extension, in your browser.

You will see the same output, but it will take longer!


But only the first time.


If you reload
it again, it will load normally.

What is happening behind the scenes is that your JSP is being turned into a J
ava file,
compiled and loaded.


This compilation only happens once, so after the first load, the file
doesn't take long to load anymore.


(But everytime you change the JSP file, it will be re
-
compiled again.)

Of course, it is not very useful to just write

HTML pages with a .jsp extension!


We now
proceed to see what makes JSP so useful.

Adding dynamic content via expressions

As we saw in the previous section, any HTML file can be turned into a JSP file by changing
its extension to .jsp.


Of course, what
makes JSP useful is the ability to embed Java.


Put the
following text in a file with .jsp extension (let us call it
hello.jsp
), place it in your JSP
directory, and view it in a browser.



<HTML>

<BODY>

Hello!


The time is now <%= new java.util.Date() %>

<
/BODY>

</HTML>

Notice that each time you reload the page in the browser, it comes up with the current time.

The character sequences
<%=

and
%>

enclose Java expressions, which are evaluated at run
time.

This is what makes it possible to use JSP to generate dyamic HTML pages that change in
response to user actions or vary from user to user.

Exercise:


Write a JSP to output the values returned by
System.getProperty

for various
system properties such as
jav
a.version, java.home, os.name, user.name,
user.home, user.dir

etc.