JavaServer Pages (JSP) The Context The Presentation Layer of a Web - - PowerPoint PPT Presentation

javaserver pages jsp
SMART_READER_LITE
LIVE PREVIEW

JavaServer Pages (JSP) The Context The Presentation Layer of a Web - - PowerPoint PPT Presentation

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)


slide-1
SLIDE 1

JavaServer Pages (JSP)

slide-2
SLIDE 2

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

slide-3
SLIDE 3

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

  • ut.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>");

  • ut.close();

} }

slide-4
SLIDE 4

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>

slide-5
SLIDE 5

The Concept

Standard component to create the presentation, that conforms to View – Helper design pattern

slide-6
SLIDE 6

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
  • riented 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
slide-7
SLIDE 7

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
slide-8
SLIDE 8

The Life Cycle of a JSP Page

slide-9
SLIDE 9

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 { ...

  • ut.write("<HTML>");

...

  • ut.write("</HTML>");

} } implements javax.servlet.Servlet

slide-10
SLIDE 10

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++) {

  • ut.println("<H" + i + ">" + message + "</H" + i + ">");

} %> <!-- Page generated at: <%= new Date() %> --> </body> </html> JSP Directives JSP Expression JSP Comment JSP Declaration JSP Scriptlet

slide-11
SLIDE 11

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>

slide-12
SLIDE 12

Scopes

slide-13
SLIDE 13

JSP Objects

Object Type Scope

request HttpServletRequest REQUEST response HttpServletResponse PAGE application ServletContext APPLICATION pageContext PageContext PAGE

  • ut

JSPWriter PAGE config ServletConfig PAGE page (this) HttpJspPage PAGE session HttpSession SESSION exception Throwable PAGE

slide-14
SLIDE 14

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

  • ut.println("<h1> Hello </h1>");

response.sendRedirect("http://www.google.ro"); response.sendError(404); %>

slide-15
SLIDE 15

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

slide-16
SLIDE 16

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

slide-17
SLIDE 17

JSP Standard Actions

  • Accessing the “Data Layer” (The Model)

– <jsp:useBean> – <jsp:setProperty> – <jsp:getProperty>

  • Dispatching the request

– <jsp:forward> – <jsp:include>

  • ...
slide-18
SLIDE 18

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”
slide-19
SLIDE 19

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

slide-20
SLIDE 20

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

A (small) step towards accesing the data layer without writing Java code...

Person, your name is: ${pers.name}

slide-21
SLIDE 21

Model 1

slide-22
SLIDE 22

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>

slide-23
SLIDE 23

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

slide-24
SLIDE 24

<jsp:forward page=”...”/>

slide-25
SLIDE 25

<jsp:include page=”...”/>

<%@ include … %> directive ≠ <jsp: include …/> action

slide-26
SLIDE 26

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

slide-27
SLIDE 27

Model – View – Controller