Java Server Pages

glueblacksmithInternet and Web Development

Nov 13, 2013 (3 years and 6 months ago)

111 views

1
Java Server Pages
Sistemas Distribuídos, 2004-2005
Sistemas Informáticos I, 2005-2006
What are JSPs?
• JSP works on top of a servlet infrastructure.
• At runtime JSP tags are translated into Servlet code
• JSPs make it possible to imbed Java right into web pages
– Similar to Microsoft's Active Server Pages (ASP)
• JSPs are used to separate code (Java) from presentation (HTML)
• Contains a combination of:
– HTML/XML
– Java
– <SERVLET> tags
– JSP-specific tags
• Support the use of JavaBeans
• A JavaServer Pages file has the extension .jsp
JSPs vs ASPs vs PHP
 
  










 


!"
#$%"
#&%
 

'%%'(
%'
%





JSP or Servlets?
– Use
JSP
for dynamic page presentation.
– Use
Servlets
for specialised support services such as
database connections and authentication.
2
Compilação dos JSPs
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 Scripting Elements
• JSP scripting elements allow you to
insert code into the servlet that is
generated by the JSP page.
) *%

 +,-.
) %+,-
) 
+,-/
) $+,-0
3
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.
General form:
<%=
Java Expression
%>
JSP: Scriplets
<HTML>
<BODY>
<% // This is a scriptlet.
System.out.println( "Evaluating date now");
java.util.Date
date
= new java.util.Date(); %>
Hello!The time is now
<%=
date
%>
</BODY>
</HTML>
Data.jsp
Scriptlets allow you to embed code fragments within <% .... %>.
You can have multiple lines of code, loops,…
JSP: Pre-defined Variables
– request
• the HTTPServletRequest
• request.getParameter(“parameterName”)
– response
• HTTPServletResponse
– session
• HTTPSession
• session.setAttribute("username", username)
• session.getAttribute(“username”)
– out
• out.println(“string”);
JSP: using out
<html>
<body>
Hello,
<%
out.println(" World!");
%>
</body>
</html>
4
JSP: using request
scriptlet.jsp:
< html > < body >
Hello,
<% out.println(
request.getParameter
("name")); %>
< /body > < /html >
Invoke with:
http://host/scriptlet.jsp?name=World
Generates:
Hello, World
session: methods
Stores an attribute in the sessions.setAttribute(String key,
String value)
Returns an attribute that is stored in the session.getAttribute(String key)
Discards the session, releasing any objects
stored as attributes.
invalidate()
Returns true if user’s browser has not yet
confirmed the session id.
isNew()
Returns the time at which the session was
created
getCreationTime()
Returns the session ID.
getId()
DescriptionMethod
JSP: Declarations
<%@ page import="java.util.*" %>
<HTML>
<BODY>
<%!
Date theDate = new Date();
Date getDate(){
System.out.println( "In getDate() method");
return theDate;
}
%>
Hello!The time is now
<%=
getDate()
%>
</BODY>
</HTML>
Data2.jsp
JSP: Declarations
• Declarations are used to define methods and
variables in the scripting language used by the
page.
• Initialized when JSP page is initialised and
available to other declarations, scriptlets and
expressions.
eg.
<%! Declaration(s) %>
5
JSP: Declarations
* variable
<%! int hitCount = 0; %>
* method
<%!
public String getFirstName(String fullName){
return fullName.subString(0, 3)}
%>
JSP Directives
• Directives are messages for the JSP
engine.
• The common tag form is
– <%@ directive attribute=“value” %>
• Three types
– page
– include
– taglib
JSP Directives
• page
– can import classes, set content-type etc.
– <%@ page import=“java.util.*” %>
– <%@ page contentType=“text/plain” %>
• include
– lets you include page elements,
preformatted content etc.
– <%@ include file=“disclaimer.html” %>
• 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
6
JSP Directive: include
<HTML>
<BODY>
Going to include index2.html...<BR>
<%@ include file=“index2.html” %>
</BODY>
</HTML>
JSP Pages + java code...
A.Servlets + JSPs
B.JSPs + Java Beans
Simple Servlet/JSP Example
Web Browser
Client
Web Server
WebSphere Application Server
1
CallJSP
Servlet
outputjsp
JSP
5
Output HTML
2
DataBean
setValue1
value1
getValue1
Data
3
4
DataBean class
package
nservlets;
public class
DataBean {
String property1 =
null
;
public
String getValue1() {
return
property1;
}
public void
setValue1(String value1) {
property1 = value1;}
}
7
Servlets + JSP: servlet
public void
doPost(HttpServletRequest req, HttpServletResponse resp)
throws
ServletException, IOException {
DataBean dataBean =
new
DataBean();
//Create an instance of DataBean
if
(req.getParameter(
"value"
) ==
null
)
// No parameter, so set a default value
dataBean.setValue1(
"Something Important"
);
else
dataBean.setValue1(req.getParameter(
"value"
));
req.setAttribute(
"dataBean"
, dataBean);
RequestDispatcher rd =
getServletContext().getRequestDispatcher(
"/outputJSP.jsp"
);
rd.forward(req, resp);
}
Servlets + JSP: jsp page
<
HTML
>
<
HEAD
><
TITLE
>
Simple JSP with Bean
</
TITLE
></
HEAD
>
<
BODY
>
<
P
><
BR
>
<
BR
>
<
BR
>
<
IMG
border
=
"0"
src
=
"as400.gif"
width
=
"120"
height
=
"120"
>
</
P
>
<
CENTER
>
<%
nservlets.DataBean myDataBean = (nservlets.DataBean)
request.getAttribute(
"dataBean"
);
out.println(
"The value of the parameter is "
+
myDataBean.getValue1());
%>
</
CENTER
>
</
BODY
>
</
HTML
>
Exemplo:
Servlet access to Database
if
(parameter.toUpperCase().equals(
"*ALL"
)) {
rec = st.executeQuery(
"SELECT * FROM Administrator.EMPLOYEE"
);
}
else
{
rec =st.executeQuery(
"SELECT * FROM Administrator.EMPLOYEE where
EMPNO = "
+
"'"
+ parameter +
"'"
);
}
req.setAttribute(
"resultSet"
, rec);
RequestDispatcher rd =
getServletContext().getRequestDispatcher(
"/outputJSP2.jsp"
);
rd.forward(req, resp);
st.close();
conn.close();
Exemplo: JSP Page
<
TITLE
>
outputJSP2.jsp
</
TITLE
>
</
HEAD
>
<
BODY
>
<
P
><
IMG
border
=
"0"
src
=
"as400.gif"
width
=
"120"
height
=
"120"
></
P
>
<
P
></
P
>
<
CENTER
>
<
TABLE
BORDER
>
<
P
>
<
CENTER
><
B
><
FONT
SIZE
=
+3
>
Here are the results of your query:
</
FONT
></
B
>
</
P
>
<
TR
>
<
TH
>
EMPLOYEE NO
</
TH
>
<
TH
>
First Name
</
TH
>
<
TH
>
Initial
</
TH
>
<
TH
>
Last Name
</
TH
>
</
TR
>
<%
java.sql.ResultSet rec =
null
;
// ResultSet
rec = (java.sql.ResultSet) request.getAttribute(
"resultSet"
);
while
(rec.next()) {
out.print (
"<TD>"
+ rec.getString(
"EMPNO"
) +
"</TD>"
);
out.print (
"<TD>"
+ rec.getString(
"FIRSTNME"
) +
"</TD>"
);
out.print (
"<TD>"
+ rec.getString(
"MIDINIT"
) +
"</TD>"
);
out.print (
"<TD>"
+ rec.getString(
"LASTNAME"
) +
"</TD>"
);
out.println(
"</TR>"
);
}
out.println(
"</TABLE>"
);
out.println(
"</FONT></BODY></HTML>"
);
%>
</
CENTER
>
</
BODY
>
</
HTML
>
8
Exemplo: JSP dynamic code
<%
java.sql.ResultSet rec =
null
;
// ResultSet
rec = (java.sql.ResultSet) request.getAttribute(
"resultSet"
);
while
(rec.next()) {
out.print (
"<TD>"
+ rec.getString(
"EMPNO"
) +
"</TD>"
);
out.print (
"<TD>"
+ rec.getString(
"FIRSTNME"
) +
"</TD>"
);
out.print (
"<TD>"
+ rec.getString(
"MIDINIT"
) +
"</TD>"
);
out.print (
"<TD>"
+ rec.getString(
"LASTNAME"
) +
"</TD>"
);
out.println(
"</TR>"
);
}
out.println(
"</TABLE>"
);
out.println(
"</FONT></BODY></HTML>"
);
%>
Example: Output
JSP + Java Beans
JSPs with Beans
Enterprise
Systems
(legacy,
DBMS,
etc.)
Browser
JSP
JavaBean
Servlet Container
request
response
9
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
get### and set### methods.
JSP & JavaBeans
• Using beans in a JSP page
– <jsp:useBean id=“user”
class=“package.Classname”/>
– creates a variable called
user
of type
package.Classname.
– looks first for a reference to an existing
variable and only creates if none in scope.
– this tag can have an optional body that can
run as a scriptlet (only when created).
jsp: useBean
• Format
<jsp:useBean id="name" class="package.Class" />
<jsp:useBean id="book1" class=“Book" />
• can be thought of as equivalent to the scriptlet
<% Book book1 = new Book(); %>
• If that class has a method called XPTO() we can use:
<%
book1.XPTO();
%>
JSP: get/set Properties
• Once created you can access the bean’s
properties:
• accessing properties
<jsp:getProperty name=“user”
property=“Name”/>
• setting properties
<jsp:setProperty name=“user”
property=“Name”
value=“Peseiro”/>
10
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="entry“ class="SaleEntry" />
<jsp:setProperty name="entry" property="*" />
Beans and HTML Forms...
<HTML>
<BODY>
<FORM METHOD=POST ACTION="
GetInfo.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 football club? <INPUT TYPE=TEXT NAME=
club
SIZE=15>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
Get_Info.html
JSP Bean... (UserData.java)
public class
UserData
{
String username;
String email;
String club;
public void setUsername( String value ) {
username = value;
}
public void setEmail( String value ) {
email = value;
}
public void setClub( String value ) {
club = value;
}
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getClub() { return club; }
}
JSP:GetInfo.jsp
<jsp:useBean id="
user
" class="
UserData
" scope="
session
"/>
<jsp:setProperty name="
user
" property="
*
"/>
<HTML>
<BODY>
You entered<BR>
Name: <%=
user.getUsername()
%><BR>
Email: <%=
user.getEmail()
%><BR>
Club: <%=
user.getClub()
%><BR>
</BODY>
</HTML>
11
JSP:OtherJSP.jsp
<jsp:
useBean
id="user" class="
UserData

scope="
session
"/>
<HTML>
<BODY>
OTHER JSP: dados do Java Bean..<BR>
Name: <%=
user.getUsername()
%><BR>
Club: <%=
user.getClub()
%><BR>
</BODY>
</HTML>
Sharing Beans
<jsp:
useBean
id="user"
class="
UserData
"
scope="session"/>
<jsp:
useBean
id="user"
class="
UserData
"
scope=“request”
<jsp:
useBean
id="user"
class="
UserData
"
scope=“application"/>
<jsp:
useBean
id="user"
class="
UserData
"
scope=“page"/>
JSP Containers
• Blazix:
http://www.blazix.com
• Tomcat:
http://jakarta.apache.org/
JSP = HTML + JAVA... (pouco java, pf
JSP = HTML + TAGs + JAVA BEANS
SERVLETS + JSPs
TUTORIAL: http://www.jsptut.com