Implicit objects
Download
Report
Transcript Implicit objects
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. <% and %>
• Implicit objects: application, config, exception, out, pageContext,
request, response, and session
• request.getHeader(“user-agent”)
• 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.
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.
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>
<% } %>
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.
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
Data Types and Variables
•
•
•
•
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
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 type
int[] 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];
• int[][] table = new int[2][]; //allowed declaration
Operators, Assignments, and Comparisons
• a += b; // same as a = a + b;
• a++; // same as a += 1;
• a--; // same as a -= 1;
• Comparisons
• !=, >, >=, <, <=
• Comparison warning
String 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))
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";
• Or
switch(a) {
case 1:
s = "yes";
break;
default:
s = "no";
break;
}
Iterations
• for (initial-assignment; end-condition; iteration-expression) {
statements; }
• while (end-condition) { statements; }
• for (;end-condition;) { statements; }
• do { statements; } while (end-condition);
• Java variation of for loop
String concatenate(Set<String> ss) {
String conc = "";
String concatenate(Set<String> ss) {
String conc = "";
Iterator<String> iter = ss.iterator();
for (String s : ss) {
while (iter.hasNext()) {
conc += s;
conc += iter.next();
}
return conc;
}
return conc;
}
}
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()%>
• The application Object
• Provides access to the resource shared within the web application
if (application.getAttribute("do_it") != null) {
/* ...place your "switchable" functionality here... */
}
• 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.
• The out Object
• Use out like System.out
<% out.print("abc"); %>
<%="abc"%>
abc
out.print("a string" + intVar + obj.methodReturningString() + ".");
• Spaces
<%@page trimDirectiveWhitespaces="true"%>
• 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)
• 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.
• Example: User Authentication
• 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 <webapp> 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.
• 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.
• 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) { ...
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");
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
• 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.
• 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.
• 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 selfcontained 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"%>