JSP - FBK | SE

Download Report

Transcript JSP - FBK | SE

An introduction to
JavaServer Page
Alessandro Marchetto
Fondazione Bruno Kessler-IRST,
1


Outline

Just a quick introduction
After this lecture you will be able to
read and write “simple” JSP.
JavaServer Pages








expressions,
scriplets,
declarations,
directives,
predefined variables,
actions,
JavaBeans
...
2
JavaServer Pages (JSP)



JavaServer Pages (JSP) lets you separate the dynamic part of
your pages from the static HTML.
You simply write the regular HTML in the normal manner.
You then enclose the Java code for the dynamic parts in special
tags: “<%” and end with “%>”.
3


We write a JSP page
Then the JSP is automatically converted
into servlet (by the servlet container)
JSP are Servlets

You normally give your file a .jsp extension, and typically
install it in any place you could place a normal Web page.
Although what you write often looks more like a regular
HTML file than a servlet the JSP page just gets
converted to a normal servlet.

This is normally done the first time the page is requested.

4
JSP structure
The dynamic code of a given JSP can be composed of the following
structures:







expressions,
scriplets,
declarations,
directives,
predefined variables,
actions
....
5
JSP Expressions

A JSP expression is used to insert Java values directly into
the output. It has the following form:
<%= Java Expression %>


The Java expression is evaluated, converted to a string,
and inserted in the page. This evaluation is performed at
run-time (when the page is requested), and thus has full
access to information about the request.
For example, the following shows the date/time that the
page was requested:
Current time: <%= new java.util.Date() %>
6

JSP expressions
A small example
<html>
<head>
<title>Simple JSP Page</title>
</head>
<body>
<p>This JSP page contains some HTML code ....
<h1>and a small piece of dynamic code:
<%= new java.util.Date() %>
</p>
</body>
</html>
At runtime it becomes: “dd-mm-yy”
7
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;

simple.jsp converted into a servlet
public class facile_Jsp extends HttpJspBase {
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException, ServletException {
…
JspWriter out = pageContext.getOut();
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Simple JSP Page</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<p>This JSP page contains some HTML code ”);
out.println(“....”);
out.println(“and a small piece of dynamic code:: ”);
out.println(new java.util.Date() );
out.println(“</p></body>”);
out.println(“</html>”);
}
public void service(HttpServletRequest request,
HttpServletResponse response) {
_jspService(request, response);
}
8
JSP Scriplets


If you want to do something more complex than insert a
simple expression, JSP scriptlets let you insert arbitrary
code into the servlet method that will be built to generate
the page. Scriptlets have the following form:
<% Java Code %>
Scriplets can contain a “not-complete” set of Java
statements, and blocks left open can affect the static
HTML outside of the scriptlets.
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
9

JSP scriplets
A small example
<html>
<body>
<% String name=(String)request.getParameter(“param1”);%>
<p>Welcome, <% out.print(name);%> Today is:
<% Date d= new java.util.Date();
out.print(d); %> </p>
</body>
</html>
output
<html>
<body>
<p>Welcome, name Today is: dd-mm-yy
</p>
</body>
</html>
10
JSP Declarations

A JSP declaration lets you define methods or fields that get
inserted into the main body of the servlet class
<%! Java Code %>

Since declarations do not generate any output, they are
normally used in conjunction with JSP expressions or
scriptlets.
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
11

JSP declarations
A small example
<%! private int number = 0;
private int randomNamber() {
return Math.abs(new Random().nextInt() % 100) + 1; }%>
<html>
<head>…</head>
<body>
<h1>Example of JSP declarations</h1>
<h2>Variable values <tt>number</tt>: <%= ++number %>
</h2>
<h2>random number: <%= randomNamber() %>
</body>
</html>
12
JSP Directives

A JSP directive affects the overall structure of the servlet
class. It usually has the following form:
<%@ directive attribute="value" [… attributeN="valueN“] %>

Examples:
<%@ page import="java.util.*" %>
<%@ include file="navbar.html" %>

There are three main directive:
 page
 include
 taglib
13
JSP Directive “Page”
<%@ page attribute1=“value1”, attribute2=“value2”, … %>
Attributes:

Import: define the package to be imported



content-type: define the response content-type (default is “text/html”)
Session: verify if the page is tied to a session


<%@ page session="true" %>
errorPage: redirect to the error page in case of error


<%@ page import="java.util.*" %>
<%@ page errorPage="error.jsp" %>
isErrorPage: define a page that can be used as an error page

<%@ page isErrorPage="true" %>
14
JSP Directive “Include”
This directive lets you include files at the time the JSP page is
translated into a servlet.
<%@ include file=“nome-file” %>
 It has a unique attribute “file”.
 The value of this attribute can be an URL (related to a JSP or
a HTML page)
e.g., <%@ include file="/navbar.html" %>
15
JSP Directive “Taglib”
It allows the JSP page to use custom tag (i.e., custom tag
extensions):
Custom tags are special types of tags tied to Java code that are
usable in JSP pages
E.g., <%@ taglib uri=“tagLibraryURI” prefix=“tagPrefix” %>
URI related to the tag
library to be used
Prefix to be used into the JSP page
to identify the tags of the libray
<tagPrefix:tagname … />
16

JSP without and with taglib
A small example
<html>
<head>
<title>Count without JSTL </title>
</head>
<body>
<%
for(int a=1;a<=10;a++)
{%>
<%=a%><br/>
<%
}
%>
</body>
</html>
<%@ taglib
uri=“http://java.sun.com/jsp/jstl/core”
prefix=“c”
%>
<html>
<head>
<title>Count with JSTL</title>
</head>
<body>
<c:forEach var=“a” begin=“1”
end=“10” step=“1”>
<c:out value=“${a}” />
<br />
</c:forEach>
</body>
</html>
see http://java.sun.com/products/jsp/jstl/ (and click on theAPI Specification link)
17
Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied
with eight automatically defined variables.






Request. HttpServletRequest associated with the request
Response. HttpServletResponse associated with the response to the client.
Out. PrintWriter used to send output to the client.
Session. HttpSession object associated with the request.
Application. ServletContext as obtained via getServletConfig().getContext().
…
18
JavaBeans are software components
Actions
JSP actions use constructs in XML syntax to control the
behavior of the servlet engine.





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..
19
Using JavaBean (1)
SimpleBean.java
package hall;
public class SimpleBean {
private String message = "No message";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
20
BeanTest.jsp
Using JavaBeans (2)
<HTML>
<HEAD> … </HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">
Reusing JavaBeans in JSP</TABLE>
</CENTER>
<P>
<jsp:useBean id="test" class="hall.SimpleBean" />
<jsp:setProperty name="test"
property="message"
value="Hello WWW" />
<H1>Message: <I>
<jsp:getProperty name="test" property="message" />
</I></H1>
</BODY>
</HTML>
instantiate the JavaBean
SimpleBean test=new SimpleBean();
Set the property (message)
message=“Hello WWW”;
Get the value of message
“Hello WWW”
Bean Test result
22
References




Tutorial about Servlets and JSP www.apl.jhu/%7Ehall/java/Servlet-Tutorial
Understanding “Architecture 2” www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html
Sun http://java.sun.com/products/servlet/

Sun (Servlet and JSP) API http://java.sun.com/javaee/5/docs/api/

Sun (Servlet) Documentation http://java.sun.com/products/servlet/docs.html

Sun J2EE Tutorial http://java.sun.com/javaee/5/docs/tutorial/doc/
Apache Tomcat http://tomcat.apache.org/

Tomcat (servlet) API http://tomcat.apache.org/tomcat-5.0-doc/servletapi/index.html

Tomcat (jsp) API http://tomcat.apache.org/tomcat-5.0-doc/jspapi/index.html

Tomcat in Eclipse http://www.sysdeo.com/eclipse/tomcatplugin (a Tomcat installation is
required)

Tutorial
about
how
to
intregrate
Tomcat
in
Eclipse
http://plato.acadiau.ca/courses/comp/dsilver/2513/EclipseAndTomcatTutorial/
23
Tomcat configuration
Tomcat directory organization:
In the directory: $TOMCAT_HOME$/webapps
./myApplication
./myApplication/*.html
./myApplication/*.jsp
./myApplication/WEB-INF/
./myApplication/WEB-INF/web.xml
./myApplication/WEB-INF/classes/*.class
./myApplication/WEB-INF/lib/*.jar
[./myApplication/WEB-INF/src/*.java]
24