Download presentation
Presentation is loading. Please wait.
1
WEB TECHNOLOGIES – Unit VII
By B. Ravinder Reddy Assistant Professor Department of CSE UNIT-7 WT
2
LECTURE PLAN UNIT-7 Lecture No. Topic Name Slide No L1 2 L2 34 L3 51
JSP Application Development: Generating Dynamic Content 2 L2 Using Scripting Elements, Implicit JSP Objects, Conditional Processing. 34 L3 Displaying Values Using an Expression to Set an Attribute 51 L4 Declaring Variables and Methods, Sharing Data Between JSP pages,Requests 61 L5 Error Handling and Debugging 70 L6 Users Passing Control and Date between Pages 87 L7 Sharing Session and Application Data 97 L8 Memory Usage Considerations 108 UNIT-7 WT
3
LECTURE-1 UNIT-7 WT
4
JSP Application Development: Generating Dynamic Content
UNIT-7 WT
5
Contents Java Server Pages model view controller
1 Java Server Pages 2 model view controller 3 Accessing Java Server Pages 4 How does JSP work: Life cycle 5 javax.servlet.jsp.HttpJspPage 6 Syntactic Elements of a JSP Page 7 Template Data 8 JSP Comment 9 Elements 10 Scripting elements UNIT-7 WT
6
Contents Scriptlets Expressions JSP Declarations Implicit JSP objects
11 Scriptlets 12 Expressions 13 JSP Declarations 14 Implicit JSP objects 15 out object 16 request object 17 response object 18 application object 19 session object 20 exception, page and config object UNIT-7 WT
7
Contents pageContext object JSP Directives Page directive
21 pageContext object 22 JSP Directives 23 Page directive 24 Attribute List 25 Include directive UNIT-7 WT
8
Java Server Pages JavaServer Pages (JSP) technology enables you to mix regular, static HTML with dynamically generated content from servlets. UNIT-7 WT
9
What is JSP? http://java.sun.com/products/jsp,
A way to create dynamic web pages, Server side processing, Based on Java Technology, Large library base Platform independence Separates the graphical design from the dynamic content. UNIT-7 WT
10
JSP versus Servlets But JSP pages are converted to Servlets? Aren’t they the same? Similarities Provide identical results to the end user JSP is an additional module to the Servlet Engine UNIT-7 WT
11
JSP versus Servlets (cont’d)
Differences Servlets: “HTML in Java code” HTML code inaccessible to Graphics Designer Everything very accessible to Programmer JSP: “Java Code Scriptlets in HTML” HTML code very accessible to Graphics Designer Java code very accessible to Programmer UNIT-7 WT
12
How the JSP Engine Works: Overview
UNIT-7 WT
13
How the JSP Engine Works: Internals
UNIT-7 WT
14
UNIT-7 WT
15
Accessing Java Server Pages
Need to have a Web server that supports JSP Give your file a “.jsp” extension Simply install it in any place you put a normal Web page No compiling, no packages, and no user CLASSPATH settings. UNIT-7 WT
16
How does JSP work: Life cycle
A JSP container manages two phases of a JSP page’s life. Translation phase: During the translation phase the container locates or creates the JSP page implementation class that corresponds to a given JSP page. Execution phase/ Request Processing Phase:During the execution phase the JSP container delivers events to the JSP page implementation object. The container is responsible for instantiating request and response objects and invoking the appropriate JSP page implementation object. Upon completion of processing, the response object is received by the container for communication to the client. Servlet class generated at the end of translation phase extend a superclass that ; Either specified by page author via an extends attribute in the page directive or A JSP container specific implementation class that extends interface called javax.servlet.jsp.JspPage interface. Since most JSP page use HTTP, class actually extends javax.servlet.jsp.HttpJspPage which inherits from javax.servlet.jsp.JspPage. While implementations for jspInit() and jspDestroy() methods can be provided in the JSP, implementation for _jspService() should never be provided. This method will be generated by the container. The three major life events methods that work together are: It takes longer time for the first JSP page to load. Time taken to load any subsequent requests for the same page would be the same as that of a servlet. UNIT-7 WT
17
javax.servlet.jsp.HttpJspPage
JSP page is converted into servlet and this class implements HttpJspPage The life cycle methods of HttpJspPage public void jspInit() public void _jspService(HttpServletRequest req, HttpservlerResponse res) throws servletException, IOException public void jspDestroy() UNIT-7 WT
18
Initialized and invoked only once for the first request _jspService()
jspInit() Initialized and invoked only once for the first request _jspService() Handle requests: Invoked for every request including the first jspDestroy() Invoked by the container to clean up the JSP UNIT-7 WT
19
Syntactic Elements of a JSP Page
A JSP page is composed of template data Template data is everything else: anything that the JSP translator does not know about. elements An element is an instance of an element type known to the JSP container UNIT-7 WT
20
Template Data Template data is anything that is not a scripting element anything that JSP processor does not process. A large percentage of the JSP page just consists of static HTML, known as template text. JSP comment is also a kind of template data. In template text a literal <% is quoted by <\%. That is if you need an output <%, you need to put <\% in the template text. Next slide UNIT-7 WT
21
JSP Comment A comment to that appears in the JSP page but not in the resultant document is a JSP comment <%-- JSP Comment --%> Note that the HTML comment <!– xxxx will pass through the JSP translator and will appear in the resultant source code of the html page. UNIT-7 WT
22
Invoking Dynamic Code (from JSPs)
Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags) UNIT-7 WT
23
Invoking Dynamic Code (from JSPs)
Simple Application or Small Development Team Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags) Complex Application or Big Development Team UNIT-7 WT
24
Java Beans Purpose: Store Data Simple Object,
requires no argument constructor Properties accessible via get & set methods UNIT-7 WT
25
Java Beans For a "foo" property, a java bean will respond to
Type getFoo() void setFoo(Type foo) For a boolean "bar" property, a java bean will respond to boolean isBar() void setBar(boolean bar) UNIT-7 WT
26
Java Bean int getCount() void setCount(int c) String getS()
void setS(String s) int[] getFoo() void setFoo(int[] f) int count; String s; int[] foo; UNIT-7 WT
27
UNIT-7 WT
28
/* A simple bean that contains a single * "magic" string. */
// MagicBean.java /* A simple bean that contains a single * "magic" string. */ public class MagicBean { private String magic; public MagicBean(String string) { magic = string; } public MagicBean() { magic = "Woo Hoo"; // default magic string public String getMagic() { return(magic); public void setMagic(String magic) { this.magic = magic; UNIT-7 WT
29
Java Beans <jsp:useBean id="myBean" class="com.foo.MyBean“ scope="request"/> <jsp:getProperty name="myBean“ property="lastChanged" /> <jsp:setProperty name="myBean“ property="lastChanged" value="<%= new Date()%>"/> Example <jsp:usebean id="bean" class="MagicBean" /> <jsp:getProperty name="bean" property="magic" /> UNIT-7 WT
30
<h3>Bean JSP</h3>
<hr> <h3>Bean JSP</h3> <p>Have all sorts of elaborate, tasteful HTML ("presentation") surrounding the data we pull off the bean. <p> Behold -- I bring forth the magic property from the Magic Bean... <!-- bring in the bean under the name "bean" --> <jsp:usebean id="bean" class="MagicBean" /> <table border=1> <tr> <td bgcolor=green><font size=+2>Woo</font> Hoo</td> <td bgcolor=pink> does bean.getMagic() --> UNIT-7 WT
31
<td bgcolor=pink> <!-- the following effectively
<font size=+3> <td bgcolor=pink> <!-- the following effectively </font> </td> <td bgcolor=yellow>Woo <font size=+2>Hoo</font></td> </tr> </table> <!-- pull in content from another page at request time with a relative URL ref to another page --> <jsp:include page="trailer.html" flush="true" /> UNIT-7 WT
32
public class HelloBean extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); String title = "Hello Bean"; out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body bgcolor=white>"); out.println("<h1>" + title + "</h1>"); out.println("<p>Let's see what Mr. JSP has to contribute...");request.setAttribute("foo", "Binky"); UNIT-7 WT
33
MagicBean bean = new MagicBean("Peanut butter sandwiches!");
request.setAttribute("bean", bean); RequestDispatcher rd = getServletContext().getRequestDispatcher("/bean.jsp"); rd.include(request, response); out.println("<hr>"); out.println("</body>"); out.println("</html>"); } // Override doPost() -- just have it call doGet() public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); UNIT-7 WT
34
JSP Tags Found in JSP Pages Look like HTML Tags
<blah attr=val>Foo</blah> Single Tag Format <blah attr=val/> UNIT-7 WT
35
LECTURE-2 UNIT-7 WT
36
Using Scripting Elements, Implicit JSP Objects, Conditional Processing
Scripting elements provide glue around template text and actions. Directive elements provide information for the translation phase. Action elements Actions provide information for the request processing phase. An Actions can either be standard, that is, defined in this specification, or custom, that is provided via the portable tag extension mechanism. UNIT-7 WT
37
Scripting elements 3 Types of elements of scripting elements
scriptlets <% …. %> expressions <%= ... %> declarations <%! ... %> UNIT-7 WT
38
Scriptlets <% …. %>
A set of one or more java statements intended to be used to process the request Goes into _jspService() method. UNIT-7 WT
39
Example- Scriplet <html>
<head><title>Prime</title> </head> <body> <h1> List of prime numbers between 2 to 100</h1> <% boolean flag=true; for(int i=2;i<100;i++){ for(j=2;j=i/2;j++){ if(i%j==0) flag=false; break; } if(flag) out.println(i+ “<br> “); } %> </body> </html> Scriplets Template data Special object used to print the output to html page- more on this coming up … UNIT-7 WT
40
Implicit JSP objects out request response session application
Implicit JSP objects are automatically defined variables These are defined in the _jspService() method These are not accessible in declarations out request response session application exception page pageContext config UNIT-7 WT
41
out object This object handles text output to browser from the JSP page. An instance of javax.servlet.jsp.JspWriter Example: <% out.println("<h1>Hello</h1>"); %> UNIT-7 WT
42
request object This object can be used to access lots of information contained in the HTTP request header sent from a browser when requesting a JSP page. The request object is analogous to request object in servlet. Common Examples: <%=request.getParameter("name") %> UNIT-7 WT
43
response object This object is used in response header that are sent to the browser from the server along with the current page. The response object is analogous to request object in servlet. Examples: <% response.setContentType("text/html"); %> <% response.sendRedirect(" UNIT-7 WT
44
application object This object is used to hold references to other objects that may be accessed by multiple users. One such object is database connectivity. Represents the ServletContext object in servlet. Methods: getAttribute(), setAttribute(). Examples: <% application.setAttribute("aName","CollPortal"); %> <%= application.getAttribute("aName")%> UNIT-7 WT
45
session object When a JSP page is opened in a browser a unique session identity is allocated for each user accessing that application. Represents HttpSession object in Servlet Methods: getAttribute(), setAttribute(), invalidate(),getId(). UNIT-7 WT
46
exception, page and config object
The exception object is available only to pages which are defined as error pages by setting the value for the attribute “isErrorPage” in the page directive. page This variable is simply a synonym for this and is not very useful in the Java programming language. It was created as a place holder for the time when the scripting language could be something other than Java. config Similar to ServletConfig class UNIT-7 WT
47
pageContext object getException() getPage() getSession() getOut()
Used to organize references to all of the objects involved in creating a jsp page. JSP engine writes the code that obtains the implicit objects from this object. getException() getPage() getOut() getRequest() getResponse() getSession() getServletConfig() getServletContext() UNIT-7 WT
48
Conditional Processing
! <CFIF> <CFIF expression> HTML and CFML tags executed if expression is true <CFELSE> HTML and CFML tags executed if expression is false </CFIF> ! if/else in pure Java (servlet, class,scriptlet) <% if(expression) { // Java code to execute if expression is true } else { // Java code to execute if expression UNIT-7 WT
49
<% if(expression) { %>
! if/else in JSP <% if(expression) { %> HTML and JSP tags executed if expression is true <% } else { %> HTML and JSP tags executed if expression is false <% } %> UNIT-7 WT
50
Conditional Expressions in CF/JSP
! Really about CF vs Java expressions,as in: ! IS vs == or .equals() ! IS NOT vs != UNIT-7 WT
51
<CFLOOP FROM=“1” TO=“10” INDEX=“i”>
<CFOUTPUT>#i#</CFOUTPUT><BR> </CFLOOP> ! “for” loop in pure Java <% for(int i=1; i<=10; i++) { out.println(i + “<BR>”); } %> UNIT-7 WT
52
LECTURE-3 UNIT-7 WT
53
Displaying Values Using an Expression to Set an Attribute
Simpler way to print value of a java variable or expression into HTML page <%= expression %> Goes into _jspService() method Note: no semicolon UNIT-7 WT
54
Expressions- Example <html> <head> <title> Date </title> </head> <body> <% java.util.Date now=new java.util.Date();%> <h2> Server date and time is <%=now %> </h2> </body> </html> Scriplet Expression UNIT-7 WT
55
JSP Declarations Allows the declaration of member variables and methods in JSP source code which finally become part of the generated servlet class. Call back life cycle methods like jspInit() and jspDestroy() are also written inside the declaration. <%! expression %> Note that _jspService() method must not be overridden unless you really know what you are doing! UNIT-7 WT
56
Example: Declaration <html> … <body>Date and Time:<%=getDate()%> <%! int counter=0; java.util.Date getDate(){ return new java.util.Date(); } %> Thank you for visiting this page <BR> You are vistor number <%= ++counter%></body></html> UNIT-7 WT
57
JSP Directives JSP directive are messages that are sent to JSP processor from JSP. These are used to set global values for the jsp page and do not produce any output. directivename attribute=“value” %> The page directive The include directive taglib directives UNIT-7 WT
58
Page directive A page can contain any no. of page directives, anywhere in the jsp. The page directive defines a number of page dependent properties and communicates these to the JSP container. However, there can be only one occurrence of any attribute/value pair defined by the page directive in a given jsp. Only exception is the import attributes. page attribute=“value” %> UNIT-7 WT
59
Attribute List {language=”scriptingLanguage”} { extends=”className” }
{ import=”importList” } { session=”true|false” } { buffer=”none|sizekb” } { autoFlush=”true|false” } { isThreadSafe=”true|false” } buffer: Servers can use a larger buffer than you specify, but not a smaller one. For example, page buffer="32kb" %> means the document content should be buffered and not sent to the client until at least 32 kilobytes have been accumulated or the page is completed. The default buffer size is server specific, but must be at least 8 kilobytes. Depending upon the value of the “autoFlush” attribute, the contents of this buffer is either automatically flushed, or an exception is raised, when overflow would occur.Be cautious about turning off buffering; doing so requires JSP entries that set headers or status codes to appear at the top of the file, before any HTML content isErrorPage: If true, then current jsp page is an error page for another jsp page. Gives access to a JSP implicit exception variable when true to allow an error to be examined and handled. Note: if autoFlush=true then if the contents of the initial Jsp-Writer has been flushed to the ServletResponse output stream then any subsequent attempt to dispatch an uncaught exception from the offending page to an errorPage may fail. When an error page is also indicated in the web.xml descriptor, the JSP error page applies first, then the web.xml page. contentType: Specifies the MIME type to be used for JSP page that is going to be generated. (default: text/html). errorPage: Defines a URL to a resource to which any Java programming language Throwable object(s) thrown but not caught by the page implementation are forwarded for error processing. import: similar to import statement in java class. Classes within the following packages are available by default: java.lang.*, javax.servlet.*, javax.servlet.jsp.*,javax.servlet.http.*. Example: page import=“java.sql.*, java.util.*,javax.naming.*”> session: If true, the implicit object variable session will refer to a session object either already existing for the requesting user, or explicitly created for the page invocation. If false, then any reference to the session implicit object within the JSP page results in a translation-time error. The default is true. If your JSP page is not intended to interact with session objects then creation of session object could be an overhead. If this is the case, then you should ensure that the page session=”false” %> directive tag is included within your JSP. language: In JSP 1.2, the only defined and required scripting language value for this attribute is “java”. extends: The value is a fully qualified Java programming language class name, that names the super class of the class to which this JSP page is transformed. This attribute should not be used without careful consideration as it restricts the ability of the JSP container to provide specialized super classes that may improve on the quality of rendered service. isThreadSafe: Indicates the level of thread safety implemented in the page. If “false” then the JSP container shall dispatch multiple outstanding client requests, one at a time, in the order they were received, to the page implementation for processing.If “true” then the JSP container may choose to dispatch multiple outstanding client requests to the page simultaneously. Note that even if the isThreadSafe attribute is “false” the JSP page author must ensure that accesses to any shared objects are properly synchronized., The objects may be shared in either the ServletContext or the HttpSession. autoFlush:Specifies whether the buffered output should be flushed automatically (“true” value) when the buffer is filled, or whether an exception should be raised (“false” value) to indicate buffer overflow. The default is “true”. Note: it is illegal to set autoFlush to “false” when“buffer=none”. info: Defines an arbitrary string that is incorporated into the translated page, that can subsequently be obtained from the page’s implementation of Servlet.getServletInfo() method. pageEncoding: Defines the character encoding for the JSP page. The CHARSET value of contentType is used as default if present, or ISO otherwise. UNIT-7 WT
60
Attribute List { info=”info_text” } { errorPage=”error_url” }
{ isErrorPage=”true|false” } { contentType=”ctinfo” } { pageEncoding=”peinfo” } UNIT-7 WT
61
Example: using ‘import’
page language=“Java” import=“java.util.*,java.io.*”> <html> <head> <title> Example 1 </title> </head> <body> <% Date now=new Date();%> <h2> Server date and time is <%=now %></h2> </body> </html> UNIT-7 WT
62
LECTURE-4 UNIT-7 WT
63
Declaring Variables and Methods
The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single method of this class.You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions. To add a declaration, you must use the <%! and %> sequences to enclose your declarations, as shown below. UNIT-7 WT
64
<%@ page import="java.util.*" %> <HTML> <BODY>
<%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return theDate; } %> Hello! The time is now <%= getDate() %> </BODY> </HTML> UNIT-7 WT
65
Both of these are available now in our scriptlets and expressions.
The example has been created a little contrived, to show variable and method declarations.Here we are declaring a Date variable theDate, and the method getDate. Both of these are available now in our scriptlets and expressions. But this example no longer works! The date will be the same, no matter how often you reload the page. This is because these are declarations, and will only be evaluated once when the page is loaded! (Just as if you were creating a class and had variable initialization declared in it.) Exercise: Modify the above example to add another function computeDate which re-initializes theDate. Add a scriptlet that calls computeDate each time. UNIT-7 WT
66
Note: Now that you know how to do this -- it is in general not a good idea to use variables as shown here. The JSP usually will run as multiple threads of one single instance. Different threads would interfere with variable access, because it will be the same variable for all of them. If you do have to use variables in JSP, you should use synchronized access, but that hurts the performance. In general, any data you need should go either in the session object or the request object (these are introduced a little later) if passing data between different JSP pages. Variables you declare inside scriptlets are fine. e.g. <% int i = 45; %> because these are declared inside the local scope and are not shared. UNIT-7 WT
67
Users Passing Control and Date between Pages
The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single method of this class. You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions. To add a declaration, you must use the <%! and %> sequences to enclose your declarations, as shown below. UNIT-7 WT
68
System.out.println( "In getDate() method" );
page import="java.util.*" %> <HTML> <BODY> <%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return theDate; } %> Hello! The time is now <%= getDate() %> </BODY> </HTML> UNIT-7 WT
69
The example has been created a little contrived, to show variable and method declarations.
Here we are declaring a Date variable theDate, and the method getDate. Both of these are available now in our scriptlets and expressions. UNIT-7 WT
70
But this example no longer works
But this example no longer works! The date will be the same, no matter how often you reload the page. This is because these are declarations, and will only be evaluated once when the page is loaded! (Just as if you were creating a class and had variable initialization declared in it.) UNIT-7 WT
71
LECTURE-5 UNIT-7 WT
72
Error Handling and Debugging
UNIT-7 WT
73
Example: Runtime Error handling
page contentType="text/html" %> page errorPage="error.jsp" %> <html><head><title>Error Handling</title></head> <body> <form method="post" action="divide.jsp"> Number1: <input type="text" name="num1"> divided by Number2: <input type="text" name="num2"> <input type="submit" value="="> UNIT-7 WT
74
Result: <input type="text" name="result" value="
<% String num1=request.getParameter("num1"); String num2=request.getParameter("num2"); if (num1!=null && num2!=null){ int n1=Integer.parseInt(num1); int n2=Integer.parseInt(num2); int r= n1/n2; out.print( r); } } %> "> </form> </body> </html> UNIT-7 WT
75
<%@ page contentType="text/html" %>
error.jsp page contentType="text/html" %> page isErrorPage="true" %> <html> <head><title>Error Handling</title></head> <body> Error: <%= exception.getMessage() %> </body> </html> UNIT-7 WT
76
<%! public void jspInit() { //some initialization code } %>
JSP declarations let you define page-level variables to save information or define supporting methods that the rest of a JSP page may need. While it is easy to get led away and have a lot of code within your JSP page, this move will eventually turn out to be a maintenance nightmare. For that reason, and to improve reusability, it is best that logic-intensive processing is encapsulated as JavaBean components. Declarations are found within the <%! ... %> tag. Always end variable declarations with a semicolon, as any content must be valid Java statements: <%! int i=0; %> You can also declare methods. For example, you can override the initialization event in the JSP life cycle by declaring: <%! public void jspInit() { //some initialization code } %> UNIT-7 WT
77
JSP provides a rather elegant mechanism for handling runtime exceptions. Although you can provide your own exception handling within JSP pages, it may not be possible to anticipate all situations. By making use of the page directive's errorPage attribute, it is possible to forward an uncaught exception to an error handling JSP page for processing. For example, page isErrorPage="false" errorPage="errorHandler.jsp" %> informs the JSP engine to forward any uncaught exception to the JSP page errorHandler.jsp. It is then necessary for errorHandler.jspto flag itself as a error processing page using the directive: page isErrorPage="true" %> This allows the Throwable object describing the exception to be accessed within a scriptlet through the implicit exception object. UNIT-7 WT
78
Installing and Configuring Tomcat Skeleton Code errhandler.jsp
This exercise implements a JSP page (errhandler.jsp), which processes a POST operation and throws an exception in case of an "incorrect" answer. You will see how these exceptions can be automatically forwarded by the JSP engine to an "error handler." You also develop an error processing JSP page (errorpage.jsp), which receives the exception by means of the exception implicit variable. Prerequisites Installing and Configuring Tomcat Skeleton Code errhandler.jsp errorpage.jsp UNIT-7 WT
79
5. Deploy the JSP files for the example within Tomcat.
Tasks 1. Design a JSP page called errhandler.jsp that can process a POST operation. 2. Indicate an error page, errorpage.jsp, using the page directive for the JSP page. 3. Process the posted form elements. Throw an exception if the value posted for the input element is not equal to an expected value, else print an acknowledgment back to the user. 4. Develop an error page, errorpage.jsp, which can access the runtime exception. 5. Deploy the JSP files for the example within Tomcat. 6. Run the error handling example. Where help exists, the task numbers above are linked to the step-by-step help page. UNIT-7 WT
80
Solution Source The following files contain a complete implementation of the JSP error handling example: errhandler.jsp errorpage.jsp UNIT-7 WT
81
You should see an HTML form as shown below:
Demonstration From your browser, access the URLhttp://localhost:8080/examples/jsp/jdc/errHandling/errhandler.jsp You should see an HTML form as shown below: UNIT-7 WT
82
UNIT-7 WT
83
Now, make a selection and submit the form
Now, make a selection and submit the form. If you made an incorrect selection, an exception is thrown and the request is forwarded to the error handler page, which extracts and displays the exception: UNIT-7 WT
84
UNIT-7 WT
85
If you made the right choice, you get an acknowledgment from the JSP page itself:
UNIT-7 WT
86
Include directive This tag is useful to merge the content of an external static file with the contents of a JSP page. Including data is a significant part of the tasks in a JSP page. include file=“filename” %> Example: include file=“agreement.txt” %> include file=“date.jsp” %> The included file may contain any valid JSP tags. These tags will be translated to Java source and included in the JSP page compilation class. One consequence of the fact that the file referenced within the include directive is included during the translation phase is that subsequent changes to the included file will not be picked up by the Web container on subsequent invocations of the JSP. The changes will only be visible when the JSP containing the include directive is itself updated, or its JSP page compilation class is deleted, forcing the translation phase to be carried out. UNIT-7 WT
87
JSP Include Directive Includes a static file
include file=“relativeURL” %> Example: main.jsp: <html><body> Current date and time is: file=“date.jsp” %> </body></html> date.jsp: import =“java.util.*” %> <% =(new java.util.Date()).toLocaleString() %> Output : Current date and time is: Mar 5, :56:50 UNIT-7 WT
88
LECTURE-6 UNIT-7 WT
89
Sharing Data Between JSP Pages, Requests
With the <jsp:forward> tag, you can redirect the request to any JSP, servlet, or static HTML page within the same context as the invoking page. This effectively halts processing of the current page at the point where the redirection occurs, although all processing up to that point still takes place: <jsp:forward page="somePage.jsp" /> The invoking page can also pass the target resource bean parameters by placing them into the request, UNIT-7 WT
90
As shown in the diagram:
UNIT-7 WT
91
<jsp:forward page="<%= somePage %>" >
A <jsp:forward> tag may also have jsp:param subelements that can provide values for some elements in the request used in the forwarding: <jsp:forward page="<%= somePage %>" > <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" /> </jsp:forward> UNIT-7 WT
92
Request Chaining Request chaining is a powerful feature and can be used to effectively meld JSP pages and servlets in processing HTML forms, as shown in the following figure: UNIT-7 WT
93
<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/>
Consider the following JSP page, say Bean1.jsp, which creates a named instance fBean of type FormBean, places it in the request, and forwards the call to the servlet JSP2Servlet. Observe the way the bean is instantiated--here we automatically call the bean's setter methods for properties which match the names of the posted form elements, while passing the corresponding values to the methods. <jsp:useBean id="fBean" class="govi.FormBean" scope="request"/> <jsp:setProperty name="fBean" property="*" /> <jsp:forward page="/servlet/JSP2Servlet" /> UNIT-7 WT
94
The servlet JSP2Servlet now extracts the bean passed to it from the request, makes changes using the appropriate setters, and forwards the call to another JSP page Bean2. jsp using a request dispatcher. Note that this servlet, acting as a controller, can also place additional beans if necessary, within the request. UNIT-7 WT
95
FormBean f = (FormBean) request.getAttribute ("fBean");
public void doPost (HttpServletRequest request, HttpServletResponse response) { try { FormBean f = (FormBean) request.getAttribute ("fBean"); f.setName("Mogambo"); // do whatever else necessary getServletConfig(). getServletContext() getRequestDispatcher("/jsp/Bean2.jsp"). forward(request, response); } catch (Exception ex) { . . . } UNIT-7 WT
96
The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans that may have been passed by the controller servlet) from the request and extract its properties. UNIT-7 WT
97
For example: <jsp:include page="shoppingcart.jsp" flush="true"/>
not only allows shoppingcart.jsp to access any beans placed within the request using a <jsp:useBean> tag, but the dynamic content produced by it is inserted into the calling page at the point where the <jsp:include> tag occurs. The included resource, however, cannot set any HTTP headers, which precludes it from doing things like setting cookies, or else an exception is thrown. UNIT-7 WT
98
LECTURE-7 UNIT-7 WT
99
Sharing Session and Application Data
By default, all JSP pages participate in an HTTP session. The HttpSession object can be accessed within scriptlets through the sessionimplicit JSP object. Sessions are a good place for storing beans and objects that need to be shared across other JSP pages and servlets that may be accessed by the user. The session objects is identified by a session ID and stored in the browser as a cookie. If cookies are unsupported by the browser, then the session ID may be maintained by URL rewriting. Support for URL rewriting is not mandated by the JSP specification and is supported only within a few servers. Although you cannot place primitive data types into the session, you can store any valid Java object by identifying it by a unique key. For example: UNIT-7 WT
100
<% Foo myFoo = (Foo) session.getValue("foo"); %>
<% Foo foo = new Foo(); session.putValue("foo",foo); %> makes available the Foo instance within all JSP pages and servlets belonging to the same session. The instance may be retrieved within a different JSP page as: <% Foo myFoo = (Foo) session.getValue("foo"); %> The call to session.getValue() returns a reference to the generic Object type. Thus it is important to always cast the value returned to the appropriate data type before using it. It is not mandatory for JSP pages to participate in a session; they may choose to opt out by setting the appropriate attribute of the page directive: UNIT-7 WT
101
page session="false" %> There is no limit on the number of objects you can store into the session. However, placing large objects into the session may degrade performance, as they take up valuable heap space. By default, most servers set the lifetime of a session object to 30 minutes, although you can easily reset it on a per session basis by invoking setMaxInvalidationInterval(int secs) on the session object. The figure below highlights the general architecture of session management: UNIT-7 WT
102
. UNIT-7 WT
103
The JSP engine holds a live reference to objects placed into the session as long as the session is valid. If the session is invalidated or encounters a session timeout, then the objects within are flagged for garbage collection UNIT-7 WT
104
First we have a form, let us call it GetName.html
On a typical web site, a visitor might visit several pages and perform several interactions. If you are programming the site, it is very helpful to be able to associate some data with each visitor. For this purpose, "session"s can be used in JSP. A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site. Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out installing and using these. First we have a form, let us call it GetName.html UNIT-7 WT
105
First we have a form, let us call it GetName
First we have a form, let us call it GetName.html <HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML> UNIT-7 WT
106
<% String name = request.getParameter( "username");
The target of the form is "SaveName.jsp", which saves the user's name in the session. Note the variable "session". This is another variable that is normally made available in JSPs, just like out and request variables. (In directive, you can indicate that you do not need sessions, in which case the "session" variable will not be made available.) <% String name = request.getParameter( "username"); session.setAttribute( "theName", name ); %> <HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML> UNIT-7 WT
107
Hello, <%= session.getAttribute( "theName" ) %> </BODY>
The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp. NextPage.jsp shows how to retrieve the saved name. <HTML> <BODY> Hello, <%= session.getAttribute( "theName" ) %> </BODY> </HTML> UNIT-7 WT
108
If you bring up two different browsers (not different windows of the same browser), or run two browsers from two different machines, you can put one name in one browser and another name in another browser, and both names will be kept track of. The session is kept around until a timeout period. Then it is assumed the user is no longer visiting the site, and the session is discarded UNIT-7 WT
109
LECTURE-8 UNIT-7 WT
110
Memory Usage Considerations
Well, you got your application running in your localhost test system. It gives the right results and doesn’t throw exceptions, so you must be finished with debugging, right? Wrong, There are still plenty of bugs that can become apparent only after it has been running a while. For example, you might have a memory leak due if objects are being put into a Vector or Hashtable and are never removed. If each object is only a hundred bytes, it will take many UNIT-7 WT
111
A Thread leak might occur if every request creates a Thread to carry out some task but you have neglected to provide a way for the Thread to exit the run method and die normally. After a few thousand Thread objects have accumulated, the application may get very odd. What you need for this kind of debugging is a way to remotely monitor memory and UNIT-7 WT
112
Thread usage in a running server
Thread usage in a running server. That way you can look in from time to time and watch for trends that might indicate a bug. Listing 5.19 shows memory.jsp, a simple JSP that can display the current servlet engine Threads and Java Virtual Machine memory usage. UNIT-7 WT
113
<HTML><HEAD>
The memory.jsp source <HTML><HEAD> <TITLE>Memory Usage Monitor</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"><FONT FACE=VERDANA> <H2 ALIGN=CENTER> Thread And Memory Status </H2><BR> page language="java" import="java.util.*" %> <%! String brcrlf = "<br>\r\n"; %> <% UNIT-7 WT
114
ThreadGroup tg = Thread.currentThread().getThreadGroup();
Thread[] thrds = new Thread[ tg.activeCount() ] ; tg.enumerate( thrds ); // fills array %><h3> Active Thread Count: <%= thrds.length + brcrlf %></h3> <ul> <% for( int i = 0 ; i < thrds.length ; i++ ){ out.print("<li>"); out.print( thrds[i].toString() ); out.print( brcrlf ); } %> UNIT-7 WT
115
</ul><h3>Memory Usage</h3> <%
Runtime rt = Runtime.getRuntime(); out.print("Total memory: " + rt.totalMemory() + brcrlf + " Free memory: " + rt.freeMemory() + brcrlf ); %> <%= new Date().toString() %><br> </BODY> </HTML> UNIT-7 WT
116
server using this JSP is shown in Figure 5.5.
This page uses the fact that all Thread objects created in a servlet engine typically belong to the same ThreadGroup. The toString method displays the name of the Thread, its priority, and the name of the ThreadGroup it belongs to. Example output from the Tomcat Web server using this JSP is shown in Figure 5.5. UNIT-7 WT
117
Output from memory.jsp on a Tomcat server
UNIT-7 WT
118
Note that some of the Thread objects shown in Figure 5
Note that some of the Thread objects shown in Figure 5.5 are named “StandardManager” and some are named “Thread-n” where n is a sequence number. The sequence number naming style is the default for Thread objects created without a programmer-supplied name. If your application creates any Thread objects, you should name them so that they will stand out in this listing. UNIT-7 WT
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.