Presentation is loading. Please wait.

Presentation is loading. Please wait.

JSP Elements Chapter 2.

Similar presentations


Presentation on theme: "JSP Elements Chapter 2."— Presentation transcript:

1 JSP Elements Chapter 2

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”)

3 JSTL – standardized tag library
Directive elements are messages to the JSP container 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. Action elements – you can create addition tags

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

5 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> <% } %>

6 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: 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.

7 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

8 Data Types and Variables

9 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

10 Special characters

11 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];

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

13 Operators, Assignments, and Comparisons
a += b; // same as a = a + b; a++; // same as a += 1; a--; // same as a -= 1; Comparisons !=, >, >=, <, <= Typecasting – assigning long value to an int variable

14 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)) B1 and b2 are true, but b3 is false. Comparisons operators don’t look inside the objects. They only check whether the objects are the same instance of a class, not whether they hold the same value. Equality operators are used to compare the memory locations of the two objects. Use .equals to compare contents

15 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";

16 Or switch(a) { case 1: s = "yes"; break; default: s = "no"; }

17 Iterations for (initial-assignment; end-condition; iteration-expression) { statements; } while (end-condition) { statements; } for (;end-condition;) { statements; } do { statements; } while (end-condition);

18 Java variation of for loop
String 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;

19 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()%>

20 The application Object
Provides access to the resource shared within the web application if (application.getAttribute("do_it") != null) { /* ...place your "switchable" functionality here... */ }

21 Example to enable and disable conditional code

22 continuations

23 Example using an attribute to control logging

24

25 The config Object The exception 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.

26 Listing 2-7 shows you two methods to send the stack trace to the output.
isErrorPage=“true”%>

27 <%@page errorPage=“stack_trace.jsp”%>

28 The out Object Use out like System.out <% out.print("abc"); %>
out.print("a string" + intVar + obj.methodReturningString() + ".");

29 <%@page trimDirectiveWhitespaces="true"%>
Ways to remove new lines trimDirectiveWhitespaces="true"%> - removes unnecessary spaces from the output, including the newlines.

30 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)

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

32 Listing the Headers

33

34 Example: User Authentication
Tomcat-users.xml file is shared by all applications Read the other two examples

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

36

37

38

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

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

41 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");

42 Directive Elements attr1="value1" [attr2="value2"...] %> The page Directive Tell Tomcat that the scripting language is Java and that the output is to be HTML: language="java" contentType="text/html"%> Tell Tomcat which external class definitions your code needs import="java.util.ArrayList"%> import="java.util.Iterator"%> import="myBeans.OneOfMyBeans"%> import="java.util.ArrayList, java.util.Iterator"%> // for multiple class import="java.util.*"%> not good

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

44 Simple program that utilizes the isThreadSafe attribute to test concurrency. Slows down execution.

45 alternative

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

47 The include Directive The taglib Directive
The includedirective lets you insert into a JSP page the unprocessed content of another text file. 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. uri=" prefix=”my”%> <my:oneOfMyTags> ... </my:oneOfMyTags> The following code includes the core JSP Standard Tag Library: uri=" prefix="c"%>


Download ppt "JSP Elements Chapter 2."

Similar presentations


Ads by Google