JavaServer Pages (JSP)acf/tj/slides/jsp_slide_en.pdf · JavaServer Pages (JSP) The standard...

Post on 28-Jul-2020

17 views 0 download

Transcript of JavaServer Pages (JSP)acf/tj/slides/jsp_slide_en.pdf · JavaServer Pages (JSP) The standard...

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– 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 is conform to

View – Helper design pattern

JavaServer Pages (JSP)

● The standard 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.*;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>"); }}

implements javax.servlet.Servlet

JSP Syntax

<%-- Hello World example, not again ... --%>

<%@ page language="java" contentType="text/html; pageEncoding="UTF-8"%>

<html><head> <title>First JSP</title> </head>

<%@ page import="java.util.Date" %><%@ include file="header.html" %>

<%! String message = "Hello World"; %>

<body><% for(int i=1; i<=4; i++) { out.println("<H" + i + ">" + message + "</H" + i + ">"); }%><!-- Page generated at: <%= new Date() %> --></body></html>

JSP Directives

JSP Expression

JSP Comment

JSP Declaration

JSP Scriptlet

JSP Elements

Element Standard Syntax XML Syntax

Comment <%--.. --%> <!-- .. -->

Declarations <%! ..%> <jsp:declaration> .. </jsp:declaration>

Directives <%@ include .. %><%@ page .. %><%@ taglib .. %>

<jsp:directive.include .. /><jsp:directive.page .. />xmlns:prefix="tag library URL"

Expressions <%= ..%> <jsp:expression> .. </jsp:expression>

Scriptles <% ..%> <jsp:scriptlet> .. </jsp:scriptlet>

Standard actions

<jsp:action> .. </jsp:action><jsp:useBean> .. </jsp:useBean><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 Scoperequest 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><% // 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><p>Sorry, an error occurred.</p><p>Here is the exception stack trace: </p><pre> <% exception.printStackTrace(response.getWriter()); %></pre></body></html>

Error Handler

Some JSP Page

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;

public class Person {

private String name;

private BigDecimal salary;

...

public String getName() {

return name;

}

public void setName(String name) {

this.nume = nume;

}

...

}

Name is a property

Person is a bean

Standard Actions for JavaBeans

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"/>

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

Request Chaining

The first JSP of the chain maps the input elements of the form to the properties of the bean.

<jsp:setProperty name="pers" property="name" value="*" />

Model – View – Controller