Java Server Pages

clangpotatoSoftware and s/w Development

Oct 28, 2013 (3 years and 10 months ago)

71 views

Java Server Pages

JSPs?
<
html
>

<
body
>


Hello World!
<
br
/>


It's now:
<%= new java.util.Date() %>

</
body
>

</
html
>

What are JSPs?


JSP works on top of a servlet infrastructure.


At runtime JSP tags are translated into Servlet code



JSPs: you can put Java into web pages


Similar to Microsoft's Active Server Pages (ASP)


JSPs are used to separate code (Java) from
presentation (HTML)


Support the use of JavaBeans


A JavaServer Pages file has the extension
.jsp

JSPs to Servlets

MyJSP.jsp

MyJSP_jsp.java

MyJSP_jsp.class

MyJSP_jsp
Servlet
Object
Servlet
code
JSP
Page
Servlet
class
How do JSPs Compile?
Web
Browser
JSP Page
Generated Servlet
Compiled Servlet
1. Request
2. compiled
3. loaded
4. Response
Transforming JSP into Servlets...


Servlet provider parses JSP file


Strips out java code, creates valid .java file (a servlet)


Full class name, imports, etc.


Compiles (javac) .java file


To produce .class file


Executes .class file


Which reads in original .jsp file, writes HTML and java output
to browser


Generated .java and .class file live in servlets
\pagecompile directory


Timestamp kept inside generated .java file


Only recreated and recompiled if .jsp file changes
JSP Lifecycle

JSP or Servlets?


The Java 2 Enterprise Edition includes a
set of design guidelines (J2EE Blueprints)
that provide recommendations on when
to use JSP and servlets.


Use
JSP
for dynamic page presentation.


Use
Servlets
for specialized support
services such as database connections and
authentication.
JSP Scripting Elements

JSP Expression:


<%=

%>
JSP Scriptlet:


<%


%>
JSP Declarations:

<%!


%>
JSP Directive:


<%@

%>

JSP: Expressions

<html>
<body>
<p>
<%= Integer.toString( 5 * 5 ) %>
</p>
</body>
</html>

<html>
<body>
<p>25</p>
</body>
</html>

JSP expressions insert values directly into servlet output:



<%= Integer.toString(5*5) %>

à
out.println(
Integer.toString(5*5 )
);

General form:
<%=

Java Expression

%>
JSP: Scriplets

Data.jsp
<HTML>
<BODY>
<%
System.out.println( "Evaluating date now");
java.util.Date
date
= new java.util.Date();
%>


Hello! <br>
The time is now
<%=
date
%>

</BODY>
</HTML>

JSP: Scriptlets


Scriptlets allow you to embed code fragments
within <% .... %>.


You can have multiple lines of code, loops,…

<%
String host = request.getHostName();
if(host.equals(
l
eden.dei.uc.pt
z
))
out.println(
l
Hello user from Eden!
z
);
else
out.println(
l
Hello stranger!
z
);
%>
JSP: Pre-defined Variables


request


the HTTPServletRequest


request.getParameter(
l
parameterName
z
)



response


HTTPServletResponse


session


HTTPSession


session.setAttribute(
l
username
z
, username)


session.getAttribute(
l
username
z
)



out


out.println(
l
string
z
);


application



ServletContext

JSP: using out

<HTML>
<BODY>
<%
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>
Scriptlets mixed with HTML

<HTML>
<BODY>

<TABLE BORDER=2>
<%
for (int i=0; i<10; i++) {
%>
<TR>
<TD>Number</TD> <TD><%= i+1 %></TD>
</TR>
<%
}
%>
</TABLE>

</BODY>
</HTML>
JSP: using request
< html >
< body >
Hello,
<% out.println(
request.getParameter
("name")); %>
< /body >
< /html >

Invoke with:
http://host/scriptlet.jsp?name=Carlos

Generates:
Hello, Carlos
session: methods
Method

Description

getId()

Returns the session ID.

getCreationTime()

Returns the time at which the session was
created

isNew()

Returns
true
if user
`
s browser has not yet
confirmed the session id.

invalidate()

Discards the session, releasing any objects
stored as attributes.

getAttribute(String key)

Returns an attribute that is stored in the session.

setAttribute(String key,
String value)

Stores an attribute in the sessions.

JSP: Declarations


Declarations are used to define methods
and variables in the scripting language
used by the page.


Declarations do not create any output to
the current out stream.


Initialized when JSP page is initialized
and
available to other declarations, scriptlets
and expressions.
eg.
<%!
Declaration(s)
%>
JSP: Declarations
- variable

<%! int hitCount = 0; %>

- method
<%!
public String getFirstName(String fullName)
{
StringTokenizer st
= new StringTokenizer(fullName);
if (st.hasNext())
return st.next();
else
return fullName;
}
%>
JSP: Declarations

<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%!
private Date genTime = new Date();


public Date getDate()
{



return genTime;
}
%>

Hello! The page was generated at <%=
getDate()
%>
</BODY>
</HTML>
Data2.jsp
JSP Directives


The common tag form is


<%@ directive attribute=
l
value
z
%>


Three types


page


include


taglib

JSP Directives


page


can import classes, set content-type etc.


<%@ page import=
l
java.util.*
z
%>


<%@ page contentType=
l
text/plain
z
%>


include


lets you include page elements,
preformatted content etc.


<%@ include file=
l
disclaimer.html
z
%>


taglib



allows you to define custom tags
JSP Directive: page

<%@ page import="java.util.*" %>

<HTML>
<BODY>
<%

System.out.println( "Evaluating date now" );
Date date = new Date();
%>
Hello! The time is now
<%= date %>
</BODY>
</HTML>
Data3.jsp

JSP Directive: include

<HTML>
<BODY>
Going to include index2.html...<BR>
<%@ include file=
l
index2.html
z
%>
</BODY>
</HTML>
jsp

Index2.html

Session Management



You can use the same approaches as in
Servlets


URL Rewriting


Cookies


Session Objects

Store.jsp

<html><head><title>The Store</title></head><body>

<%

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

String passwd = request.getParameter("password");



if (!passwd.equals("isctem"))


response.sendRedirect("/loja2/InvalidLogin.html");

else

{


session.setAttribute("username", username);

}
%>

<h1>Olá
<%= username %>
, bem vindo à loja!</h1>
<a href="/loja2/Supermarket.jsp">Secção de supermercado</a><br>
<a href="/loja2/Electronics.jsp">Secção de carros</a>

</body></html>
The “username” attribute is
stored in the current session

<html><head><title>The Store</title></head><body>

<%

String username = (String) session.getAttribute("username");
%>

<h1>Olá <%= username %>.<br>
Está neste momento no supermercado.</h1>

</body></html>

<html><head><title>The Store</title></head><body>

<%

String username = (String) session.getAttribute("username");
%>

<h1>Olá <%= username %>.<br>
Está neste momento na loja de electrónica.</h1>

</body></html>

Supermarket.jsp

Electronics.jsp

<jsp:forward page=“...” >

<%
if
(
username.equals
(“
admin
”)) { %>

<
jsp:forward

page
=“
outroJSP.jsp
” >
<% } %>


<%
if
(
username.equals
(“
admin
”)) {

pageContext.forward
(“
outroJSP.jsp
”);
%>


Example <jsp:forward >

<html><body>
Welcome!
<% if(request.getParameter(“username”) == null){ %>

<jsp:forward page=“Login_invalido.jsp” />
<% } %>
Hello <%= request.getParameter(“username”) %>
</body></html>

<html><body>
Sorry, you have to logon again!
<form action=“Hello.jsp” method=“POST” >
Nome: <input name=“username” type=“text” >
<input name=“Submit” type=“submit”>
</form>
</body></html>
Welcome.jsp

Login_invalido.jsp

JSP: Standard Actions


Standard Actions allow you to instantiate
objects and communicate with server-side
resources.


Much of this could be done with code in
Scriptlets, however using standard actions helps
separate logic and presentation.


looser coupling


less dependencies


promotes re-usability


This relies on the use of
JavaBeans
as
JSP
`
s
component model

JSP + Java Beans
JSPs with Beans

Enterprise
Systems
(legacy,
DBMS,
etc.)
Browser
JSP
JavaBean
Servlet Container
request

response

JSP & JavaBeans


For simple usage in JSP pages there are
couple of minimal requirements:


A bean class must have a default
constructor.


A bean class should have no public
instance variables


Class properties should be accessed via
getXXXX()
and
setXXXX()
methods.
JSP & JavaBeans


Using beans in a JSP page:
<jsp:useBean id=
l
myBook
z
class=
l
isctem.Book
z
>




creates a bean called
book
of type
isctem.Book
.


first looks for a reference to an existing variable and only
creates if none in scope only creates it if this bean is not
active



Roughly equivalent to:


isctem.Book myBook = new isctem.Book();
jsp:
useBean



useBean:


<jsp:useBean id="myBook" class="isctem.Book" />


is equivalent to the scriptlet:

<% isctem.Book myBook = new isctem.Book(); %>


If that class has a method() we can use it:

<%


myBook.setName(“Distributed Systems”);

%>

JSP:
get/set Properties


get properties:

<jsp:getProperty name=
l
myBook
z
property=
l
Name
z
/>



set properties:

<jsp:setProperty name=
l
myBook
z
property=
l
Name
z



value=
l
Distributed Systems
z
/>
Allow access to bean properties (i.e. calls to getXXX() and
setXXX() methods) without explicit Java programming.
Example:
<jsp:getProperty name=
l
myBook
z
property=
l
Name
z
/>
is the same as
<%= myBook.getName() %>

Using Beans with Forms
<jsp:useBean id=
l
user
z
class=
l
isctem.User
z
/>
<jsp:setProperty name=
l
user" property="*" />

The person trying to login is:
<%= user.getUserName() %>
<html><body>
<form action=“
DoLogin.jsp
”>
Username: <input type=“text” name=“
userName
”/>
Password: <input type=“password” name=“
password
”/>
<input type=“submit”>
</form>
</body></html>

DoLogin.jsp

Associate all properties



Use "*" for the value of the property attribute
of jsp:setProperty to indicate that Value should
come from
request parameter whose name
matches property name
.


<jsp:useBean id=
l
sale
z
class=
l
store.Products" />

<jsp:setProperty name=
l
sale
z
property="*" />
Another Example
HTML Form: GetInfo.html

<HTML>
<BODY>

<FORM METHOD=POST ACTION=
l
SaveUser.jsp">

Name: <INPUT TYPE=TEXT NAME=
z
username
z
SIZE=20>

<BR/>
Email: <INPUT TYPE=TEXT NAME=
l
email
z
SIZE=20>

<BR/>
Age:

<INPUT TYPE=TEXT NAME=
l
age
z
SIZE=10>


<BR/>

<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
/
jsps
/
regjsp
/
index.jsp

Java Bean: UserData.java

package isctem;

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

getAget
() { return age; }
}

JSP: SaveUser.jsp

<jsp:useBean id="user" class=
l
isctem.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>

<HTML>
<BODY>
<H1> Thank you for submitting this user: </H1>


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

<br/>

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


<br/>

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


<br/>

<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
JSP: NextPage.jsp

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


<HTML>
<BODY>

<H1>Still here:</H1><BR>

Name: <%= user.getUsername() %> <BR>
Email: <%= user.getEmail() %> <BR>
Age: <%= user.getAge() %> <BR>

</BODY>
</HTML>
Sharing Beans

<jsp:useBean id="user" class=
l
isctem.UserData"
scope="
session
"/>
<jsp:useBean id="user" class=" isctem.UserData "
scope=
l
request
z

<jsp:useBean id="user" class=" isctem.UserData "
scope=
l
application
"/>
<jsp:useBean id="user" class=" isctem.UserData "
scope=
l
page
"/>

Scope: “page”



The bean is
instantiated just for the
current page
. The bean is automatically
destroyed after the JSP page looses its
scope (move to another page).


Simultaneous accesses to the same page
correspond to different beans
Scope: “request”



Similar to page but the
bean is available
in other pages that are included or
forwarded from the first one
.


pageContex.include
()


pageContex.forward
()

Scope: “session”



The most useful mode:
the bean is
available throughout the entire session


The bean in put on the user
`
s
session

object


Different users accessing the same page
see different beans
Scope: “application”



The is only
one bean for the whole
application


Different
users accessing the same page see
the same bean