JSP Elements

47
JSP Elements Chapter 2

description

JSP Elements. Chapter 2. A JSP page is made out of a page template, which consists of HTML code and JSP elements such as scripting elements, directive elements, and action elements Scripting elements consist of code delimited by particular sequences of characters. - PowerPoint PPT Presentation

Transcript of JSP Elements

Page 1: JSP Elements

JSP ElementsChapter 2

Page 2: JSP Elements

• A JSP page is made out of a page template, which consists of HTML code and JSP elements such as scripting elements, directive elements, and action elements• Scripting elements consist of code delimited by particular sequences

of characters. <% and %>• Implicit objects: application, config, exception, out, pageContext,

request, response, and session• request.getHeader(“user-agent”)

Page 3: JSP Elements

• Directive elements are messages to the JSP container <%@page language="java" contentType="text/html"%>

• include and taglib

• Action elements specify activities that, like the scripting elements, need to be performed when the page is requested• Action elements can use, modify, and/or create objects, and they may affect

the way data is sent to the output.<jsp:include page=“another.jsp”/>

• JSTL – standardized tag library• EL – additional JSP component that provides easy access to external objects.

Page 4: JSP Elements

Scripting Elements and Java• Scripting elements let you embed Java code in an HTML page.• Every Java executable—whether it’s a free-standing program running

directly within a runtime environment, an applet executing inside a browser, or a servlet executing in a container such as Tomcat—boils down to instantiating classes into objects and executing their methods.

Page 5: JSP Elements

Scriptlets• A scriptlet is a block of Java code enclosed between <%and %>. • For example, this code includes two scriptlets that let you switch an

HTML element on or off depending on a condition: <% if (condition) { %>

<p>This is only shown if the condition is satisfied</p> <% } %>

Page 6: JSP Elements

Expression• An expression scripting element inserts into the page the result of a

Java expression enclosed in the pair <%=and %>. • For example, in the following snippet of code, the expression scripting

element inserts the current date into the generated HTML page: <%@page import="java.util.Date"%> Server date and time: <%=new Date()%>

• In practice, it means that every Java expression will do, except the execution of a method of type void.

Page 7: JSP Elements

Declarations• A declaration scripting element is a Java variable declaration enclosed

between <%!and %>. • It results in an instance variable shared by all requests for the same

page

Page 8: JSP Elements

Data Types and Variables

Page 9: JSP Elements

• String aString = “abcdxyz”;• int k = aString.length();• char c = aString.charAt(4);• Static final NAME = “John Doe”;

• Declaration • <% int k = 0; %> // new variable is created for each incoming HTTP client request• <%! int k = 0; %> // new variable is created for each new instance of the servlet• <%! static int k = 0; %> //the variable is shared among all instances of the servlet

Page 10: JSP Elements
Page 11: JSP Elements

Objects and Arrays• To create an object of a certain type (i.e., to instantiate a class), use

the keyword new.Integer integerVar = new Integer(55);

• Arrays of any object type or primitive data typeint[] intArray1; int[] intArray2 = {10, 100, 1000}; String[] stringArray = {"a", "bb"};

int[] array = new int[10];int[][] table1 = {{11, 12, 13}, {21, 22}};int[][] table = new int[2][3];

Page 12: JSP Elements

• int[][] table = new int[2][]; //allowed declaration

Page 13: JSP Elements

Operators, Assignments, and Comparisons• a += b; // same as a = a + b; • a++; // same as a += 1; • a--; // same as a -= 1;

• Comparisons• !=, >, >=, <, <=

Page 14: JSP Elements

• Comparison warningString s1 = "abc"; String s2 = "abc"; String s3 = "abcd".substring(0,3); boolean b1 = (s1 == "abc"); // parentheses not needed but nice! boolean b2 = (s1 == s2); boolean b3 = (s1 == s3);

• &&, ||, ! – can be used to form more complex conditions((a1 == a2) && !(b1 || b2))

Page 15: JSP Elements

Selections• The following statement assigns to the string variable sa different string

depending on a condition: if (a == 1) {

s = "yes"; } else {

s = "no"; }

• You can omit the else part. String s = (a== 1) ? "yes" : "no";

Page 16: JSP Elements

• Or switch(a) {

case 1: s = "yes"; break;

default: s = "no"; break;

}

Page 17: JSP Elements

Iterations• for (initial-assignment; end-condition; iteration-expression)

{ statements; }• while (end-condition) { statements; } • for (;end-condition;) { statements; }• do { statements; } while (end-condition);

Page 18: JSP Elements

• Java variation of for loopString concatenate(Set<String> ss) {

String conc = ""; Iterator<String> iter = ss.iterator(); while (iter.hasNext()) {

conc += iter.next(); }

return conc; }

String concatenate(Set<String> ss) { String conc = ""; for (String s : ss) {

conc += s; } return conc;

}

Page 19: JSP Elements

Implicit Objects• Most commonly used implicit objects defined by Tomcat are out and

request, followed by application and session.• In general, <%=the_mysterious_object.getClass().getName()%>

Page 20: JSP Elements

• The application Object• Provides access to the resource shared within the web application

if (application.getAttribute("do_it") != null) { /* ...place your "switchable" functionality here... */

}

Page 21: JSP Elements
Page 22: JSP Elements
Page 23: JSP Elements
Page 24: JSP Elements
Page 25: JSP Elements

• The config Object• The config object is an instance of the

org.apache.catalina.core.StandardWrapperFacadeclass, which Tomcat defines to implement the interface javax.servlet.ServletConfig. • Tomcat uses this object to pass information to the servlets.

config.getServletName()

• The exception Object• The exception object is an instance of a subclass of Throwable(e.g.,

java.lang.NullPointerException) and is only available in error pages.

Page 26: JSP Elements
Page 27: JSP Elements
Page 28: JSP Elements

• The out Object• Use out like System.out

<% out.print("abc"); %> <%="abc"%> abc

out.print("a string" + intVar + obj.methodReturningString() + ".");

Page 29: JSP Elements

• Spaces

<%@page trimDirectiveWhitespaces="true"%>

Page 30: JSP Elements

• The pageContext Object• A class to access all objects and attributes of a JSP page• The PageContext class defines several fields, including PAGE_SCOPE,

REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four possible scopes.

pageContext.removeAttribute("attrName", PAGE_SCOPE)

Page 31: JSP Elements

• The request Object• The request variable gives you access within your JSP page to the HTTP

request sent to it by the client.• Note: You cannot mix methods that handle parameters with methods that

handle the request content, or methods that access the request content in different ways.

Page 32: JSP Elements
Page 33: JSP Elements
Page 34: JSP Elements

• Example: User Authentication

Page 35: JSP Elements

• To password-protect all the pages inside a particular folder of an application, you have to edit the WEB-INF/web.xml file in the application’s root directory. • Listing 2-11 shows you the code you need to insert inside the <web-

app> element to limit the access of the pages in the folder /tests/auth/this/to users with the role canDoThis, and of the pages in the folder /tests/auth/that/to users with the role canDoThat.

Page 36: JSP Elements
Page 37: JSP Elements
Page 38: JSP Elements
Page 39: JSP Elements

• The response Object• The response variable gives you access within your JSP page to the HTTP response to be sent back to the

client. • The HttpServletResponse interface includes the definition of 41 status codes (of type public static final int)

to be returned to the client as part of the response. • The HTTP status codes are all between 100 and 599.

• The range 100–199 is reserved to provide information, • 200–299to report successful completion of the requested operation, • 300–399to report warnings, • 400–499to report client errors, and • 500–599 to report server errors. • You will find the full list of errors at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.

• The normal status code is SC_OK (200), and the most common error is SC_NOT_FOUND (404),• Working with Tomcat, the most common server error is SC_INTERNAL_SERVER_ERROR (500). • You get it when there is an error in a JSP. You can use these constants as arguments of the sendErrorand

setStatusmethods.

Page 40: JSP Elements

• The session Object• The term session refers to all the interactions a client has with a server from

the moment the user views the first page of an application to the moment they quit the browser (or the session expires because too much time has elapsed since the last request).• When Tomcat receives an HTTP request from a client, it checks whether the

request contains a cookie that by default is named JSESSIONID.

session.setAttribute("MyAppOperator", "");boolean isOperator = (session.getAttribute("MyAppOperator") != null); if (isOperator) { ...

Page 41: JSP Elements

session.setAttribute("upref", preferences); In all the pages of your application, you can then retrieve that

information with something like this: UserPrefs preferences = (UserPrefs)session.getAttribute("upref");

Page 42: JSP Elements

Directive Elements• <%@directive-name attr1="value1" [attr2="value2"...] %>

• The page Directive• Tell Tomcat that the scripting language is Java and that the output is to be

HTML: • <%@page language="java" contentType="text/html"%>

• Tell Tomcat which external class definitions your code needs• <%@page import="java.util.ArrayList"%> • <%@page import="java.util.Iterator"%> • <%@page import="myBeans.OneOfMyBeans"%> • <%@page import="java.util.ArrayList, java.util.Iterator"%> // for multiple class

Page 43: JSP Elements

• In addition to language, contentType, and import, the page directive also supports autoFlush, buffer, errorPage, extends, info, isELIgnored, isErrorPage, isScriptingEnabled, isThreadSafe, pageEncoding, session, and trimDirectiveWhitespaces.

Page 44: JSP Elements
Page 45: JSP Elements
Page 46: JSP Elements

• Remaining page directives• extends tells Tomcat which class the servlet should extend. • info defines a string that the servlet can access with its

getServletInfo()method.• isELIgnored tells Tomcat whether to ignore EL expressions.• isScriptingEnabled tells Tomcat whether to ignore scripting elements.• pageEncoding specifies the character set used in the JSP page itself.• session tells Tomcat to include or exclude the page from HTTP sessions.

Page 47: JSP Elements

• The include Directive• The includedirective lets you insert into a JSP page the unprocessed content of another text file.

<%@include file="some_jsp_code.jspf"%>

• The taglib Directive• You can extend the number of available JSP tags by directing Tomcat to use external self-contained tag

libraries. The taglib directory identifies a tag library and specifies what prefix you use to identify its tags.

<%@taglib uri="http://mysite.com/mytags" prefix=”my”%><my:oneOfMyTags> ... </my:oneOfMyTags>

• The following code includes the core JSP Standard Tag Library: <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>