Java Server Pages

74
Java Server Pages Eleonora Ciceri [email protected]

Transcript of Java Server Pages

Page 1: Java Server Pages

Java Server Pages Eleonora Ciceri

[email protected]

Page 2: Java Server Pages

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

Page 3: Java Server Pages

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

Page 4: Java Server Pages

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

Page 5: Java Server Pages

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?

Page 6: Java Server Pages

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

Page 7: Java Server Pages

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)

Page 8: Java Server Pages

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

designers Static parts

Dynamic parts

Page 9: Java Server Pages

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

Page 10: Java Server Pages

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

Page 11: Java Server Pages

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

Page 12: Java Server Pages

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?

Page 13: Java Server Pages

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

Page 14: Java Server Pages

How do we produce HTML code?

Page 15: Java Server Pages

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

Page 16: Java Server Pages

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

Page 17: Java Server Pages

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

Page 18: Java Server Pages

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)

Page 19: Java Server Pages

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

Page 20: Java Server Pages

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)

Page 21: Java Server Pages

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)

Page 22: Java Server Pages

Scope variables (1)

Page scope Request

scope Session scope

Application scope

Page 23: Java Server Pages

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

Page 24: Java Server Pages

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)

Page 25: Java Server Pages

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

Page 26: Java Server Pages

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

Page 27: Java Server Pages

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

Page 28: Java Server Pages

Database connection

InsertEmployeeName.html DatabaseConnection.jsp

Name Phone

John 89398544

Sam 83478534

Page 29: Java Server Pages

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>

Page 30: Java Server Pages

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

Page 31: Java Server Pages

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

Page 32: Java Server Pages

Mixing JSP and Servlets

NewEmployee.jsp

CreateEmployee

Name Phone

NewEmployeeCreated.jsp

Store new employee and retrieve ID

Retrieve data about the created object

Page 33: Java Server Pages

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

Page 34: Java Server Pages

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

Page 35: Java Server Pages

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

Page 36: Java Server Pages

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

Page 37: Java Server Pages

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

Page 38: Java Server Pages

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

Page 39: Java Server Pages

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

Page 40: Java Server Pages

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

Page 41: Java Server Pages

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

Page 42: Java Server Pages

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>

Page 43: Java Server Pages

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)

Page 44: Java Server Pages

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

Page 45: Java Server Pages

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)

Page 46: Java Server Pages

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

Page 47: Java Server Pages

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

Page 48: Java Server Pages

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

Page 49: Java Server Pages

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

Page 50: Java Server Pages

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

Page 51: Java Server Pages

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

Page 52: Java Server Pages

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

Page 53: Java Server Pages

JSP Tag Library

Page 54: Java Server Pages

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

Page 55: Java Server Pages

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>!

Page 56: Java Server Pages

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

Page 57: Java Server Pages

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

Page 58: Java Server Pages

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

Page 59: Java Server Pages

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

Page 60: Java Server Pages

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

Page 61: Java Server Pages

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

Page 62: Java Server Pages

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

Page 63: Java Server Pages

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

Page 64: Java Server Pages

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

Page 65: Java Server Pages

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>

Page 66: Java Server Pages

Java Server Pages Application example

Page 67: Java Server Pages

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

Page 68: Java Server Pages

Da

ta m

od

el

Page 69: Java Server Pages

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

Page 70: Java Server Pages

Application structure

topicList.jsp messageList.jsp

topicID

messageDetails.jsp

messageID

newMessage.jsp

include include

CreateMessage.java

TopicList.java

Bean

TopicBean.java

Page 71: Java Server Pages

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

Page 72: Java Server Pages

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

Page 73: Java Server Pages

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

Page 74: Java Server Pages

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