SlideShare a Scribd company logo
1 of 74
Download to read offline
Java Server Pages
Eleonora Ciceri
ciceri@elet.polimi.it
Servlets: what we know so far
¤  Interaction with user
¤  A servlet accepts HTTP requests
¤  HTML pages are returned as HTTP responses
¤  Page production
¤  Dynamic parts of the page:
¤  Depend on dynamic states (e.g., request parameters)
¤  Are filled with Java code which, when compiled,
produced HTML code
¤  Static parts of the page are printed on the output as they
are, without any modification
Servlets: too many out.println…
out.println(“<span style=“width:100%;”>”);!
out.println(“Select an action:”);!
out.println(“<ul>”);!
out.println(“<li>Action 1</li>”);!
out.println(“<li>Action 2</li>”);!
out.println(“<li>Action 3</li>”);!
out.println(“</ul>”);!
out.println(“</span>”);!
Difficult to
read!
Mixing presentation with content in Java code
Servlets: are they a good idea?
¤  Complex code, not really readable
¤  HTML is mixed up with the Java Servlet code
¤  If HTML is printed, a lot of out.println() are used
¤  Presentation and logic are merged in a unique resource
¤  What if I want to change some of the aspects of the
presentation style? Do I have to read and modify also the
code used for producing dynamic content?
¤  Errors in the HTML code are difficult to be spotted
Servlet modification
Web designer
•  Required to
understand Java
Programmer
•  Required to write part
of the page layout
Problem: “mixing competences”
How do we define which are the
tasks that need to be developed by
each person in the team?
•  Train web designers for Java?
•  Compromises about page layout?
Java Server Pages (1)
¤  JSP integrates Java instructions in the HTML code. These
instructions are used in order to compute parts of the
page dynamically
¤  Difference with Java Servlet: a servlet integrates HTML in the
Java code, JSP integrates Java code in the HTML
¤  This is an attempt to separate content from presentation
¤  Still some problems: one could integrate huge pieces of
Java code…
¤  Advantages: learning is easier, more readable
¤  Disadvantage: still “primitive” solution (JSTL?)
Java Server Pages (2)
Servlets Java Server Pages
Necessary to
•  Write a class
•  Write a configuration
•  Know methods and syntax
Necessary to
•  Know HTML + a bit of Java
No configuration (auto-compiled)
Java Server Pages (3)
Scriptlet
•  1+ for each page
•  JSP with 0 scriptlet =
plain HTML page
Template
Here: whatever
depends on
dynamic behaviors
(e.g., request
parameters, db
connections…)
•  Modified by
programmers
Here: fixed page
layout, presentation
•  Modified by
designersStatic parts
Dynamic parts
Java Server Pages (4)
¤  A JSP page is called template
¤  The Java code inserted in the template is called scriptlet
¤  Servlets are still useful!
¤  General usage
¤  Servlets are used to contain the logic
¤  JSP pages are used for the presentation of the results
Mixing HTML, JSP and servlets (1)
¤  Example of application
¤  The user inserts the parameters of the query he wants to
perform in an HTML form
¤  Results are retrieved from the database and displayed
Mixing HTML, JSP and servlets (2)
HTML form
•  No dynamic parts
•  No need to use
server-side scripting
Servlet
•  Database connection
•  Retrieve results
JSP page
•  Display the results
Logic
Presentation
JSP interpretation
¤  A Java Server Page does NOT produce HTML code as an
output
¤  JSP belongs to the server-side programming techniques,
thus it runs on the server
WebContent folder
Translated
into what?
JSP goes to servlets
Template
HTML code
Scriptlets
HTML code
Interpreted
by the server
¤  The template is interpreted by the server in order to
generate a page made of HTML code
¤  The browser receives just HTML code
¤  This hides the scripts, hackers would not see them
Servlet
Automatically
generated
How do we produce HTML code?
JSP: behind the scenes (1)
¤  The server automatically creates, compiles, loads and
runs a special servlet to generate the page’s content
¤  The static portions of the HTML page are generated by the
servlet by using out.println()
¤  The dynamic portions are included directly
¤  Every time there is a change in the JSP page, the servlet
is automatically recompiled
¤  First time: longer periods of time in order to create the servlet
¤  Other times: shorter periods of time in order to add pieces to
the servlet
JSP: behind the scenes (2)
1)  Start server
(load every JSP page
in WebContent)
WebContent folder
2) Translate
(each JSP page is automatically
translated into a Servlet)
Automatic mapping
between the requested
page and the created
servlet
JSP: behind the scenes (3)
1)  Request to the
JSP page
(user requires to access
to the page)
2) Look for the mapping
(the server looks for the mapping between the
requested JSP page and the created servlet)
3) Compute the response
(the servlet handles the request and
returns the response)
HTML
code
JSP: behind the scenes (4)
1)  Modify the JSP
page
(with any modification –
either on static or dynamic
parts)
2) Look for the mapping
(the server looks for the mapping between the
modified JSP page and the created servlet)
3) Modify the servlet
(the update is reflected on the
servlet)
Plain HTML or JSP?
¤  Allowed
¤  Create a JSP page
with 0+ scriptlets
¤  Suggested
¤  Create a JSP page
with 1+ scriptlets
¤  To be avoided
¤  Create a JSP page
with 0 scriptlets
JSP page with 0 scriptlets
(= HTML page)
Unaltered
HTML code
Translation
OVERHEAD
Using Java Server Pages
¤  Each block of servlet code is surrounded by a leading <%
tag and a closing %> tag
¤  A scriptlet can use predefined variables:
¤  request: the servlet request(HttpServletRequest)
¤  response: the servlet response (HttpServletResponse)
¤  out: the output writer (PrintWriter)
¤  in: the input reader (BufferedReader)
HelloWorld JSP page
<html>!
<head><title>Hello, World!</title></head>!
<body>!
!<% !
!if (request.getParameter("name") == null) !
out.println("Hello, World!");!
!else!
out.println("Hello, " + request.getParameter
("name") + "!"); !!
!%>!
</body>!
</html>
Retrieve a parameter from the
request (here: query string)
Scope variables (1)
Page
scope Request
scope
Session
scope
Application
scope
Scope variables (2)
¤  page: the data can be retrieved from any of the parts of
the page
¤  request: the data can be retrieved from all the pages
that analyse the same HTTP request (<jspforward>)
¤  session: the data can be retrieved from any template
required by the same user (at least until the session is
valid)
¤  application: the data can be retrieved from any of the
templates of the same web application
Scope variables (3)
¤  Set an attribute of a variable
¤  variable.setAttribute(String name, Object value)
¤  Read an attribute from a variable
¤  Object o = variable.getAttribute(String name)
JSP syntax (1)
¤  Comment: <%-- comment --%>
¤  Expression: <%= expression %>
¤  The expression is computed, translated into a String and then
displayed
¤  Declaration: <%! declaration %>
¤  How to define attributes and methods that will be copied in
the servlet
¤  Action: <jsp:actionName action />
¤  XML tag that invokes Web server functionalities
JSP syntax (2)
¤  Directive: <%@ directiveName attrName =
“attrValue”%>
¤  Allows to use other servlet aspects
¤  Examples of directives:
¤  <%@ page session=“false”%> disables the session tracking
¤  <%@ page errorPage=“error.jsp”%> sets the page URL
that will be used in case of error
¤  <%@ page import=“java.lib.*”%> imports a Java library
HelloWorld JSP: refactored
<html>!
<head><title>Hello, World!</title></head>!
<body>!
!Hello, <%=getName(request) %>!!
</body>!
</html>!
!
<%!!
private static final String DEFAULTNAME = "World";!
private static final String getName(HttpServletRequest request) {!
String name = request.getParameter("name");!
if (name == null)!
!return DEFAULTNAME;!
else!
!return name;!
}!
%>
JSP declaration
Database connection
InsertEmployeeName.html DatabaseConnection.jsp
Name Phone
John 89398544
Sam 83478534
Database connection: user input
<html>!
<head><title>Retrieve phone number</title></head>!
<body>!
!<form method=POST action="DatabaseConnection.jsp">!
Insert the name of the employee here:!
<input type="text" name="employeeName"/>!
<input type="submit"/>!
!</form>!
</body>!
</html>
Database connection: data retrieval (1)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>!
<%@ page import="java.sql.*" %>!
!
<%!
String name = request.getParameter("employeeName");!
Class.forName("com.mysql.jdbc.Driver");!
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/
test", "root", "");!
PreparedStatement statement = connection.prepareStatement("SELECT * FROM employees
WHERE name=?");!
statement.setString(1,name);!
ResultSet resultSet = statement.executeQuery();!
%>!
!
<html>!
<head><title>Phone numbers</title></head>!
<body>!
Phone numbers for the required user:!
<% if (!resultSet.isBeforeFirst()) { %>!
There are no numbers!!
<% !
}!
Check if there are
no results
Prepare query and
execute it
Database connection: data retrieval (2)
else {%>!
<table>!
<tr>!
<td><font size="+1">Name</font></td>!
<td><font size="+1">Phone</font></td>!
</tr>!
<% while (resultSet.next()) { %>!
<tr>!
<td><%= resultSet.getString("name") %></td>!
<td><%= resultSet.getString("phone") %></td>!
</tr>!
<% } %>!
</table>!
<% } %>!
</body>!
</html>!
!
<%!
resultSet.close();!
statement.close();!
connection.close();!
%>
Print each tuple in
the result set
Close connection
and statement
Mixing JSP and Servlets
NewEmployee.jsp
CreateEmployee
Name
Phone
NewEmployeeCreated.jsp
Store new
employee and
retrieve ID
Retrieve data about
the created object
Insert new employee data
<html>!
<head><title>Create a new employee</title></head>!
<body>!
<form method=POST action="CreateEmployee">!
!Name: <input type="text" name="name"/>!
!<br />!
!Phone: <input type="text" name="phone"/>!
!<br />!
!<input type="submit"/>!
</form>!
</body>!
</html>
NewEmployee.jsp
Store the employee in the database
(1)
public class CreateEmployee extends HttpServlet {!
Connection connection;!
!!
public void init(ServletConfig config) throws ServletException { !
ServletContext context = config.getServletContext(); !
String loginUser = context.getInitParameter("dbUser");!
String loginPasswd = context.getInitParameter("dbPassword");!
String loginUrl = context.getInitParameter("dbURL"); !
!
try {!
Class.forName("com.mysql.jdbc.Driver");!
connection = DriverManager.getConnection(loginUrl,
loginUser, loginPasswd);!
}!
catch (ClassNotFoundException ex) {!
System.err.println("ClassNotFoundException: " +
ex.getMessage());!
throw new ServletException("Class not found Error");!
}!
catch (SQLException ex) {!
System.err.println("SQLException: " + ex.getMessage());!
}!
}!
CreateEmployee
Get parameters from the context
Get the connection
Store the employee in the database
(2)
public void doPost(HttpServletRequest request, HttpServletResponse response)!
!throws IOException, ServletException {!
String id = ””;!
try {!
synchronized(connection) {!
String query = "INSERT INTO employees (name, phone) VALUES (?,?)";!
PreparedStatement statement = connection.prepareStatement(query);!
statement.setString(1, (String) request.getParameter("name"));!
statement.setString(2, (String) request.getParameter("phone"));!
statement.executeUpdate(); !
statement.close();!
! !!
query = "SELECT id FROM employees WHERE name=? AND phone=?";!
statement = connection.prepareStatement(query);!
statement.setString(1, (String) request.getParameter("name"));!
statement.setString(2, (String) request.getParameter("phone"));!
ResultSet resultSet = statement.executeQuery();!
resultSet.next();!
id = resultSet.getString("id");!
}!
} !
CreateEmployee
Insert employee in
the database
Retrieve the
employee ID
Store the employee in the database
(3)
catch(Exception ex) { !
ex.printStackTrace();!
return;!
}!
response.sendRedirect("NewEmployeeCreated.jsp?id=" +
id);!
} !
public void destroy() {!
try {!
if (connection != null){!
connection.close();!
}!
} !
catch (SQLException sqle) {}!
}!
}
CreateEmployee
Send redirect to the
second JSP page
Report the results (1)
<%@ page import="java.sql.*,java.util.*,java.text.*" %>!
<%Connection connection = null; ResultSet resultSet = null;!
ServletContext context = config.getServletContext(); !
String loginUser = context.getInitParameter("dbUser");!
String loginPasswd = context.getInitParameter("dbPassword");!
String loginUrl = context.getInitParameter("dbURL");!
!
String name = "”; String phone = "”;!
!
try {!
Class.forName("com.mysql.jdbc.Driver");!
connection = DriverManager.getConnection(loginUrl, loginUser, loginPasswd); !
}!
catch (ClassNotFoundException ex) {!
System.err.println("ClassNotFoundException: " + ex.getMessage());!
throw new ServletException("Class not found Error");!
}!
catch (SQLException ex) {!
System.err.println("SQLException: " + ex.getMessage());!
}!
String id = request.getParameter("id");!
Retrieve data about
the connection to
the database
Retrieve the id of the created
employee from the request
Create database connection
NewEmployeeCreated.jsp
Report the results (2)
if ((id != null) && (id != "")) { !
try {!
String query = "SELECT name,phone FROM employees WHERE id
= ?";!
PreparedStatement statement = connection.prepareStatement
(query);!
statement.setInt(1, new Integer(id));!
resultSet = statement.executeQuery();!
resultSet.next();!
name = resultSet.getString("name");!
phone = resultSet.getString("phone");!
}!
catch (Exception e) {!
e.printStackTrace();!
}!
} !
%>!
Retrieve data about the
inserted employee
NewEmployeeCreated.jsp
Report the results (3)
<html>!
<head><title>New employee created!</title></head>!
<body>!
New employee created.!
<ul>!
<li> Name: <%=name %></li>!
<li> Phone: <%=phone %></li>!
</ul>!
</body>!
</html>
Print the values that were
inserted in the database
NewEmployeeCreated.jsp
JSP include (1)
¤  A JSP page can be fractioned in parts
¤  Each part could represent a specific functionality
¤  Each part can be reused in other JSP pages
Connection.jsp
(performs the connection to
databases)
SearchEmployee.jsp
InsertEmployee.jsp
JSP include (2)
¤  How to include (mode 1)
¤  <%@ include file=“path” %>
¤  The code is included when the servlet is created
¤  If the included page is modified, the including pages need
to be recompiled
¤  The variables that are present in the included page are
visible also in the including page
JSP include (3)
¤  How to include (mode 2)
¤  <jsp:include page=“path” flush=“true”/>
¤  The page is included at request time: no need to recompile
¤  The output of the resource is included in the caller
¤  Caller page and called page are independent, thus in order
to pass parameters between them:
<jsp:include page=“path”>
<jsp:param name=“paramName” value=“paramValue”/>
</jsp:include>
JSP redirect vs. JSP forward
¤  The forward action allows one to send the request to
another resource
¤  The redirect is performed in a transparent way: the browser is
not notified
¤  <jsp:forward page=“/path.jsp”/>
¤  The request variable is identical to the one sent to the source
page
¤  The redirect action performed on HttpServletResponse
asks to the client to send a new request in order to obtain
the new page
¤  response.sendRedirect(String location)
Disadvantages of scriptlets
¤  Writing the scriptlets in the page makes the page difficult
to be read and understood by those who don’t know the
Java language
¤  Content developers
¤  Designers
So many questions…
¤  Mixing competences
¤  Who edits the Java code?
¤  Who edits the presentation?
¤  How to divide the roles?
¤  XML validation
¤  How can we validate the JSP templates? (No valid XML: it
includes no-XML code)
Solution: Java beans
¤  A Java bean is a reusable class with methods and
variables that follow some naming conventions, so as to
make them easily accessible
¤  Constructor: without parameters
¤  Getter and setter for each attribute
¤  A Java bean is used so as to perform ad-hoc operations
¤  JSP uses natively the Java beans
¤  They can be included in the scopes
¤  Their attributes can be set automatically
Java beans: usage
¤  Inclusion
¤  <jsp:useBean id=“name” scope=“page|request|
session|application” class=“className”
type=“typeName”/>
¤  Handling parameters
¤  <jsp:setProperty name=“beanName”
property=“propertyName” param=“paramName”/>
¤  <jsp:setProperty name=“beanName”
property=“propertyName” value=“constant”/>
¤  <jsp:getProperty name=“beanName”
property=“propertyName”/>
From the request
Constant value
A simple Java bean
public class HelloBean {!
private String name = "World";!
private String place = "empty";!
!!
public void setName(String name) {!
this.name = name;!
}!
public String getName(){!
return this.name;!
}!
public void setPlace(String place) {!
this.place = place;!
}!
public String getPlace() {!
return this.place;!
}!
}
Properties of the bean
Accessing to the bean
<%@page import="it.polimi.tiw.jsp.examples.beans.HelloBean" %>!
<jsp:useBean id="hello" !
class="it.polimi.tiw.jsp.examples.beans.HelloBean">!
<jsp:setProperty name="hello" property="name" param="userName"/>!
</jsp:useBean>!
!
<html>!
<head><title>Hello, World!</title></head>!
<body>!
!Hello, <jsp:getProperty name="hello" property="name"/>!!
</body>!
</html>
Bean name
Bean name Name of the property
that will be modified
Parameter of the query string that
will be used to set the property
Bean name Name of the
property that will be
read from the bean
Java beans and session scope
¤  When a bean is stored in the session, it can be accessed
from any page that uses that session
Java
Bean
Session
Read
information
Store bean in session
<%@page import="it.polimi.tiw.jsp.examples.beans.HelloBean" %>!
<jsp:useBean id="hello" class="it.polimi.tiw.jsp.examples.beans.HelloBean"
scope="session">!
<jsp:setProperty name="hello" property="name" param="userName"/>!
<jsp:setProperty name="hello" property="place" value="Como"/>!
</jsp:useBean>!
!
<html>!
<head><title>Hello, World!</title></head>!
<body>!
Hello, <jsp:getProperty name="hello" property="name"/>!!
<br />!
Place (stored in session): <jsp:getProperty name="hello"
property="place"/>!
<form method=POST action="HelloWorldBeanSession2.jsp">!
<input type="submit"/>!
</form>!
</body>!
</html>
Retrieve
from the
query string
Set the property equal
to a fixed value
When instantiated, the bean is
stored in the session.
•  Properties can be retrieved
from the session
Read information from the session
<%@page import="it.polimi.tiw.jsp.examples.beans.HelloBean" %>!
<jsp:useBean id="hello" !
class="it.polimi.tiw.jsp.examples.beans.HelloBean"
scope="session"/>!
!
<html>!
<head><title>Hello, World!</title></head>!
<body>!
Name in session: <jsp:getProperty property="name" name="hello"/>!
</body>!
</html>
Retrieve the bean from the session
Read the property from the bean
JSP Tag Library
Tag libraries: Custom actions (1)
¤  We can define custom action libraries using the JSP tag
extension
¤  A custom action is invoked by using a custom tag in a JSP
page
¤  A tag library is a collection of custom tags
¤  The tag libraries are used in order to hide the Java code
in the mark-up language
¤  Each tag is associated with a Java class, called tag
handler, that implements a specific interface:
javax.servlet.jsp.tagext.Tag
Tag libraries: Custom actions (2)
¤  The Tag Library Descriptor (TLD) is an XML file that keeps
track of the associations between classes and tags
¤  Example:
<%@ taglib uri=“myTagLibrary.tld” prefix=“mtl”%>!
<tr>!
<td>!
Cost of the transaction: <mtl:write
scope=“session” name=“transactionValue”/>!
</td>!
</tr>!
Tag libraries: Advantages
¤  The JSP pages are built out of reusable components
¤  Increase productivity
¤  Separate Java programmers (who will write the tag libraries)
and the Web application designers
¤  Features
¤  Configuration using attributes
¤  Access to JSP variables
¤  Communication between different tags
How does it work?
Translates
into
<tag>
JSP page
Each time <tag> is encountered in the
JSP page, it is translated into a call to
one of the methods in Tag Handler
How to build a custom tag
¤  In order to build a custom tag:
¤  Define a tag handler, i.e., a Java class that encapsulate the
logic of the tag
¤  Define a TLD, i.e., an XML file that stores the coupling
between tag handlers and tags
¤  Types of custom tags:
¤  javax.servet.jsp.tagext.Tag: generic tags
¤  javax.servlet.jsp.tagext.BodyTag: tag that write on
nested elements
Custom tag: methods (1)
¤  The main methods are doStartTag() and doEndTag()
¤  They are invoked on the tag handler
¤  Between the two invocations the tag handler holds a state
that must be preserved
¤  After the doEndTag() call, the tag is available for further
invocations
Default values for
the properties Initialized properties
(pageContext,
parent, AttSet)
Hold state
new()
setPageContext()
setParent()
setters()
doStartTag()
doEndTag()
release()
Custom tag: methods (2)
¤  Field summary
¤  EVAL_BODY_INCLUDE: evaluate body into existing out stream
¤  EVAL_PAGE: continue evaluating the page
¤  SKIP_BODY: skip body evaluation
¤  SKIP_PAGE: skip the rest of the page
¤  doStartTag() returns EVAL_BODY_INCLUDE is the tag
content has to be executed, otherwise it returns
SKIP_BODY
¤  doEndTag() returns EVAL_PAGE is the rest of the page has
to be executed and SKIP_PAGE otherwise
Simple tag example: handler (1)
public class SimpleTagHandler implements Tag, Serializable {!
!private PageContext pc = null;!
!private Tag parent = null;!
!private String name = null;!
!!
!public void setPageContext(PageContext pc) {!
! !this.pc = pc;!
!}!
!!
!public void setParent(Tag parent) {!
! !this.parent = parent;!
!}!
!!
!public void setName(String name) {!
! !this.name = name;!
!}
Declaration of
page context
Attributes
Attribute setters
Page context
setters
Simple tag example: handler (2)
!public int doStartTag() throws JspException {!
try {!
if (name != null)!
! !pc.getOut().write("Hello, " + name + "!");!
else!
! !pc.getOut().write("You didn't enter your name");!
}!
catch (IOException e) {!
throw new JspTagException("An IO exception occurred");!
}!
return SKIP_BODY;!
!}!
!public int doEndTag() throws JspException {!
return EVAL_PAGE;!
!}!
!public void release() {!
pc = null;!
parent = null;!
name = null;!
!}!
}
When the tag is
evaluated, printing
the name on the
output is requested
Once the tag is evaluated, the body does
not have to be evaluated
Then, the page evaluation is continued
Then the tag is
released, all the
properties are set to
an undefined value
Simple tag example: TLD
<taglib>!
<tlibversion>1.0</tlibversion>!
<jspversion>1.1</jspversion>!
<shortname>MyTagLibrary</shortname>!
<info>My Tag Library</info>!
<tag>!
<name>simple</name>!
<tagclass>it.polimi.tiw.jsp.taglib.handlers.SimpleTagHandler</
tagclass>!
<bodycontent>empty</bodycontent>!
<info>This tag prints a name</info>!
<attribute>!
<name>name</name>!
<required>false</required>!
</attribute>!
</tag>!
</taglib>
The name that will be used to reference the tag
The attribute that can be used in the tag.
It is not required, i.e., if not specified a
default behavior will be applied
Simple tag example: JSP page
<%@ taglib uri="/WEB-INF/MyTagLibrary.tld"
prefix="mtl" %>!
<html>!
!<head>!
! !<title>Simple Tag Example</title>!
!</head>!
!<body>!
! !Name: <mtl:simple name="TIWuser"/>!
!</body>!
</html>
Include the tag library and assign the prefix mtl to it
Use the tag by specifying the attribute name
Tags and variables
¤  It is possible to make the tag create and store variables
either in the page context or in the tag body
<star:secondtag>
<p align="center">Date value retrieved from JSP
Tag :
<%= time %></p>
</star:secondtag>
Java Server Pages
Application example
Forum application
¤  Users register to the forum
¤  Several topics are available
¤  A message is related to a topic
¤  By selecting a topic one can visualize the list of messages
related to that topic
¤  Users can:
¤  Write a new message related to a specific topic
¤  Write a new message that answers to another message
Datamodel
Data model - SQL
CREATE TABLE user (
oid INTEGER NOT NULL PRIMARY KEY,
username VARCHAR(255),
password VARCHAR(255),
email VARCHAR(255));
CREATE TABLE message(
oid SERIAL NOT NULL PRIMARY KEY,
title VARCHAR(255),
body TEXT,
date DATE,
parentmessageoid INTEGER,
useroid INTEGER,
topicoid INTEGER);
CREATE TABLE topic(
oid INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(255),
description VARCHAR(255));
Application structure
topicList.jsp messageList.jsp
topicID
messageDetails.jsp
messageID
newMessage.jsp
includeinclude
CreateMessage.java
TopicList.java
Bean
TopicBean.java
Topic bean
public class TopicBean {!
private String oid;!
private String name;!
private String description;!
!!
public TopicBean(String oid, String name,
String description) {!
!this.setOid(oid);!
!this.setName(name);!
!this.setDescription(description);!
}!
!
// getters, setters… !!
}
Topic data
TopicBean.java
Topics retrieval (1)
public class TopicList extends HttpServlet {!
private Connection connection = null;!
!!
public void init(ServletConfig config) throws
ServletException {!
try {!
Class.forName("com.mysql.jdbc.Driver");!
!
ServletContext context = config.getServletContext
();!
String url = context.getInitParameter("dbUrl");!
String user = context.getInitParameter("dbUser");!
String password = context.getInitParameter
("dbPassword");!
connection = DriverManager.getConnection(url, user,
password); ! ! !!
}!
…Exceptions here…!
}!
Connection
to the
database
TopicList.java
Topics retrieval (2)
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {!
HttpSession session = request.getSession();!
! !!
String query="SELECT oid, name, description FROM topic"; !
PreparedStatement statement;!
try {!
statement = connection.prepareStatement(query);!
ResultSet result = statement.executeQuery();!
! ! !!
Vector<TopicBean> vector = new Vector<TopicBean>();!
while (result.next())!
vector.add(new TopicBean(result.getString("oid"),
result.getString("name"), result.getString("description"))); !
! !!
result.close();!
statement.close();!
! ! !!
session.setAttribute("topicPopulation", vector);!
}!
catch (SQLException e) {e.printStackTrace();}!
! !!
response.sendRedirect("topicList.jsp"); ! !!
}!
}
Store the topic
data in a vector of
beans
Store the beans in
the session
Visualize the list of topics
...!
<h3>Topics</h3>!
<ul>!
<% !
Vector<TopicBean> beans = (Vector<TopicBean>)
session.getAttribute("topicPopulation");!
if (beans == null) { %>!
No topics available.!
<%}!
else!
for (int i = 0; i < beans.size(); i++) {!
%>!
<li>!
<a href="messageList.jsp?tid=<%=beans.get
(i).getOid() %>”><%=beans.get(i).getName() %></a>:!
<%=beans.get(i).getDescription() %>!
</li>!
<%} %>!
</ul>
Retrieve the beans containing
the topic data from the session
Read the data of a
specific bean
topicList.jsp

More Related Content

What's hot (20)

Jsp(java server pages)
Jsp(java server pages)Jsp(java server pages)
Jsp(java server pages)
 
Jsp
JspJsp
Jsp
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp elements
Jsp elementsJsp elements
Jsp elements
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Jsp slides
Jsp slidesJsp slides
Jsp slides
 
Jsp
JspJsp
Jsp
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp Slides
Jsp SlidesJsp Slides
Jsp Slides
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Jsp basic
Jsp basicJsp basic
Jsp basic
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
 

Viewers also liked

Viewers also liked (11)

JSP
JSPJSP
JSP
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Java server pages
Java server pagesJava server pages
Java server pages
 
jsp MySQL database connectivity
jsp MySQL database connectivityjsp MySQL database connectivity
jsp MySQL database connectivity
 
Losseless
LosselessLosseless
Losseless
 
Video Streaming - 4.ppt
Video Streaming - 4.pptVideo Streaming - 4.ppt
Video Streaming - 4.ppt
 
Compression
CompressionCompression
Compression
 
Facebook Presentation
Facebook PresentationFacebook Presentation
Facebook Presentation
 
Facebook Powerpoint
Facebook PowerpointFacebook Powerpoint
Facebook Powerpoint
 

Similar to Java Server Pages

Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Ayes Chinmay
 
Java web application development
Java web application developmentJava web application development
Java web application developmentRitikRathaur
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...MathivananP4
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server PageVipin Yadav
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 

Similar to Java Server Pages (20)

JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
20jsp
20jsp20jsp
20jsp
 
Unit 4 1 web technology uptu
Unit 4 1 web technology uptuUnit 4 1 web technology uptu
Unit 4 1 web technology uptu
 
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
Ch. 7 beeing a jsp
Ch. 7 beeing a jsp     Ch. 7 beeing a jsp
Ch. 7 beeing a jsp
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
 
Being a jsp
Being a jsp     Being a jsp
Being a jsp
 
Jsp 01
Jsp 01Jsp 01
Jsp 01
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Jsp
JspJsp
Jsp
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 

More from Eleonora Ciceri

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfEleonora Ciceri
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfEleonora Ciceri
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfEleonora Ciceri
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfEleonora Ciceri
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfEleonora Ciceri
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfEleonora Ciceri
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - ExercisesEleonora Ciceri
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorEleonora Ciceri
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch frameworkEleonora Ciceri
 

More from Eleonora Ciceri (17)

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdf
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdf
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdf
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdf
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Trees
TreesTrees
Trees
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - Exercises
 
Doubly Linked Lists
Doubly Linked ListsDoubly Linked Lists
Doubly Linked Lists
 
Linked lists
Linked listsLinked lists
Linked lists
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introduction
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Client side scripting
Client side scriptingClient side scripting
Client side scripting
 
HTML5 - An introduction
HTML5 - An introductionHTML5 - An introduction
HTML5 - An introduction
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User Behavior
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch framework
 

Recently uploaded

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 

Recently uploaded (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 

Java Server Pages

  • 1. Java Server Pages Eleonora Ciceri ciceri@elet.polimi.it
  • 2. Servlets: what we know so far ¤  Interaction with user ¤  A servlet accepts HTTP requests ¤  HTML pages are returned as HTTP responses ¤  Page production ¤  Dynamic parts of the page: ¤  Depend on dynamic states (e.g., request parameters) ¤  Are filled with Java code which, when compiled, produced HTML code ¤  Static parts of the page are printed on the output as they are, without any modification
  • 3. Servlets: too many out.println… out.println(“<span style=“width:100%;”>”);! out.println(“Select an action:”);! out.println(“<ul>”);! out.println(“<li>Action 1</li>”);! out.println(“<li>Action 2</li>”);! out.println(“<li>Action 3</li>”);! out.println(“</ul>”);! out.println(“</span>”);! Difficult to read! Mixing presentation with content in Java code
  • 4. Servlets: are they a good idea? ¤  Complex code, not really readable ¤  HTML is mixed up with the Java Servlet code ¤  If HTML is printed, a lot of out.println() are used ¤  Presentation and logic are merged in a unique resource ¤  What if I want to change some of the aspects of the presentation style? Do I have to read and modify also the code used for producing dynamic content? ¤  Errors in the HTML code are difficult to be spotted
  • 5. Servlet modification Web designer •  Required to understand Java Programmer •  Required to write part of the page layout Problem: “mixing competences” How do we define which are the tasks that need to be developed by each person in the team? •  Train web designers for Java? •  Compromises about page layout?
  • 6. Java Server Pages (1) ¤  JSP integrates Java instructions in the HTML code. These instructions are used in order to compute parts of the page dynamically ¤  Difference with Java Servlet: a servlet integrates HTML in the Java code, JSP integrates Java code in the HTML ¤  This is an attempt to separate content from presentation ¤  Still some problems: one could integrate huge pieces of Java code… ¤  Advantages: learning is easier, more readable ¤  Disadvantage: still “primitive” solution (JSTL?)
  • 7. Java Server Pages (2) Servlets Java Server Pages Necessary to •  Write a class •  Write a configuration •  Know methods and syntax Necessary to •  Know HTML + a bit of Java No configuration (auto-compiled)
  • 8. Java Server Pages (3) Scriptlet •  1+ for each page •  JSP with 0 scriptlet = plain HTML page Template Here: whatever depends on dynamic behaviors (e.g., request parameters, db connections…) •  Modified by programmers Here: fixed page layout, presentation •  Modified by designersStatic parts Dynamic parts
  • 9. Java Server Pages (4) ¤  A JSP page is called template ¤  The Java code inserted in the template is called scriptlet ¤  Servlets are still useful! ¤  General usage ¤  Servlets are used to contain the logic ¤  JSP pages are used for the presentation of the results
  • 10. Mixing HTML, JSP and servlets (1) ¤  Example of application ¤  The user inserts the parameters of the query he wants to perform in an HTML form ¤  Results are retrieved from the database and displayed
  • 11. Mixing HTML, JSP and servlets (2) HTML form •  No dynamic parts •  No need to use server-side scripting Servlet •  Database connection •  Retrieve results JSP page •  Display the results Logic Presentation
  • 12. JSP interpretation ¤  A Java Server Page does NOT produce HTML code as an output ¤  JSP belongs to the server-side programming techniques, thus it runs on the server WebContent folder Translated into what?
  • 13. JSP goes to servlets Template HTML code Scriptlets HTML code Interpreted by the server ¤  The template is interpreted by the server in order to generate a page made of HTML code ¤  The browser receives just HTML code ¤  This hides the scripts, hackers would not see them Servlet Automatically generated
  • 14. How do we produce HTML code?
  • 15. JSP: behind the scenes (1) ¤  The server automatically creates, compiles, loads and runs a special servlet to generate the page’s content ¤  The static portions of the HTML page are generated by the servlet by using out.println() ¤  The dynamic portions are included directly ¤  Every time there is a change in the JSP page, the servlet is automatically recompiled ¤  First time: longer periods of time in order to create the servlet ¤  Other times: shorter periods of time in order to add pieces to the servlet
  • 16. JSP: behind the scenes (2) 1)  Start server (load every JSP page in WebContent) WebContent folder 2) Translate (each JSP page is automatically translated into a Servlet) Automatic mapping between the requested page and the created servlet
  • 17. JSP: behind the scenes (3) 1)  Request to the JSP page (user requires to access to the page) 2) Look for the mapping (the server looks for the mapping between the requested JSP page and the created servlet) 3) Compute the response (the servlet handles the request and returns the response) HTML code
  • 18. JSP: behind the scenes (4) 1)  Modify the JSP page (with any modification – either on static or dynamic parts) 2) Look for the mapping (the server looks for the mapping between the modified JSP page and the created servlet) 3) Modify the servlet (the update is reflected on the servlet)
  • 19. Plain HTML or JSP? ¤  Allowed ¤  Create a JSP page with 0+ scriptlets ¤  Suggested ¤  Create a JSP page with 1+ scriptlets ¤  To be avoided ¤  Create a JSP page with 0 scriptlets JSP page with 0 scriptlets (= HTML page) Unaltered HTML code Translation OVERHEAD
  • 20. Using Java Server Pages ¤  Each block of servlet code is surrounded by a leading <% tag and a closing %> tag ¤  A scriptlet can use predefined variables: ¤  request: the servlet request(HttpServletRequest) ¤  response: the servlet response (HttpServletResponse) ¤  out: the output writer (PrintWriter) ¤  in: the input reader (BufferedReader)
  • 21. HelloWorld JSP page <html>! <head><title>Hello, World!</title></head>! <body>! !<% ! !if (request.getParameter("name") == null) ! out.println("Hello, World!");! !else! out.println("Hello, " + request.getParameter ("name") + "!"); !! !%>! </body>! </html> Retrieve a parameter from the request (here: query string)
  • 22. Scope variables (1) Page scope Request scope Session scope Application scope
  • 23. Scope variables (2) ¤  page: the data can be retrieved from any of the parts of the page ¤  request: the data can be retrieved from all the pages that analyse the same HTTP request (<jspforward>) ¤  session: the data can be retrieved from any template required by the same user (at least until the session is valid) ¤  application: the data can be retrieved from any of the templates of the same web application
  • 24. Scope variables (3) ¤  Set an attribute of a variable ¤  variable.setAttribute(String name, Object value) ¤  Read an attribute from a variable ¤  Object o = variable.getAttribute(String name)
  • 25. JSP syntax (1) ¤  Comment: <%-- comment --%> ¤  Expression: <%= expression %> ¤  The expression is computed, translated into a String and then displayed ¤  Declaration: <%! declaration %> ¤  How to define attributes and methods that will be copied in the servlet ¤  Action: <jsp:actionName action /> ¤  XML tag that invokes Web server functionalities
  • 26. JSP syntax (2) ¤  Directive: <%@ directiveName attrName = “attrValue”%> ¤  Allows to use other servlet aspects ¤  Examples of directives: ¤  <%@ page session=“false”%> disables the session tracking ¤  <%@ page errorPage=“error.jsp”%> sets the page URL that will be used in case of error ¤  <%@ page import=“java.lib.*”%> imports a Java library
  • 27. HelloWorld JSP: refactored <html>! <head><title>Hello, World!</title></head>! <body>! !Hello, <%=getName(request) %>!! </body>! </html>! ! <%!! private static final String DEFAULTNAME = "World";! private static final String getName(HttpServletRequest request) {! String name = request.getParameter("name");! if (name == null)! !return DEFAULTNAME;! else! !return name;! }! %> JSP declaration
  • 29. Database connection: user input <html>! <head><title>Retrieve phone number</title></head>! <body>! !<form method=POST action="DatabaseConnection.jsp">! Insert the name of the employee here:! <input type="text" name="employeeName"/>! <input type="submit"/>! !</form>! </body>! </html>
  • 30. Database connection: data retrieval (1) <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>! <%@ page import="java.sql.*" %>! ! <%! String name = request.getParameter("employeeName");! Class.forName("com.mysql.jdbc.Driver");! Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ test", "root", "");! PreparedStatement statement = connection.prepareStatement("SELECT * FROM employees WHERE name=?");! statement.setString(1,name);! ResultSet resultSet = statement.executeQuery();! %>! ! <html>! <head><title>Phone numbers</title></head>! <body>! Phone numbers for the required user:! <% if (!resultSet.isBeforeFirst()) { %>! There are no numbers!! <% ! }! Check if there are no results Prepare query and execute it
  • 31. Database connection: data retrieval (2) else {%>! <table>! <tr>! <td><font size="+1">Name</font></td>! <td><font size="+1">Phone</font></td>! </tr>! <% while (resultSet.next()) { %>! <tr>! <td><%= resultSet.getString("name") %></td>! <td><%= resultSet.getString("phone") %></td>! </tr>! <% } %>! </table>! <% } %>! </body>! </html>! ! <%! resultSet.close();! statement.close();! connection.close();! %> Print each tuple in the result set Close connection and statement
  • 32. Mixing JSP and Servlets NewEmployee.jsp CreateEmployee Name Phone NewEmployeeCreated.jsp Store new employee and retrieve ID Retrieve data about the created object
  • 33. Insert new employee data <html>! <head><title>Create a new employee</title></head>! <body>! <form method=POST action="CreateEmployee">! !Name: <input type="text" name="name"/>! !<br />! !Phone: <input type="text" name="phone"/>! !<br />! !<input type="submit"/>! </form>! </body>! </html> NewEmployee.jsp
  • 34. Store the employee in the database (1) public class CreateEmployee extends HttpServlet {! Connection connection;! !! public void init(ServletConfig config) throws ServletException { ! ServletContext context = config.getServletContext(); ! String loginUser = context.getInitParameter("dbUser");! String loginPasswd = context.getInitParameter("dbPassword");! String loginUrl = context.getInitParameter("dbURL"); ! ! try {! Class.forName("com.mysql.jdbc.Driver");! connection = DriverManager.getConnection(loginUrl, loginUser, loginPasswd);! }! catch (ClassNotFoundException ex) {! System.err.println("ClassNotFoundException: " + ex.getMessage());! throw new ServletException("Class not found Error");! }! catch (SQLException ex) {! System.err.println("SQLException: " + ex.getMessage());! }! }! CreateEmployee Get parameters from the context Get the connection
  • 35. Store the employee in the database (2) public void doPost(HttpServletRequest request, HttpServletResponse response)! !throws IOException, ServletException {! String id = ””;! try {! synchronized(connection) {! String query = "INSERT INTO employees (name, phone) VALUES (?,?)";! PreparedStatement statement = connection.prepareStatement(query);! statement.setString(1, (String) request.getParameter("name"));! statement.setString(2, (String) request.getParameter("phone"));! statement.executeUpdate(); ! statement.close();! ! !! query = "SELECT id FROM employees WHERE name=? AND phone=?";! statement = connection.prepareStatement(query);! statement.setString(1, (String) request.getParameter("name"));! statement.setString(2, (String) request.getParameter("phone"));! ResultSet resultSet = statement.executeQuery();! resultSet.next();! id = resultSet.getString("id");! }! } ! CreateEmployee Insert employee in the database Retrieve the employee ID
  • 36. Store the employee in the database (3) catch(Exception ex) { ! ex.printStackTrace();! return;! }! response.sendRedirect("NewEmployeeCreated.jsp?id=" + id);! } ! public void destroy() {! try {! if (connection != null){! connection.close();! }! } ! catch (SQLException sqle) {}! }! } CreateEmployee Send redirect to the second JSP page
  • 37. Report the results (1) <%@ page import="java.sql.*,java.util.*,java.text.*" %>! <%Connection connection = null; ResultSet resultSet = null;! ServletContext context = config.getServletContext(); ! String loginUser = context.getInitParameter("dbUser");! String loginPasswd = context.getInitParameter("dbPassword");! String loginUrl = context.getInitParameter("dbURL");! ! String name = "”; String phone = "”;! ! try {! Class.forName("com.mysql.jdbc.Driver");! connection = DriverManager.getConnection(loginUrl, loginUser, loginPasswd); ! }! catch (ClassNotFoundException ex) {! System.err.println("ClassNotFoundException: " + ex.getMessage());! throw new ServletException("Class not found Error");! }! catch (SQLException ex) {! System.err.println("SQLException: " + ex.getMessage());! }! String id = request.getParameter("id");! Retrieve data about the connection to the database Retrieve the id of the created employee from the request Create database connection NewEmployeeCreated.jsp
  • 38. Report the results (2) if ((id != null) && (id != "")) { ! try {! String query = "SELECT name,phone FROM employees WHERE id = ?";! PreparedStatement statement = connection.prepareStatement (query);! statement.setInt(1, new Integer(id));! resultSet = statement.executeQuery();! resultSet.next();! name = resultSet.getString("name");! phone = resultSet.getString("phone");! }! catch (Exception e) {! e.printStackTrace();! }! } ! %>! Retrieve data about the inserted employee NewEmployeeCreated.jsp
  • 39. Report the results (3) <html>! <head><title>New employee created!</title></head>! <body>! New employee created.! <ul>! <li> Name: <%=name %></li>! <li> Phone: <%=phone %></li>! </ul>! </body>! </html> Print the values that were inserted in the database NewEmployeeCreated.jsp
  • 40. JSP include (1) ¤  A JSP page can be fractioned in parts ¤  Each part could represent a specific functionality ¤  Each part can be reused in other JSP pages Connection.jsp (performs the connection to databases) SearchEmployee.jsp InsertEmployee.jsp
  • 41. JSP include (2) ¤  How to include (mode 1) ¤  <%@ include file=“path” %> ¤  The code is included when the servlet is created ¤  If the included page is modified, the including pages need to be recompiled ¤  The variables that are present in the included page are visible also in the including page
  • 42. JSP include (3) ¤  How to include (mode 2) ¤  <jsp:include page=“path” flush=“true”/> ¤  The page is included at request time: no need to recompile ¤  The output of the resource is included in the caller ¤  Caller page and called page are independent, thus in order to pass parameters between them: <jsp:include page=“path”> <jsp:param name=“paramName” value=“paramValue”/> </jsp:include>
  • 43. JSP redirect vs. JSP forward ¤  The forward action allows one to send the request to another resource ¤  The redirect is performed in a transparent way: the browser is not notified ¤  <jsp:forward page=“/path.jsp”/> ¤  The request variable is identical to the one sent to the source page ¤  The redirect action performed on HttpServletResponse asks to the client to send a new request in order to obtain the new page ¤  response.sendRedirect(String location)
  • 44. Disadvantages of scriptlets ¤  Writing the scriptlets in the page makes the page difficult to be read and understood by those who don’t know the Java language ¤  Content developers ¤  Designers
  • 45. So many questions… ¤  Mixing competences ¤  Who edits the Java code? ¤  Who edits the presentation? ¤  How to divide the roles? ¤  XML validation ¤  How can we validate the JSP templates? (No valid XML: it includes no-XML code)
  • 46. Solution: Java beans ¤  A Java bean is a reusable class with methods and variables that follow some naming conventions, so as to make them easily accessible ¤  Constructor: without parameters ¤  Getter and setter for each attribute ¤  A Java bean is used so as to perform ad-hoc operations ¤  JSP uses natively the Java beans ¤  They can be included in the scopes ¤  Their attributes can be set automatically
  • 47. Java beans: usage ¤  Inclusion ¤  <jsp:useBean id=“name” scope=“page|request| session|application” class=“className” type=“typeName”/> ¤  Handling parameters ¤  <jsp:setProperty name=“beanName” property=“propertyName” param=“paramName”/> ¤  <jsp:setProperty name=“beanName” property=“propertyName” value=“constant”/> ¤  <jsp:getProperty name=“beanName” property=“propertyName”/> From the request Constant value
  • 48. A simple Java bean public class HelloBean {! private String name = "World";! private String place = "empty";! !! public void setName(String name) {! this.name = name;! }! public String getName(){! return this.name;! }! public void setPlace(String place) {! this.place = place;! }! public String getPlace() {! return this.place;! }! } Properties of the bean
  • 49. Accessing to the bean <%@page import="it.polimi.tiw.jsp.examples.beans.HelloBean" %>! <jsp:useBean id="hello" ! class="it.polimi.tiw.jsp.examples.beans.HelloBean">! <jsp:setProperty name="hello" property="name" param="userName"/>! </jsp:useBean>! ! <html>! <head><title>Hello, World!</title></head>! <body>! !Hello, <jsp:getProperty name="hello" property="name"/>!! </body>! </html> Bean name Bean name Name of the property that will be modified Parameter of the query string that will be used to set the property Bean name Name of the property that will be read from the bean
  • 50. Java beans and session scope ¤  When a bean is stored in the session, it can be accessed from any page that uses that session Java Bean Session Read information
  • 51. Store bean in session <%@page import="it.polimi.tiw.jsp.examples.beans.HelloBean" %>! <jsp:useBean id="hello" class="it.polimi.tiw.jsp.examples.beans.HelloBean" scope="session">! <jsp:setProperty name="hello" property="name" param="userName"/>! <jsp:setProperty name="hello" property="place" value="Como"/>! </jsp:useBean>! ! <html>! <head><title>Hello, World!</title></head>! <body>! Hello, <jsp:getProperty name="hello" property="name"/>!! <br />! Place (stored in session): <jsp:getProperty name="hello" property="place"/>! <form method=POST action="HelloWorldBeanSession2.jsp">! <input type="submit"/>! </form>! </body>! </html> Retrieve from the query string Set the property equal to a fixed value When instantiated, the bean is stored in the session. •  Properties can be retrieved from the session
  • 52. Read information from the session <%@page import="it.polimi.tiw.jsp.examples.beans.HelloBean" %>! <jsp:useBean id="hello" ! class="it.polimi.tiw.jsp.examples.beans.HelloBean" scope="session"/>! ! <html>! <head><title>Hello, World!</title></head>! <body>! Name in session: <jsp:getProperty property="name" name="hello"/>! </body>! </html> Retrieve the bean from the session Read the property from the bean
  • 54. Tag libraries: Custom actions (1) ¤  We can define custom action libraries using the JSP tag extension ¤  A custom action is invoked by using a custom tag in a JSP page ¤  A tag library is a collection of custom tags ¤  The tag libraries are used in order to hide the Java code in the mark-up language ¤  Each tag is associated with a Java class, called tag handler, that implements a specific interface: javax.servlet.jsp.tagext.Tag
  • 55. Tag libraries: Custom actions (2) ¤  The Tag Library Descriptor (TLD) is an XML file that keeps track of the associations between classes and tags ¤  Example: <%@ taglib uri=“myTagLibrary.tld” prefix=“mtl”%>! <tr>! <td>! Cost of the transaction: <mtl:write scope=“session” name=“transactionValue”/>! </td>! </tr>!
  • 56. Tag libraries: Advantages ¤  The JSP pages are built out of reusable components ¤  Increase productivity ¤  Separate Java programmers (who will write the tag libraries) and the Web application designers ¤  Features ¤  Configuration using attributes ¤  Access to JSP variables ¤  Communication between different tags
  • 57. How does it work? Translates into <tag> JSP page Each time <tag> is encountered in the JSP page, it is translated into a call to one of the methods in Tag Handler
  • 58. How to build a custom tag ¤  In order to build a custom tag: ¤  Define a tag handler, i.e., a Java class that encapsulate the logic of the tag ¤  Define a TLD, i.e., an XML file that stores the coupling between tag handlers and tags ¤  Types of custom tags: ¤  javax.servet.jsp.tagext.Tag: generic tags ¤  javax.servlet.jsp.tagext.BodyTag: tag that write on nested elements
  • 59. Custom tag: methods (1) ¤  The main methods are doStartTag() and doEndTag() ¤  They are invoked on the tag handler ¤  Between the two invocations the tag handler holds a state that must be preserved ¤  After the doEndTag() call, the tag is available for further invocations Default values for the properties Initialized properties (pageContext, parent, AttSet) Hold state new() setPageContext() setParent() setters() doStartTag() doEndTag() release()
  • 60. Custom tag: methods (2) ¤  Field summary ¤  EVAL_BODY_INCLUDE: evaluate body into existing out stream ¤  EVAL_PAGE: continue evaluating the page ¤  SKIP_BODY: skip body evaluation ¤  SKIP_PAGE: skip the rest of the page ¤  doStartTag() returns EVAL_BODY_INCLUDE is the tag content has to be executed, otherwise it returns SKIP_BODY ¤  doEndTag() returns EVAL_PAGE is the rest of the page has to be executed and SKIP_PAGE otherwise
  • 61. Simple tag example: handler (1) public class SimpleTagHandler implements Tag, Serializable {! !private PageContext pc = null;! !private Tag parent = null;! !private String name = null;! !! !public void setPageContext(PageContext pc) {! ! !this.pc = pc;! !}! !! !public void setParent(Tag parent) {! ! !this.parent = parent;! !}! !! !public void setName(String name) {! ! !this.name = name;! !} Declaration of page context Attributes Attribute setters Page context setters
  • 62. Simple tag example: handler (2) !public int doStartTag() throws JspException {! try {! if (name != null)! ! !pc.getOut().write("Hello, " + name + "!");! else! ! !pc.getOut().write("You didn't enter your name");! }! catch (IOException e) {! throw new JspTagException("An IO exception occurred");! }! return SKIP_BODY;! !}! !public int doEndTag() throws JspException {! return EVAL_PAGE;! !}! !public void release() {! pc = null;! parent = null;! name = null;! !}! } When the tag is evaluated, printing the name on the output is requested Once the tag is evaluated, the body does not have to be evaluated Then, the page evaluation is continued Then the tag is released, all the properties are set to an undefined value
  • 63. Simple tag example: TLD <taglib>! <tlibversion>1.0</tlibversion>! <jspversion>1.1</jspversion>! <shortname>MyTagLibrary</shortname>! <info>My Tag Library</info>! <tag>! <name>simple</name>! <tagclass>it.polimi.tiw.jsp.taglib.handlers.SimpleTagHandler</ tagclass>! <bodycontent>empty</bodycontent>! <info>This tag prints a name</info>! <attribute>! <name>name</name>! <required>false</required>! </attribute>! </tag>! </taglib> The name that will be used to reference the tag The attribute that can be used in the tag. It is not required, i.e., if not specified a default behavior will be applied
  • 64. Simple tag example: JSP page <%@ taglib uri="/WEB-INF/MyTagLibrary.tld" prefix="mtl" %>! <html>! !<head>! ! !<title>Simple Tag Example</title>! !</head>! !<body>! ! !Name: <mtl:simple name="TIWuser"/>! !</body>! </html> Include the tag library and assign the prefix mtl to it Use the tag by specifying the attribute name
  • 65. Tags and variables ¤  It is possible to make the tag create and store variables either in the page context or in the tag body <star:secondtag> <p align="center">Date value retrieved from JSP Tag : <%= time %></p> </star:secondtag>
  • 67. Forum application ¤  Users register to the forum ¤  Several topics are available ¤  A message is related to a topic ¤  By selecting a topic one can visualize the list of messages related to that topic ¤  Users can: ¤  Write a new message related to a specific topic ¤  Write a new message that answers to another message
  • 69. Data model - SQL CREATE TABLE user ( oid INTEGER NOT NULL PRIMARY KEY, username VARCHAR(255), password VARCHAR(255), email VARCHAR(255)); CREATE TABLE message( oid SERIAL NOT NULL PRIMARY KEY, title VARCHAR(255), body TEXT, date DATE, parentmessageoid INTEGER, useroid INTEGER, topicoid INTEGER); CREATE TABLE topic( oid INTEGER NOT NULL PRIMARY KEY, name VARCHAR(255), description VARCHAR(255));
  • 71. Topic bean public class TopicBean {! private String oid;! private String name;! private String description;! !! public TopicBean(String oid, String name, String description) {! !this.setOid(oid);! !this.setName(name);! !this.setDescription(description);! }! ! // getters, setters… !! } Topic data TopicBean.java
  • 72. Topics retrieval (1) public class TopicList extends HttpServlet {! private Connection connection = null;! !! public void init(ServletConfig config) throws ServletException {! try {! Class.forName("com.mysql.jdbc.Driver");! ! ServletContext context = config.getServletContext ();! String url = context.getInitParameter("dbUrl");! String user = context.getInitParameter("dbUser");! String password = context.getInitParameter ("dbPassword");! connection = DriverManager.getConnection(url, user, password); ! ! !! }! …Exceptions here…! }! Connection to the database TopicList.java
  • 73. Topics retrieval (2) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {! HttpSession session = request.getSession();! ! !! String query="SELECT oid, name, description FROM topic"; ! PreparedStatement statement;! try {! statement = connection.prepareStatement(query);! ResultSet result = statement.executeQuery();! ! ! !! Vector<TopicBean> vector = new Vector<TopicBean>();! while (result.next())! vector.add(new TopicBean(result.getString("oid"), result.getString("name"), result.getString("description"))); ! ! !! result.close();! statement.close();! ! ! !! session.setAttribute("topicPopulation", vector);! }! catch (SQLException e) {e.printStackTrace();}! ! !! response.sendRedirect("topicList.jsp"); ! !! }! } Store the topic data in a vector of beans Store the beans in the session
  • 74. Visualize the list of topics ...! <h3>Topics</h3>! <ul>! <% ! Vector<TopicBean> beans = (Vector<TopicBean>) session.getAttribute("topicPopulation");! if (beans == null) { %>! No topics available.! <%}! else! for (int i = 0; i < beans.size(); i++) {! %>! <li>! <a href="messageList.jsp?tid=<%=beans.get (i).getOid() %>”><%=beans.get(i).getName() %></a>:! <%=beans.get(i).getDescription() %>! </li>! <%} %>! </ul> Retrieve the beans containing the topic data from the session Read the data of a specific bean topicList.jsp