JSP - FTP Directory Listing

clangpotatoSoftware and s/w Development

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

71 views

1
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Interdisciplinary Center Herzeliza Israel
Enterprise Application
Development using J2EE
Shmulik London
Web Programming II –
JSP (Java Server Pages)
Lecture #6
Enterprise Application Development Using J2EE / ©Shmulik London 2004
The Problem
ResultSet result = statement.executeQuery(
"SELECT course_id, name, hours FROM courses");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println(<html><body><table border=\"1\">");
writer.println("<tr><td>ID</td><td>Name</td></tr>);
while(result.next()) {
long id = result.getLong(1);
String name = result.getString(2);
writer.println("<tr><td>"+id+"</td>+
<tr><td>+name+</td></tr>);
}
writer.println(</table></body></html>);
Enterprise Application Development Using J2EE / ©Shmulik London 2004
The Problem
• Writing HTML in Java is
cumbersome and inefficient (both
runtime and development cycle)
• We would like Web Designers to do
design the page and programmers
to do the logic (separation of
concerns)
Enterprise Application Development Using J2EE / ©Shmulik London 2004
How we approached it
in the old days... (ASP)
<HTML><TITLE>Multiplication Table</TITLE>
<H2>Multiplication Table</H2>
<TABLE border="1" cellpadding="2" cellspacing="0">
<TR height="20" bgcolor="#f0f0f0"><TD width="20"></TD>
<% FOR J=1 TO 10 %>
<TD width="20"><%=J%></TD>
<% NEXT
FOR I=1 TO 10 %>
<TR height="20"><TD width="20" bgcolor="#f0f0f0"><%=I%></TD>
<% FOR J=1 TO 10 %>
<TD width="20"><%=I*J%></TD>
<% NEXT
NEXT %>
</TABLE>
</HTML>
Note: this example is superficial  we dont need the se rver
for the data, we might as well do it in client side JavaScript
Enterprise Application Development Using J2EE / ©Shmulik London 2004
ASP request processing
Internet
File-system
static content
and templates
Enterprise Application Development Using J2EE / ©Shmulik London 2004
And some continued
this way in JSP…
<HTML>
<TITLE>Multiplication Table</TITLE>
<H2>Multiplication Table</H2>
<TABLE border="1" cellpadding="2" cellspacing="0">
<TR height="20" bgcolor="f0f0f0"><TD width="20"></TD>
<% for (int j=1; j<=10; j++) { %>
<TD width="20"><%=j%></TD>
<% } %>
<% for (int i=0; i<=10; i++) { %>
<TR height="20"><TD width="20" bgcolor="f0f0f0"><%=i%></TD>
<% for (int j=1; j<=10; j++) { %>
<TD width="20"><%=i*j%></TD>
<% }
} %>
</TABLE>
</HTML>
2
Enterprise Application Development Using J2EE / ©Shmulik London 2004
<HTML>
<TITLE>Multiplication Table</TITLE>
<H2>Multiplication Table</H2>
<TABLE border="1" cellpadding="2" cellspacing="0">
<TR height="20" bgcolor="f0f0f0"><TD width="20"></TD>
<% for (int j=1; j<=10; j++) { %>
<TD width="20"><%=j%></TD>
<% } %>
<% for (int i=0; i<=10; i++) { %>
<TR height="20"><TD width="20" bgcolor="f0f0f0"><%=i%></TD>
<% for (int j=1; j<=10; j++) { %>
<TD width="20"><%=i*j%></TD>
<% }
} %>
</TABLE>
</HTML>
Scripting elements make
the code messy and dont
allow for good separation
of concerns (design / logic)
JSP offer better alternatives.
Avoid scripting elements
!
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Scripting Elements
• Imagine large pages, containing both
scripting elements, JavaScript / DHTML,
CSS, sometimes Applets or ActiveX
controls.. server side script that
generate client side script!, pages
delegates control to each other..
• This results in a jungle that is impossible
to maintain
Enterprise Application Development Using J2EE / ©Shmulik London 2004
JSP as a Template Engine
JSP Page
Request
Fetch data or
compute
Use the data
to fill in a JSP template
Return the result of merging the static html
of the template with the dynamic data
Servlet
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example (Query Form)
<html>
<head><title>Course Search</title></head>
<body>
<h1>Course Search</h1>
<form action="course-info" method="POST">
<table border="0">
<tr>
<td>Enter course code</td>
<td><input name="code"
type="text" size="10"/></td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example (JSP Template)
<%@ page contentType="text/html" %>
<html>
<body>
<h1>Course Details</h1>
<b>Name:</b> ${courseName} <br/>
<b>Code:</b> ${courseCode} <br/>
<b>Credit points:</b> ${creditPoints} <br/>
...
</body>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example (Servlet)
protected void doPost(HttpServletRequest request
String code = request.getParameter(code);
String courseName =  fetch data using code
String creditPoints =  fetch data 
request.setAttribute(courseName, courseName);
request.setAttribute(courseCode, code);
request.setAttribute(creditPoints, creditPoints);
RequestDispatcher dispatcher =
request.getRequestDispatcher(
"/course-info.jsp");
dispatcher.forward(request, response);
}
3
Enterprise Application Development Using J2EE / ©Shmulik London 2004
JSP request processing
Internet
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Template Engines
• Many web frameworks use the idea
of a template engine
– JSP, Velocity, FreeMarker… (Java)
– Django (Python)
– Ruby on Rails (Ruby)
– Grails (Groovy)
– Lift (Scala)
– …
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Beyond Placeholders
• Sometimes we need more than just
placeholders
– Lists / Tables
– Conditional segments
– Common elements – header, footer..
– …
• We use
JSP Tags
for this
– Again not embedded code!
Enterprise Application Development Using J2EE / ©Shmulik London 2004
JSP Tags
• JSP defines a set of HTML-like tags
that allow to add dynamic content
to a page
• In addition it provide a simple way
for writing your own custom tags
• You can find numerous of tag
libraries (often open source)
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example:
include
Tag
<%@ page contentType="text/html" %>
<html>
<body>
<jsp:include page="header.html/>
<jsp:include page="menu.jsp/>
<h1>My special page</h1>
Here is the content of my special page . . .
. . .
<jsp:include page="footer.html"/>
</body>
</html>
• Includes the content of another page
(static or dynamic) in the current page
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example
Using <jsp:include> to include a result of a Servlet
Again: this example is superficial  we dont need the se rver for the data, we might as well
do it in client side JavaScript
4
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example
Using <jsp:include> to include a result
of a Servlet
MultiplicationTableServletmultiplication_table.jsp
Enterprise Application Development Using J2EE / ©Shmulik London 2004
MultiplicationTableServlet
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
try {
int rows = Integer.parseInt(
request.getParameter("rows"));
int columns = Integer.parseInt(
request.getParameter("columns"));
PrintWriter writer = response.getWriter();
printTable(writer, rows, columns);
} catch (NumberFormatException e) {
System.out.println("Illegal parameter value");
}
}
Enterprise Application Development Using J2EE / ©Shmulik London 2004
MultiplicationTableServlet
private void printTable(
PrintWriter writer,
int rows,
int columns) {
writer.println("<TABLE border=\"1\" cellpading... >");
writer.println("<TR height=\"20\" bgcolor=...</TD>");
for (int j=1; j<=columns; j++) {
writer.println("<TD width=\"20\">"+j+"</TD>");
}
for (int i=1; i<=rows; i++) {
writer.println(
"<TR height=\"20\"><TD width=\"20\" " +
"bgcolor=\"f0f0f0\">"+i+"</TD>");
...
}
}
Enterprise Application Development Using J2EE / ©Shmulik London 2004
multiplication_table.jsp
<%@ page contentType="text/html" %>
<h2>Multiplication Table</h2>
<form method="GET" action="multiplication_table.jsp" >
Rows <select name="rows"><option value="3">3</option>...
</select>
Columns <select name="columns">...
</select>
<input type="submit" value="Go">
</form>
<jsp:include page="/multiplication_table_servlet"
flush="true">
<jsp:param name="rows"
value="<%=request.getParameter("rows")%>"/>
<jsp:param name="columns"
value="<%=request.getParameter("columns")%>"/>
</jsp:include>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
JSTL
• JSTL - JSP Standard Tag Library
• Collection of tags for functions that
are common to many web apps
– flow control, formatting, IO...
– Introduces EL expressions
Note: JSTL introduce many Tags, but not all make sense,
Tags that access the database or read files directly from the JSP
page is a bad idea! In general all the logic of fetching the data should
be done in lower layer
Enterprise Application Development Using J2EE / ©Shmulik London 2004
if Tag
<%@ page import="sokoban.web.*"%>
<%@ page contentType="text/html" %>
<%@ taglib prefix="c
uri="http://java.sun.com/jstl/core" %>
<jsp:include page="/header.html"/>
<p>Welcome to our Sokoban server.
...
<c:if test="${!(empty sessionInfo.message)}">
<p><font color="#CC3300">
<c:out value="${sessionInfo.message}" />
</font></p>
</c:if>
...
EL Expressions
5
Enterprise Application Development Using J2EE / ©Shmulik London 2004
foreach Tag
<%@ page contentType="text/html" %>
<%@ page isELIgnored ="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h1>Course List</h1>
<table border="1" cellpadding="3" cellspacing="0">
<tr>
<th width="80" align="center">Symbol</th>
<th width="400" align="center">Name</th>
<th width="120" align="center">Instructor</th>
</tr>
<c:forEach var="course" items="${courses}">
<tr>
<td align="center">${course.symbol}</td>
<td align="center">${course.name}</td>
<td align="center">${course.instructor}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Servlet Side
public void doGet(HttpServletRequest request  ) {
...
ResultSet results = statement.executeQuery(
SELECT * FROM courses);
List<CourseInfo> courses = new ArrayList<CourseInfo>();
while (results.next()) {
CourseInfo course = new CourseInfo();
course.setSymbol(results.getString(symbol));
course.setName(results.getString(name));
...
}
request.setAttribute(courses, courses);
request.getRequestDispatcher(/course-list.jsp).
forward(request, response);
}
Note: there might be too many results to be sent in a single request, it is always a good idea to
limit the number of results and page through them
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Tag Libraries
• JSP allows you to add additional
tags through tag-libraries
• You can wrap a commonly used
presentation code in a new tag and
provide it to the web-designer
• You can find numerous tag libraries
(notably JSTL) or develop your
own
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Custom Tag Example
Repeated HTML code
Again, this example is superficial  we are
better off using JavaScript here as expanding
the tag in the server will result-in large html
sent to the client, and redundant server load
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Custom JSP Tag
<%@ page contentType="text/html" %>
<%@ taglib prefix="examples
uri="http://www.idc.ac.il/j2ee/examples" %>
<h2>Recommended EJB Books</h2>
<table border=0>
<tr>
<td><examples:rank rank="5"/></td>
<td>Enterprise JavaBeans / Reichard Monson-Haefel</td>
</tr>
<tr>
<td><examples:rank rank="5"/></td>
<td>Mastering Enterprise JavaBeans / Ed Roman</td>
</tr>
<tr>
<td><examples:rank rank="4"/></td>
<td>EJB Design Patterns / Floyd Marinescu</td>
</tr>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Custom JSP Tag
package examples.web.tags;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class RankTag extends TagSupport {
private static final int MAX_RANK = 5;
private int rank;
public void setRank(int rank) {
this.rank = rank;
}
6
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Custom JSP Tag
public int doStartTag() throws JspException {
JspWriter writer = pageContext.getOut();
try {
writer.println("<table border=0 width=50>");
writer.println("<tr height=20 width=50>");
for (int i=0; i<MAX_RANK; i++) {
writer.println(i<rank ?
<td width=10><image +
src=\"res/icons/star.gif\"</td>") :
<td width=10>&nbsp;</td>");
}
}
writer.println("</tr></table>");
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_PAGE;
}
}
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Custom JSP Tag
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, ...
<taglib>
<tlibversion>1.1</tlibversion>
<jspversion>1.1</jspversion>
<shortname>examples</shortname>
<uri>http://www.idc.ac.il/j2ee/examples</uri>
<tag>
<name>rank</name>
<tagclass>examples.RankTag</tagclass>
<attribute>
<name>rank</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Web Application Framework
• Real applications consists of many Web-
pages both dynamic & static
• Pages forward/redirect request to other
pages, include other pages, and call
components to perform logic
• We need a consistent framework for
organizing all presentation and logic
components and the interaction
between them
Enterprise Application Development Using J2EE / ©Shmulik London 2004
WAFs
• Such a framework is referred to as
WAF (Web Application Framework)
• There are many Java based WAFs,
on top of JSP and/or Servlets
• We’ll describe a general design for
working with JSP & Servlets. It is
used in Struts2 and other WAFs
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Model2
• Model2* applies a design pattern known
as MVC to the problem
– The client directs all requests to a single
controller Servlet
– The controller process the request, acts on the
model and forwards the request to another
Servlet/JSP for rendering
– The target Servlet/JSP render the response
according to attributes passed by the
controller via request/session attributes
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Model2 (MVC)
JSP Pages (View)
7
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example (ex3)
login.jsp game.jsp
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Passing parameters
public class ControllerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, ...) {
...
request.setAttribute(price, new Float(price));
... forward
<%@ page contentType="text/html" %>
...
Price: ${price}
...
Controller Servlet
Rendering JSP page
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Using JavaBeans
• JSP allows to separate presentation
from logic by using JavaBeans
– You ‘embed’ a JavaBean in your page
– Set its properties, typically according
to request parameters values
– The bean calculates the value of
other properties accordingly
– Retrieve the value of the calculated
property and include it in the page
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Using JavaBeans
Developer
Works with
Java & HTML
Web-Designer
Works with
designer tools
JSP Page
JavaBeans Component
(logic)
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Mortgage Calculator Example
Enterprise Application Development Using J2EE / ©Shmulik London 2004
MortgageCalcBean
/**
* A JavaBean component for calculating a mortgage
* monthly payment
*/
public class MortgageCalcBean implements Serializable {
// The requested amount of the loan
private double loanAmount;
// The annual interest
private double interest;
// The requested period of the load in years.
private int years;
Hold the value of the properties of the bean
8
Enterprise Application Development Using J2EE / ©Shmulik London 2004
MortgageCalcBean
public double getLoanAmount() {
return loanAmount;
}
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
public double getInterest() {
return interest;
}
public void setInterest(double interest) {
this.interest = interest;
}
Setter/Getter methods, define the
properties of the bean
Enterprise Application Development Using J2EE / ©Shmulik London 2004
MortgageCalcBean
public double getMonthlyPayment() {
double monthlyPayment = calculateMonthlyPayment();
return monthlyPayment;
}
private double calculateMonthlyPayment() {
double monthlyInterest = interest * 0.01 / 12;
int months = years * 12;
double debt = Math.pow(1+monthlyInterest, months);
double monthlyPayment =
loanAmount*debt*monthlyInterest/(debt-1);
monthlyPayment =
Math.floor(monthlyPayment*100)/100.0;
return monthlyPayment;
}
}
Read only property to return the result
Enterprise Application Development Using J2EE / ©Shmulik London 2004
mortgage_calculator.jsp
<%@ page contentType="text/html" %>
<h1 align="center">Simple Mortgage Calculator</h1>
<p>
Below is a simple calculator for calculating the
monthly payment of the mortgage. Please enter the
required loan amount, the interest you expect to get
for the loan and the period of the loan in years;
then press the 'calculate' button.
</p>
... tabs, tables to enhance the
look of the page
Enterprise Application Development Using J2EE / ©Shmulik London 2004
mortgage_calculator.jsp
<jsp:useBean id="calc" class="MortgageCalcBean"/>
<jsp:setProperty name="calc"
property="loanAmount" param="loanAmount"/>
<jsp:setProperty name="calc" property="interest" ...
<jsp:setProperty name="calc" ...
<form method="POST" action="mortgage_calc.jsp" >
Amount: <input type="text" name="loanAmount"
value="<%=calc.getLoanAmount()%>"><br>
Interest: <input type="text" name="interest"
value="<%=calc.getInterest()%>"><br>
Years: <input type="text" name="years"
value="<%=calc.getYears()%>"><br>
<input type="submit" value="Calculate">
</form>
Monthly Payment $
<jsp:getProperty name="calc" property="monthlyPayment"/>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Packaging
• A web-application consists of many
elements
– Static HTML pages and resources
(images, clips, ...)
– JSP pages and tag-libraries
– Servlets, Java classes, JARs
– Configuration files (descriptors)
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Packaging
• J2EE defines a standard form for
packaging web-applications
– The packaging unit is called a web-module
– It has standard folder structure and
contains standard descriptor files
– The module is packaged as a WAR file (Web
Achieve) – essentially a zip of the folder
– It can either be packaged standalone or as
part of a J2EE application together with
other web modules and ejb modules
9
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Packaging
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Example
resources
libraries
required
by JSTL
web-pages
JSP & static
Servlet and
supporting classes
tag library
definition
for JSTL
web application
descriptor
JBoss specific
web application
descriptor
Enterprise Application Development Using J2EE / ©Shmulik London 2004
web.xml
<web-app>
<servlet>
<servlet-name>CourseListServlet</servlet-name>
<servlet-class>CourseListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CourseListServlet</servlet-name>
<url-pattern>/course_list</url-pattern>
</servlet-mapping>
...
<env-entry>
<env-entry-name>jdbc/IDCDB</env-entry-name>
<env-entry-value>
!org.gjt.mm.mysql.Driver!jdbc:mysql://localhost:...
</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>
</web-app>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
application.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE application PUBLIC '-//Sun Microsystems, ...
<application>
<display-name>Examples</display-name>
<module>
<web>
<web-uri>examples.war</web-uri>
<context-root>/examples</context-root>
</web>
</module>
</application>
Enterprise Application Development Using J2EE / ©Shmulik London 2004
Apache Ant and other insects...
• Manual packaging is tedious & error-prone
• Application server tools & IDEs provide
varying level of support for packaging,
deployment and editing descriptor files -
often not enough
• We’ll use Apache Ant, which is a generic
build tool and de-facto standard building
Java applications
• More on Ant in a separate presentation...