What is JSP Java based technology that simplifies
What is JSP? • Java based technology that simplifies the developing of dynamic web sites • JSP pages are HTML pages with embedded code that allows to access data from Java code running on the server • JSP provides separation of HTML presentation logic from the application logic
Java Web application technologies JSP technology is built on top of Java Servlet technology and they are complimentary for the purpose of Web application development
The need for JSP • With servlets, it is easy to • • • Read form data Read HTTP request headers Set HTTP status codes and response headers Use cookies and session tracking Share data among servlets Remember data between requests • But tedious to • • Use println statements to generate HTML Maintain that HTML
JSP technology • JSP technology provides a way to combine the worlds of HTML and Java Servlet programming • Idea: • • Use regular HTML for most of the page Mark Servlet code with special tags • Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request)
What is a JSP Page? • A text-based document capable of returning both static and dynamic content to a client browser • Static content and dynamic content can be intermixed • Static content • HTML, XML, plain text • Dynamic content • • • Java code Displaying properties of Java. Beans Invoking business logic defined in Custom tags
Example: a simple JSP page <html> <body> Hello World! Current time: <%= new java. util. Date() %> Random number: <%= Math. random() %> </body> </html>
Servlets versus JSP
JSP benefits • Content and display logic are separated • Simplify web application development with JSP, Java. Beans and custom tags • Supports software reuse through the use of components (Java. Beans, custom tags) • Automatic deployment • Recompile automatically when changes are made to JSP pages • Easier to author web pages • Platform-independent
Example: another simple JSP <html> <body> Current time: <%= new java. util. Date() %> Server: <%= application. get. Server. Info() %> Session ID: <%= session. get. Id() %> Last accessed: <%= session. get. Last. Accessed. Time() %> ms </body> </html>
Forwarding a Request to a JSP Forwarding a request to another web component (including JSP) is possible using Request. Dispatcher public class Servlet. Forward extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException{ // file my. jsp should be placed into “webapp” folder Request. Dispatcher dispatcher = request. get. Request. Dispatcher("my. jsp"); dispatcher. forward(request, response); } }
Dynamic contents generation techniques JSP supports two different styles for adding dynamic content to web pages: • JSP pages can embed actual Java code • JSP supports a set of HTML-like tags that interact with Java objects on the server (without the need for raw Java code to appear in the page)
How does JSP work? 1. Client request for a page ending with ". jsp“ 2. Web Server fires up the JSP engine 3. The JSP engine checks to see if the JSP file is new or changed 4. (if new) The JSP engine takes the page and converts it into a Java servlet (by JSP parser)
How does JSP work? 5. (if new) The JSP engine compiles the servlet (by standard Java compiler) 6. Servlet Engine executes the Java servlet using the standard API 7. Servlet’s output is transferred by Web Server as a HTTP response
Calling Java code directly • Suitable only for a very simple Web application • hard to maintain • hard to reuse code • hard to understand for web page authors • Not recommended for relatively sophisticated Web applications • weak separation between contents and presentation
JSP page content • Standard HTML tags & scripts (e. g. Java. Script) • New tags for scripting in the Java language • There are three forms • • • Expressions: <%= Expressions %> Scriptlets: <% Code %> Declarations: <%! Declarations %>
Expressions • During the execution phase • • Expression is evaluated and converted into a String The String is then inserted into the servlet's output stream directly Results in something like out. println(expression) Can use predefined variables (implicit objects) within expression • Format • <%= Expression %> OR • <jsp: expression>Expression</jsp: expression> • Semi-colons are not allowed for expressions
Example: Expressions • Display current time using Date class • Current time: <%= new java. util. Date() %> • Display random number using Math class • Random number: <%= Math. random() %> • Use implicit objects • • Your hostname: <%= request. get. Remote. Host() %> Your parameter: <%= request. get. Parameter(“your. Parameter”) %> • • Server: <%= application. get. Server. Info() %> Session ID: <%= session. get. Id() %>
Passing parameters from Servlet to JSP public class Business. Servlet extends Http. Servlet { public void do. Post(. . . ). . . { int result = calculate. Result(. . . ); request. set. Attribute("result", result); Request. Dispatcher dispatcher = request. get. Request. Dispatcher("result. jsp"); dispatcher. forward(request, response); } } <html> <body> Result: <%= request. get. Attribute("result") %> </body> </html>
Scriptlets • Used to insert arbitrary Java code into servlet's jsp. Service() method • Can do things expressions alone cannot do • • • setting response headers and status codes writing to a server log executing code that contains loops, conditionals • Can use predefined variables (implicit objects) • Format: • <% Java code %> OR • <jsp: scriptlet> Java code </jsp: scriptlet>
Example: Simple scriptlet <html> <body> <% String visitor = request. get. Parameter("name"); if (visitor == null) visitor = "World"; %> <h 1>Hello <%= visitor%>!</h 1> </body> </html> /hello_visitor. jsp? name=John
Example: Scriptlet with a loop <% Iterator i = cart. get. Items(). iterator(); while (i. has. Next()) { Shopping. Cart. Item item = (Shopping. Cart. Item)i. next(); Book. Details bd = (Book. Details)item. get. Item(); %> <tr> <td align="right" bgcolor="#ffffff"> <%=item. get. Quantity()%> </td> <td bgcolor="#ffffaa"> <strong><a href="<%=request. get. Context. Path()%> /bookdetails? book. Id=<%=bd. get. Book. Id()%>"><%=bd. get. Title()%> </a></strong> </td>. . . <% // End of while } %>
Example: Declaration <H 1>Random number generator</H 1> <%! private double random. Number() { return Math. random(); } %> <% double random. Number 1 = random. Number(); double random. Number 2 = random. Number(); double sum = random. Number 1 + random. Number 2; %> First random number: <%= random. Number 1 %> Second random number: <%= random. Number 2 %> Sum: <%= sum %>
Comments JSP supports three types of comments: • XHTML comments • Format <!-- and --> • Can be placed throughout JSP, but not in scriplets • JSP comments • Format <%-- and --%> • Can be placed throughout JSP, but not in scriplets • Java comments • Standard ones // and /* */ • Place within scriplets
Implicit objects • A JSP page has access to certain implicit objects that are always available, without being declared first • Provide programmers with access to many servlet capabilities in the context of a JSP • Created by container • Corresponds to classes defined in Servlet
Implicit objects • • request (Http. Servlet. Request) response (Http. Servlet. Repsonse) session (Http. Session) application (Servlet. Context) out (Jsp. Writer) config (Servlet. Config) page. Context
Scope objects • Application scope • • Container owns objects within application scope Any servlet or JSP can manipulate such objects • Session Scope • Exists for the clients entire browsing session • Request Scope • • Exist for the duration of the requests Go out of scope when request is completed with a response to the client • Page scope • Each page has it’s own instances of the page-scope implicit objects
Directives • A directive gives further information to the JSP container that applies to how the page is compiled • Syntax <%@ directive attribute=“value” %> • Can also combine multiple attribute settings <%@ directive attribute 1="value 1“ attribute 2="value 2“ attribute. N="value N" %>
Three main types of directives • page: specifies page dependent attributes and communicate these to the JSP container • <%@ page import="java. util. * %> • include: used to include text and/or code at JSP page translation-time • <%@ include file="header. html" %> • taglib: indicates a tag library that the JSP container should interpret • <%@ taglib prefix="c" uri="http: //java. sun. com/jsp/jstl/core" %>
Some page directives • Which classes are imported • <%@ page import="java. util. * %> • What MIME type is generated • <%@ page content. Type="MIME-Type" %> • How multithreading is handled • <%@ page is. Thread. Safe="false" %> • What page handles unexpected errors • <%@ page error. Page="errorpage. jsp" %>
JSTL • JSTL = Java Standard Tag Library • The second (and preferable) way to add dynamics • Encapsulates core functionality common to many JSP applications • The following tags are provided by JSTL • • • Core tags XML tags SQL tags Formatting tags Function tags
Reminder
How to use JSTL in JSP To use JSTL in JSP, you need to do some configuration in JSP • Step 1: add standard. jar and jstl. jar <dependency> <group. Id>taglibs</group. Id> <artifact. Id>standard</artifact. Id> <version>1. 1. 2</version> </dependency> <group. Id>javax. servlet</group. Id> <artifact. Id>jstl</artifact. Id> <version>1. 1. 2</version> </dependency> • Step 2: ensure that both files are packaged in /WEB-INF/lib directory of WAR file • Step 3: Write JSP file that can use core tags
A note on web. xml • Web application configuration file web. xml has to have specific attributes defined to support JSTL tags • Maven default generated web. xml does not support it! <? xml version="1. 0" encoding="ISO-8859 -1"? > <web-app xmlns="http: //java. sun. com/xml/ns/javaee" xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xsi: schema. Location="http: //java. sun. com/xml/ns/javaee/web-app_3_0. xsd" version="3. 0"> <!– Web App Configuration --> </web-app>
taglib directive To use JSTL tags in JSP need to include the following directive in a page: <%@ taglib prefix="c" uri="http: //java. sun. com/jsp/jstl/core" %> Tag usage example: <c: set var="name" value="${param. text 1}" /> Welcome <c: out value="${name}" /> !
Core tags [1/2] • Variable support • • <c: set> <c: remove> • Conditional • • <c: if> <c: choose> • <c: when> • <c: otherwise> • Iteration • • <c: for. Each> <c: for. Tokens>
Core tags [2/2] • URL management • • • <c: import> • <c: param> <c: redirect> • <c: param> <c: url> • <c: param> • General purpose • • <c: out> <c: catch>
Example: conditions <c: if test="${!empty result}"> Result: <c: out value="${result}" /> </c: if> <c: choose> <c: when test="${customer. category == ’trial’}" >. . . </c: when> <c: when test="${customer. category == ’member’}" >. . . </c: when> <c: when test="${customer. category == ’preferred’}" >. . . </c: when> <c: otherwise>. . . </c: otherwise> </c: choose>
Example: iterating and printing <table border="1"> <c: for. Each var="customer" items="${customers}"> <tr> <td><c: out value="${customer. first. Name}"/></td> <td><c: out value="${customer. last. Name}"/></td> <td><c: out value="${customer. phone. Home}" default="no home phone specified"/></td> </tr> </c: for. Each> </table>
JSP translation into Servlet Suppose we have the following JSP page <html> <body> <H 2> My HTML </H 2> <%= my. Expression() %> <% my. Scriptlet. Code(); %> </body> </html> It will be translated into Java servlet code as follows…
JSP translation into Servlet public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type(“text/html”); Http. Session session = request. get. Session(true); JSPWriter out = response. get. Writer(); // Static HTML fragment is sent to output stream in “as is” form out. println(“<H 2>My HTML</H 2>”); // Expression is converted into String and then sent to output out. println(my. Expression()); // Scriptlet is inserted as Java code within _jsp. Service() my. Scriptlet. Code(); . . . }
References • JSP Technology in Java EE 5 Tutorial http: //java. sun. com/javaee/5/docs/tutorial/doc/bnagx. html • JSP Documents in Java EE 5 Tutorial http: //java. sun. com/javaee/5/docs/tutorial/doc/bnajo. html • JSTL in Java EE 5 Tutorial http: //java. sun. com/javaee/5/docs/tutorial/doc/bnakc. html • JSTL 1. 1 Tag Reference http: //docs. oracle. com/javaee/5/jstl/1. 1/docs/tlddocs/
- Slides: 42