JavaServer Pages (JSP)
The Context ● The Presentation Layer of a Web App – the graphical (web) user interface – frequent design changes – usually, dynamically generated HTML pages ● Should we use servlets? → No (not directly) – difficult to develop and maintain (the view) – lack of flexibility – lack of role separation: design → designer
Example: HelloServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = new PrintWriter(response.getWriter()); out.println("<html>" + "<head><title>Welcome!</title></head>" + "<body>" + "<h1><font color=\"red\"> Welcome! </font></h1>" + "<h2>Current date and time:" + new java.util.Date() + " </h2>" + "</body>" + "</html>"); out.close(); } }
Example: hello.jsp <html> <head> <title>Welcome!</title> </head> <body> <h1><font color="red"> Welcome! </font></h1> <h2>Current date and time: <%= new java.util.Date() %> </h2> </body> </html>
The Concept Standard component to create the presentation, that conforms to View – Helper design pattern
JavaServer Pages (JSP) ● The “classical” solution to create web content easily that has both static and dynamic components → Web pages ● Provides a natural, declarative, presentation oriented approach to creating static content → Templates ● Are based on and benefit from all the dynamic capabilities of Java Servlet technology → Every JSP is actually a servlet ● A first (small) step towards the role separation
The main features of JSP ● A JSP page is a text document that contains: – static data (template) (HTML, SVG, WML, etc.) – JSP elements , which construct the content ● JSP elements may be: – JSP tags – scriptles (code sequences written in Java...) ● JSP uses an expression language for accessing server-side objects ● The source files may be .jsp, .jspf, .jspx
The Life Cycle of a JSP Page
Translation Phase //Example taken from Apache Tomcat application server //This is the source file of the servlet generated for hello.jsp package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; implements javax.servlet.Servlet import javax.servlet.jsp.*; public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { ... public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { ... out.write("<HTML>"); ... out.write("</HTML>"); } }
JSP Syntax JSP Comment <%-- Hello World example, not again ... --%> <%@ page language="java" contentType="text/html; pageEncoding="UTF-8"%> <html> <head> <title>First JSP</title> </head> JSP Directives <%@ page import="java.util.Date" %> <%@ include file="header.html" %> JSP Declaration <%! String message = "Hello World"; %> <body> <% for(int i=1; i<=4; i++) { out.println("<H" + i + ">" + message + "</H" + i + ">"); JSP Scriptlet } %> <!-- Page generated at: <%= new Date() %> --> JSP Expression </body> </html>
JSP Elements Element Standard Syntax XML Syntax Comment <%--.. --%> <!-- .. --> Declarations <%! ..%> <jsp:declaration> .. </jsp:declaration> Directives <%@ include .. %> <jsp:directive.include .. /> <%@ page .. %> <jsp:directive.page .. /> <%@ taglib .. %> xmlns:prefix="tag library URL" Expressions <%= ..%> <jsp:expression> .. </jsp:expression> Scriptles <% ..%> <jsp:scriptlet> .. </jsp:scriptlet> Standard <jsp: action > .. </jsp: action > <jsp:useBean> .. </jsp:useBean> actions <jsp:forward> .. </jsp:forward> <jsp:include> .. </jsp:include> .. Everything else besides the JSP elements is considered static content and it appears unaltered in the output. <html> <!-- this is static content --> Hello world! </html>
Scopes
JSP Objects Object Type Scope request HttpServletRequest REQUEST response HttpServletResponse PAGE application ServletContext APPLICATION pageContext PageContext PAGE out JSPWriter PAGE config ServletConfig PAGE page (this) HttpJspPage PAGE session HttpSession SESSION exception Throwable PAGE
Examples of using JSP objects Get a parameter from the request <%= request.getParameter("nume") %> Get the IP address of the client and the type of his browser <%= request.getRemoteAddr() %> <%= request.getHeader("user-agent") %> <% session.setAttribute("user", "Duke"); synchronized (application) { application.setAttribute("sharedObject", new Object()); } out.println("<h1> Hello </h1>"); response.sendRedirect("http://www.google.ro"); response.sendError(404); %>
Exception Handling <%@ page errorPage="ShowError.jsp" %> <html> <head> <title>Error Handling Example</title> </head> <body> <% Some JSP Page // Throw an exception to invoke the error page int x = 1; if (x == 1) { throw new RuntimeException("Boom!"); } %> </body> </html> <%@ page isErrorPage="true" %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Opps...</h1> Error Handler <p>Sorry, an error occurred.</p> <p>Here is the exception stack trace: </p> <pre> <% exception.printStackTrace(response.getWriter()); %> </pre> </body> </html>
JSP Actions ● An action encapsulates some logic, that will be accesible using an XML tag ● The goal is: – to eliminate scriptlets from a page – to promote reusability ● There are two types of JSP actions: – standard, of the form <jsp: action …/> – custom
JSP Standard Actions ● Accessing the “Data Layer” (The Model) – <jsp:useBean> – <jsp:setProperty> – <jsp:getProperty> ● Dispatching the request – <jsp:forward> – <jsp:include> ● ...
JavaBean Components ● Reusable components that encapsulate some data exposed as properties ● Described by classes that are public , serializable and have a default constructor ● JavaBeans are used to store information at a specific scope : request, session, etc. ● JSP Pages and Servlets will store and retrieve data using JavaBeans ● “The Model”
Example of a JavaBean package test; Person is a bean public class Person { private String name; private BigDecimal salary; ... public String getName() { Name is a property return name; } public void setName(String name) { this.nume = nume; } ... }
Standard Actions for JavaBeans ( too ugly, don’t use it ) Creating/Accessing an instance of the bean <jsp:useBean id="pers" class="test.Person" scope="session" > pers.setName("Duke"); ... </jsp:useBean> Accessing the properties of the bean <jsp:setProperty name="pers" property="name" value="Joe" /> Person, your name is: <jsp:getProperty name="pers" property="name"/> Person, your name is: ${pers.name} A (small) step towards accesing the data layer without writing Java code...
Model 1
Using a JavaBean in a JSP <html> <jsp:useBean id="pers" scope="request" class="test.Person" /> <%-- We use introspection to populate the bean --%> <jsp:setProperty name="pers" property="*" /> <% if ( request.getParameter("name") == null ) { %> <form method="get"> Nume: <input type="text" name="name" size="25" /> <br/> <input type="submit" value="OK"/> </form> <% } else { <!-- If we decide not to use introspection: <jsp:setProperty name="pers" property="name" value="<%= request.getParameter("name") %>" /> --> Salut, <jsp:getProperty name="pers" property="name" />! <% } %> </html>
Using a JavaBean in a servlet public void doGet (HttpServletRequest request, HttpServletResponse response) { //Get the JavaBean from its scope Person person = (Person) request.getAttribute("pers"); // Use the JavaBean person.setName("Joe"); //Eventually, forward the request getServletContext().getRequestDispatcher("result.jsp") .forward(request, response); }
<jsp:forward page=”...”/>
<jsp:include page=”...”/> <%@ include … %> directive ≠ <jsp: include …/> action
Recommend
More recommend