Java Server Pages

49
JavaServer Pages (JSP) Svetlin Nakov Borislava Spasova Creating Dynamic Web Pages

description

Presentation about JavaServer Pages (JSP).

Transcript of Java Server Pages

Page 1: Java Server Pages

JavaServer Pages (JSP)

Svetlin NakovBorislava Spasova

Creating Dynamic Web Pages

Page 2: Java Server Pages

Contents

1. Introduction to JSP Technology

2. JSP Expressions

3. Predefined JSP Variables

4. JSP Scriptlets

5. JSP Pages are Actually Servlets

6. JSP Declarations

7. JSP Directives• The JSP @page Directive • Static and Dynamic Include

Page 3: Java Server Pages

Contents (2)

8. More About The JSP Predefined Variables

• Using The "application" Object

9. Client and Server Redirection

10. HTML Escaping Problems

Page 4: Java Server Pages

Introduction to JSP Technology

Page 5: Java Server Pages

What is JSP?

• JavaServer Pages (JSP) is:

• Technology for generating dynamic Web content

• Allows Java programming code to be embedded in the HTML pages

• The Java code is executed on the server during the rendering of the JSP page

• After execution of a JSP page a plain HTML is produced and displayed in the client's Web browser

Page 6: Java Server Pages

JSP Technology

• JSP pages provide an easy way to develop dynamic Web applications

• Operate in a request/response mode

• Like Java servlets

• Generate dynamic content with very little or no coding (for non-programmers)

• Contain HTML text freely mixed with Java code (for advanced programmers)

• Can use various XML tags that simplify development

Page 7: Java Server Pages

Date JSP Page – Example

• Sample JSP page that displays the current date and time

<html> <html> <head><title>Date JSP <head><title>Date JSP exampleexample</title></head> </title></head> <body> <body> The date is: The date is: <% out.println(new java.util.Date()); %> <% out.println(new java.util.Date()); %> </body> </body> </html></html>

date.jspdate.jsp

Page 8: Java Server Pages

JSP Expressions

• A JSP expression is used to insert the result of a Java expression directly into the output

• It has the following form:

• Examples:

<%= Java<%= Java e expression %> xpression %>

The time isThe time is: <%= new java.util.Date() %>: <%= new java.util.Date() %>

The square root of 2 isThe square root of 2 is: <%= : <%= Math.sqrt(2)Math.sqrt(2) %> %>

The value of PI is: <%= Math.PI %>The value of PI is: <%= Math.PI %>

Page 9: Java Server Pages

Predefined JSP Variables

• JSP pages support a number of predefined variables that you can use• request – current HttpServletRequest

• response – the HttpServletResponse

• session – current HttpSession associated with the request (if any)

• out – the text stream for the result of the JSP page (PrintWriter)

• These variables are always initialized and can be used in any place in the JSP page

Page 10: Java Server Pages

JSP Expressions –More Examples

• The following example uses the predefined variable request to show the remote host of the client machine:

• Getting the default session timeout

• Getting the client's Web browser identification:

Your hostname: <%= request.getRemoteHost() %> Your hostname: <%= request.getRemoteHost() %>

Session timeoutSession timeout: : <%= session.getMaxInactiveInterval() %> <%= session.getMaxInactiveInterval() %>

Browser: <%= Browser: <%= request.getHeader("User-Agent") request.getHeader("User-Agent") %>%>

Page 11: Java Server Pages

JSP Scriptlets

• JSP scriptlets allow Java code to be inserted in the JSP pages

• Scriptlets have access to the automatically defined variables in the JSP pages (request, response, session, ...)

<% Java <% Java ccode %>ode %>

<% <% String queryData = request.getQueryString();String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData);out.println("Attached GET data: " + queryData);%>%>

Page 12: Java Server Pages

JSP Scriptlets – Example

• Example of using Java code in a JSP page:

• Example of using loop:

<% if (Math.random() < 0.5) { %><% if (Math.random() < 0.5) { %> Have a <B>nice</B> day!Have a <B>nice</B> day!<% } else { %><% } else { %> Have an <B>interesting</B> day!Have an <B>interesting</B> day!<% } %><% } %>

<% for (int i=0; i<10; i++) { %><% for (int i=0; i<10; i++) { %> <%= i %> * <%= i %> = <%= i*i %><%= i %> * <%= i %> = <%= i*i %> <br><br><% } %><% } %>

Page 13: Java Server Pages

JSP InternalsHow JSP Pages Are Transformed to Servlets?

Page 14: Java Server Pages

JSP Technology Internals

• JSP pages are actually servlets!

• The Web container translates JSP pages into Java servlet source code (.java)

• Then compiles that class into Java servlet class

• JSP pages have the same life cycle like servlets

JSP PageJSP Page((datedate.jsp.jsp))

Java servletJava servlet((datedate.java.java))

CompiledCompiledJava servletJava servlet

((datedate..classclass))

JSPJSP

compilercompiler

javacjavac

Page 15: Java Server Pages

JSP Technology Internals

• Tomcat stores the compiled JSP pages in the directory CATALINA_HOME/work

• Tomcat stores the compiled JSP pages in the directory CATALINA_HOME/work

<html> <html> <head><title>Date JSP<head><title>Date JSPexample</title></head>example</title></head><body> <body> The date is: <% The date is: <% out.println(newout.println(new java.util.Date()); %> java.util.Date()); %> </body> </body> </html></html>

<html> <html> <head><title>Date JSP<head><title>Date JSPexample</title></head>example</title></head><body> <body> The date is: <% The date is: <% out.println(newout.println(new java.util.Date()); %> java.util.Date()); %> </body> </body> </html></html>

date.jspdate.jspdate.jspdate.jsp

JSPJSPcompilationcompilation

JSPJSPcompilationcompilation

packagepackage org.apache.jsp;org.apache.jsp;public final classpublic final class date_jsp extendsdate_jsp extends HttpJspBaseHttpJspBaseimplementsimplements JspSourceDependent JspSourceDependent {{ ......}}

packagepackage org.apache.jsp;org.apache.jsp;public final classpublic final class date_jsp extendsdate_jsp extends HttpJspBaseHttpJspBaseimplementsimplements JspSourceDependent JspSourceDependent {{ ......}}

date_jsp.javadate_jsp.javadate_jsp.javadate_jsp.java

\webapps\JSP-Demos\\webapps\JSP-Demos\date.jspdate.jsp

\work\Catalina\localhost\\work\Catalina\localhost\JSP-Demos\org\apache\jspJSP-Demos\org\apache\jsp

Page 16: Java Server Pages

JSP Declarations and Directives

Page 17: Java Server Pages

JSP Declarations

• A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class

• It has the following form:

• Example:<%! Java <%! Java ccodeode (fields and methods) (fields and methods) %> %>

<%! <%! long counter = 0; long counter = 0; public void getCounter() { return counter; }public void getCounter() { return counter; }%>%>

Page 18: Java Server Pages

JSP Declarations

• Declarations do not generate any output

• Normally are used in conjunction with JSP expressions or scriptlets

• Example:

• Printing how many times a page is displayed since its loading on the server:

<%! private <%! private static static int accessCount = 0; %>int accessCount = 0; %>This page has been accessedThis page has been accessed <%= ++accessCount %><%= ++accessCount %> times. times.

Page 19: Java Server Pages

JSP Directives

• A JSP directive affects the overall structure of the servlet class

• Usually has the following form:

• Or have multiple attributes:

<%@ directive attribute="value" %><%@ directive attribute="value" %>

<%@ directive attribute1="value1" <%@ directive attribute1="value1" attribute2="value2"attribute2="value2" ...... attributeN="valueN" %>attributeN="valueN" %>

Page 20: Java Server Pages

The JSP @page Directive

• The page directive lets you define one or more page attributes:

• Specifying what packages should be imported

• Example:

• The import attribute is the only one that is allowed to appear multiple times

import="package.classimport="package.class" " ororimport="package.class1,import="package.class1, ...,..., package.classN" package.classN"

<%@ page import="java.util.*" %><%@ page import="java.util.*" %>

Page 21: Java Server Pages

The JSP @page Directive (2)

• Specifying the MIME type of the output (the default is "text/html")

• For example, the directive:

has the same effect as the scriptlet:

contentType="MIME-Type" or contentType="MIME-Type" or contentType="MIME-Type; charset=Character-Set"contentType="MIME-Type; charset=Character-Set"

<%@ page contentType="text/plain" %><%@ page contentType="text/plain" %>

<% response.setContentType("text/plain"); %> <% response.setContentType("text/plain"); %>

Page 22: Java Server Pages

The JSP @page Directive (3)

• Defining whether the page will use the implicit session object (default is true)

• Defining an URL to the page to which all uncaught exceptions should be sent

• Declaring the current page as error page (allows access to the exception object)

session="true|false"session="true|false"

errorPage="url"errorPage="url"

isErrorPage="true|false"isErrorPage="true|false"

Page 23: Java Server Pages

The JSP @include Directive

• Lets you include files at the time the JSP page is translated into a servlet (also called static include)

• The directive looks like this:

• The URL specified is interpreted as relative to the JSP page that refers to it

• Example:

<%@ include file="relative url" %><%@ include file="relative url" %>

<%@ include file="/<%@ include file="/include/include/menu.jsp" %>menu.jsp" %>

Page 24: Java Server Pages

Using JSP @include Directive

• Using the @include directive to include a small navigation bar on each page

<<htmlhtml>> <<bodybody>> <%@ include file="/navbar.html" %><%@ include file="/navbar.html" %> <!-- Part specific to this page ... --><!-- Part specific to this page ... -->

</</bodybody>></</htmlhtml>>

Page 25: Java Server Pages

Dynamic Include

• Including a page at runtime (dynamic include):

• Dynamic include executes the page at runtime and appends the results of it

• More powerful and flexible

<jsp:include page="header.jsp"<jsp:include page="header.jsp" /> />

<% String headerPage = "header.jsp"<% String headerPage = "header.jsp";; %> %><jsp:include page="<%= headerPage %>" /> <jsp:include page="<%= headerPage %>" />

Page 26: Java Server Pages

JSP Predefined Variablesrequest, response, session,application, config, …

Page 27: Java Server Pages

More About The JSP Predefined Variables

• request• The HttpServletRequest associated with the

request

• Allows accessing the request parameters, HTTP headers, cookies, etc.

• response

• The HttpServletResponse associated with the response to the client

• It is legal to set HTTP status codes and response headers (because the output stream is buffered)

Page 28: Java Server Pages

More About The JSP Predefined Variables (2)

• out• The PrintWriter used to send text output to the

client

• session • The HttpSession object associated with the

request

• Sessions are created automatically, so this variable is bound even if there was no incoming session reference

• Can store state information about the current client

Page 29: Java Server Pages

More About The JSP Predefined Variables (3)

• application• The ServletContext as obtained via getServletConfig().getContext()

• Can store information accessible from whole the application

• All servlets and JSP pages can share information through this object

• pageContext• Encapsulates all other implicit JSP objects

(request, response, session, ...) in a PageContext instance

Page 30: Java Server Pages

More About The JSP Predefined Variables (4)

• page• Synonym of this object (not very useful)

• exception• The implicit Throwable object

• Available only in the error pages

• Contains the last exception

• config• Contains the ServletConfig for the current JSP

page

• Useful for accessing the init parameters

Page 31: Java Server Pages

Using The application Object

• Always use the application object in a synchronized section

• It is shared object between all threads

• Web containers run a separate thread for each client request

synchronized (application)synchronized (application) { { VectorVector items = (Vector)items = (Vector) application.getAttributeapplication.getAttribute("items");("items"); if (sharedItems == null) {if (sharedItems == null) { sharedItems = new Vector ();sharedItems = new Vector (); application.setAttributeapplication.setAttribute("items", items);("items", items); }}}}

Page 32: Java Server Pages

Using The application Object – Example

<%@ page import="java.util.Vector" %><%@ page import="java.util.Vector" %>

<%// Get the global list of shared items<%// Get the global list of shared items Vector<String> sharedItems;Vector<String> sharedItems; synchronized (application)synchronized (application) { { sharedItems = (Vector<String>)sharedItems = (Vector<String>) application.getAttributeapplication.getAttribute("items");("items"); if (sharedItems == null) {if (sharedItems == null) { sharedItems = new Vector<String>();sharedItems = new Vector<String>(); application.setAttributeapplication.setAttribute("items", sharedItems);("items", sharedItems); }} }}

// Append the new item (if exists)// Append the new item (if exists) String newItem = request.getParameter("item");String newItem = request.getParameter("item"); if (newItem != null)if (newItem != null) sharedItems.addElement(newItem);sharedItems.addElement(newItem);%>%>

Page 33: Java Server Pages

Using The application Object – Example (2)

<html><html><head><title>Global Shared List</title></head><head><title>Global Shared List</title></head><body><body> Available shared items:Available shared items: <ol><ol> <% for (String item : sharedItems) {<% for (String item : sharedItems) { %>%> <li><%= item %></li><li><%= item %></li> <% }<% } %>%> </ol></ol> <form method="POST" <form method="POST" action="Global-Shared-List.jsp">action="Global-Shared-List.jsp"> <input type="text" name="item"><input type="text" name="item"> <input type="submit" value="Add"><input type="submit" value="Add"> </form></form></body></body></html></html>

Page 34: Java Server Pages

Client and Server Redirections

Page 35: Java Server Pages

Client Redirection to Another URL

• Client redirection

• Redirects the client's Web browser to given new relative URL

• Actually sends HTTP response code 302 (Resource moved temporarily)

• The browser requests the new location

• Example:

response.sendRedirect(<url>);response.sendRedirect(<url>);

response.sendRedirect("date.jsp");response.sendRedirect("date.jsp");

Page 36: Java Server Pages

Server Redirection to Another Resource

• Server redirection

• Returns the contents of given resource at the server

• The browser does not know that a redirection is occurred at the server

• Example:

request.getRequestDispatcher(<url>).request.getRequestDispatcher(<url>). forward(request, response)forward(request, response)

request.getRequestDispatcher("date.jsp").request.getRequestDispatcher("date.jsp"). forward(request, response);forward(request, response);

Page 37: Java Server Pages

<jsp:forward>

• Forwards a client request to an HTML file, JSP file, or servlet for processing• Simple syntax

• Syntax with parameters

<jsp:forward page=<jsp:forward page= {"{"relativeURLrelativeURL" |" | "<%= "<%= expressionexpression %>"} /> %>"} />

<jsp:forward <jsp:forward page={"page={"relativeURLrelativeURL" |" | "<%="<%= expression expression %>"} > %>"} > <jsp:param name="<jsp:param name="parameterNameparameterName"" value="{value="{parameterValueparameterValue | | <%= <%= expressionexpression %>}" /> %>}" /> </jsp:forward> </jsp:forward>

Page 38: Java Server Pages

<jsp:forward> – Example

• Example:

• <jsp:forward> actually performs a server-side redirection

• The client does not know that a redirection has occurred

<jsp:forward page="Global-Shared-List.jsp"><jsp:forward page="Global-Shared-List.jsp"> <jsp:param name="<jsp:param name="itemitem" value=" value= "This item is added by JSP-forward.jsp" />"This item is added by JSP-forward.jsp" /></jsp:forward></jsp:forward>

Page 39: Java Server Pages

Escaping ProblemsAnd How to Avoid Them

Page 40: Java Server Pages

Escaping Problems

• Escaping problems are very common in the Web programming

• Displaying not escaped text is dangerous

• Makes the application unstable

• Opens security vulnerabilities

• When displaying text it should not contain any HTML special characters

• Performing escaping of the HTML entities is obligatory!

Page 41: Java Server Pages

Escaping Problems – Example

• Consider the following JSP page:

• What will happen if we enter this?

<html><html> You entered:You entered: <%= request.getParameter("something") %><%= request.getParameter("something") %> <form><form> Enter something:<br>Enter something:<br> <input type="text" name="something"><input type="text" name="something"> <input type="submit"><input type="submit"> </form></form></html></html>

<script language="JavaScript">alert('Bug!');</script><script language="JavaScript">alert('Bug!');</script>

Page 42: Java Server Pages

What To Escape?

• What symbols to escape depends on the place where we put the escaped text:• In the HTML document body dangerous

characters are:•<, >, &, space (and maybe tab, new line)

• Inside an attribute of a HTML tag the dangerous characters are:•" and &

• Inside a <textarea> we need to escape:•<, > and &

• What symbols to escape depends on the place where we put the escaped text:• In the HTML document body dangerous

characters are:•<, >, &, space (and maybe tab, new line)

• Inside an attribute of a HTML tag the dangerous characters are:•" and &

• Inside a <textarea> we need to escape:•<, > and &

Page 43: Java Server Pages

• Generally we should always escape the following HTML special characters:

• In the HTML body we may need to escape also:

• Generally we should always escape the following HTML special characters:

• In the HTML body we may need to escape also:

Escape The HTML Special Characters

"&quot;Quotation Mark

&&amp;Ampersand

>&gt;Greater Than

<&lt;Less Than

CharacterHTML EntityCharacter Name

&nbsp;&nbsp;&nbsp; &nbsp;Tab

<br>New Line

&nbsp;Space

EscapingCharacter Name

Page 44: Java Server Pages

HTML Escaping

• There is no standard method in Servlet/JSP API for HTML escaping

• We need a custom escaping method:

public static String htmlEscape(String text) {public static String htmlEscape(String text) { if (text == null) {if (text == null) { return "";return ""; }} StringBuilder escapedText = StringBuilder escapedText = new StringBuilder();new StringBuilder(); for (int i=0; i<text.length(); i++) {for (int i=0; i<text.length(); i++) { char ch = text.charAt(i);char ch = text.charAt(i);

Page 45: Java Server Pages

HTML Escaping (2)

if (ch == '<')if (ch == '<') escapedText.append("&lt;");escapedText.append("&lt;"); else if (ch == '>')else if (ch == '>') escapedText.append("&gt;");escapedText.append("&gt;"); else if (ch == '&')else if (ch == '&') escapedText.append("&amp;");escapedText.append("&amp;"); else if (ch == '\"')else if (ch == '\"') escapedText.append("&quot;");escapedText.append("&quot;"); elseelse escapedText.append(ch);escapedText.append(ch); }} String result = escapedText.toString();String result = escapedText.toString(); return result;return result;}}

Page 46: Java Server Pages

Problems

1. Create a JSP page that calculates the sum of 2 integer numbers. The page should have two form fields and a submit button.

2. Create a JSP page that can add an remove items. The items are strings and should be stored in the client's session.

3. Using the JSP dynamic include create a small web site (2-3 pages) that has header, footer and a menu on each page. The header contents, footer contents and the menu should be placed in separate files.

Page 47: Java Server Pages

Problems (2)

4. Using the global application object implement a counter of the visitors of the site.

5. Using the client's session object and the client redirection technique implement a JSP page that enters an integer number sequentially 5 times. After the entering the 5th number the client's Web browser should be redirected to another JSP page that shows all entered numbers and their sum.

6. Ensure that no escaping problems are present in all your previous JSP pages. Correct them as needed.

Page 48: Java Server Pages

Homework

1. Using the global application object implement the "number guess game" that can be played globally by multiple players in the same time.

The number guess game starts with a secret number randomly chosen by the server. Each player can make guesses and the server tells whether the number is smaller, larger or the same.

The player who first guesses the number wins and the game starts again.

Page 49: Java Server Pages

Homework (2)

2. Using the JSP technology implement a simple discussion forum. Each visitor should be able to post new topics, to reply to a topic and to delete topics and replies. Each topic is a message and can have replies. The replies are messages in the same topic (no nesting is allowed). Each message consists of author subject and contents.

Each page in the forum should have a header, a footer and a menu (implemented by including fragments of JSP pages).

Take care of possible escaping problems.