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
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)
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
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
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
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));
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