Module-Iv Java Server Pages
Module-Iv Java Server Pages
Java Server Pages Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations. But most CGI variations, including servlets, make you generate the entire page via your program, even though most of it is always the same. JSP lets you create the two parts separately. The Advantage of Servlets Over "Traditional" CGI Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies.
Efficient
With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.
Convenient
Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.
Powerful
Java servlets easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful thing like database connection pools easy to implement. They can
also maintain information from request to request, simplifying things like session tracking and caching of previous computations.
Portable
Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or Web Star. Servlets are supported directly or via a plug-in on almost every major Web server.
Inexpensive
There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap. The separation of user interface and program logic in a JSP page allows for a very convenient delegation of tasks between web content authors and developers. It also allows developers to create flexible code that can easily be updated and reused. Because JSP pages are automatically compiled as needed, web authors can make changes to presentation code without recompiling application logic. This makes JSP a more flexible method of generating dynamic web content than Java servlets, whose functionality Java Server Pages extend.
While JSP pages mainly provide a higher-level method of creating servlets, they bring other benefits as well. Advantages of using JSP are:
JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content. JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired. JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax. Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.
In general, JSP allows developers to easily distribute application functionality to a wide range of page authors. These authors do not have to know the Java programming language or know anything about writing servlet code, so they can concentrate on writing their HTML code while you concentrate on creating your objects and application logic. JSP Advantages Separation of static from dynamic content: With servlets, the logic for generation of the dynamic content is an intrinsic part of the servlet itself, and is closely tied to the static presentation templates responsible for the user interface. Thus, even minor changes made to the UI typically result in there compilation of the servlet. This tight coupling of presentation and content results in brittle, inflexible applications. However, with JSP, the logic to generate the dynamic content is kept separate from the static presentation templates by encapsulating it within external JavaBeans components. These are then created and used by the JSP page using special tags and scriptlets. When a page designer makes any changes to the presentation template, the JSP page is automatically recompiled and reloaded into the web server by the JSP engine. Write Once Run Anywhere:
JSP technology brings the "Write Once, Run Anywhere" paradigm to interactive Web pages. JSP pages can be moved easily across platforms, and across web servers, without any changes. Dynamic content can be served in a variety of formats: There is nothing that mandates the static template data within a JSP page to be of a certain format. Consequently, JSP can service a diverse clientele ranging from conventional browsers using HTML/DHTML, to handheld wireless devices like mobile phones and PDAs using WML, to other B2B applications using XML. First JSP JSP simply puts Java inside HTML pages. We can take any existing HTML page and change its extension to ".jsp" instead of ".html". What is happening behind the scenes is that the JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But every time we change the JSP file, it will be re-compiled again.) Ex: <HTML> <BODY> Hello! Our First JSP </BODY> </HTML>
Adding dynamic content via expressions As in the previous section, any HTML file can be turned into a JSP file by changing its extension to .jsp. Of course, what makes JSP useful is the ability to embed Java. Put the following text in a file with .jsp extension (let us call it hello.jsp), place it in the JSP directory, and view it in a browser. <HTML> <BODY> Hello! The time is now <%= new java.util.Date() %> </BODY> </HTML> Notice that each time we reload the page in the browser; it comes up with the current time. The character sequences <%= and %> enclose Java expressions, which are evaluated at run time. This is what makes it possible to use JSP to generate dynamic HTML pages that change in response to user actions or vary from user to user.
Converting the JSP page to a servlet and compiling the servlet form the translation phase. The JSP container initiates the translation phase for a page automatically when it receives the first request for the page. Since the translation phase takes a bit of time, the first user to request a JSP page notices a slight delay. The translation phase can also be initiated explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP page is a way to avoid hitting the first user with this delay.This occurs only when JSP file is requested for first time or if it undergoes any change to the extent of getting retranslated or recompiled.For each additional request of JSP page,request directly goes to the servlet byte code which is in memory. The JSP container is also responsible for invoking the JSP page implementation class (the generated servlet) to process each request and generate the response. This is called the request processing phase. When the request comes for the servlet, an init() is called when a servlet is loaded into virtual machine to perform global initialization.Then individual requests are sent to service() where response is put. Servlet creates new thread to run service() for each request.Request from browser converted into java object of type HttpServletRequest passes to servlet along with HttpServletResponse object send back to browser.Servlet code performs operations in jsp file.The two phases are illustrated in the figure given below.
JSP page translation and processing phases JSP Elements There are three types of JSP elements: scripting, directive and action JSP Scripting Elements JSP scripting elements enable us to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: 1. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods. 2. Expressions of the form <%= expression %> that are evaluated and inserted into the output. 3. Scriptlets of the form <% code %> that are inserted into the servlet's service method.
Declaration Declares a variable or method valid in the scripting language used in the JSP page. JSP Syntax <%! declaration; [ declaration;] + ... %> Examples <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>
Description A declaration declares one or more variables or methods that can use in Java code later in the JSP file. We must declare the variable or method before use it in the JSP file. We can declare any number of variables or methods within one declaration element, as long as we end each declaration with a semicolon. The declaration must be valid in the Java programming language. When we write a declaration in a JSP file, remember these rules:
We must end the declaration with a semicolon .We can already use variables or methods that are declared in packages imported by the <%@ page %> directive, without declaring them in a declaration element.
A declaration has translation unit scope, so it is valid in the JSP page and any of its static includes files. A static include file becomes part of the source of the JSP page and is any file included with an <%@ include %> directive or a static file included with a <jsp: include> element. The scope of a declaration does not include dynamic files included with <jsp: include>. Expression Contains an expression valid in the scripting language used in the JSP page. JSP Syntax <%= expression %> Examples Current time: <%= new java.util.Date () %> Description An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, we can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file. When we write expressions in a JSP file, remember these points:
We cannot use a semicolon to end an expression (however, the same expression within a scriptlet requires the semicolon). The expression element can contain any expression that is valid according to the Java Language Specification.
We can sometimes use expressions as attribute values in JSP elements. An expression can be complex and composed of more than one part or expression. The parts of an expression are evaluated in left-to-right order. Scriptlets JSP Syntax <% code fragment %> Description A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within a scriptlet, we can do any of the following:
Declare variables or methods to use later in the file. Write expressions valid in the page scripting language. Use any of the implicit objects or any object declared with a <jsp:useBean> element. Write any other statement valid in the scripting language used in the JSP page.
Any text, HTML tags, or JSP elements must be outside the scriptlet. Scriptlets are executed at request time, when the JSP container processes the client request. If the scriptlet produces output, the output is stored in the out object. E.g. <HTML> <BODY> <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <%= date %> </BODY> </HTML> If we run the above example, we will notice the output from the "System.out.println" on the server log. This is a convenient way to do simple debugging. By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a variable called "out". This variable does not need to
be declared. It is already predefined for scriptlets, along with some other variables. The following example shows how the scriptlet can generate HTML output. <HTML> <BODY> <% // This scriptlet declares and initializes "date" System.out.println (Evaluating date now); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% // This scriptlet generates HTML output out.println (String.valueOf (date)); %> </BODY> </HTML> Directive elements The directive elements specify information about the page itself that remains the same between requests--for example, if session tracking is required or not, buffering requirements, and the name of a page that should be used to report errors, if any.
JSP Directives A JSP directive affects the overall structure of the servlet class. It usually has the following form: <%@ directive attribute="value" %> However, we can combine multiple attribute settings for a single directive, as follows: <%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %> The three main types of directives are: page directive, include directive and tag lib directive. Element
<%@ page ... %>
Description Defines page-dependent attributes, such as session tracking, error page, and buffering requirements
Includes a file during the translation phase Declares a tag library, containing custom actions, that is used in the page
packages should be imported. For example: <%@ page import="java.util.*" %> The import attribute is the only one that is allowed to appear multiple times.
contentType="MIME-Type" charset=Character-Set. The default is text/html.
as the scriptlet
isThreadSafe="true|false".
A value of true (the default) indicates normal servlet processing, where multiple requests can be processed simultaneously with a single servlet instance, under the assumption that the author synchronized access to instance variables. A value of false indicates that the servlet should implement SingleThreadModel, with requests either delivered serially or with simultaneous requests being given separate servlet instances.
session="true|false". A value of true (the default) indicates that the predefined variable session (of type HttpSession) should be bound to the
existing session if one exists, otherwise a new session should be created and bound to it. A value of false indicates that no sessions will be used, and attempts to access the variable session will result in errors at the time the JSP page is translated into a servlet.
buffer="sizekb|none". This specifies the buffer size for the JspWriter out. The default is server-specific, but must be at least 8kb. autoflush="true|false".
A value of true, the default, indicates that the buffer should be flushed when it is full. A value of false, rarely used, indicates that an exception should be thrown when the buffer overflows. A value of false is illegal when also using buffer="none".
extends="package.class".
This indicates the superclass of servlet that will be generated. Use this with extreme caution, since the server may be using a custom superclass already.
info="message". This defines getServletInfo method.
errorPage="url". This specifies a JSP page that should Throwables thrown but not caught in the current page. isErrorPage="true|false".
This indicates whether or not the current page can act as the error page for another JSP page. The default is false.
language="java".
At some point, this is intended to specify the underlying language being used. For now, don't bother with this since java is both the default and the only legal choice.
The XML syntax for defining directives is <jsp:directive.directiveType attribute=value /> For example, the XML equivalent of <%@ page import="java.util.*" %> is <jsp:directive.page import="java.util.*" />
Standard action elements Action elements typically perform some action based on information that is required at the exact time the JSP page is requested by a browser. An action can, for instance, access parameters sent with the request to do a database lookup. It can also dynamically generate HTML, such as a table filled with information retrieved from an external system. The JSP specification defines a few standard action elements, listed in the below table:
Action element
Description <jsp:useBean> Makes a JavaBeans component available in a page Gets a property value from a JavaBeans component and adds it to the <jsp:getProperty> response <jsp:setProperty> Sets a JavaBeans component property value Includes the response from a servlet or JSP page during the request <jsp:include> processing phase <jsp:forward> Forwards the processing of a request to servlet or JSP page Adds a parameter value to a request handed off to another servlet or <jsp:param> JSP page using <jsp:include> or <jsp:forward>
<jsp:plugin>
Generates HTML that contains the appropriate browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software
type beanName
Specifies the type of the variable that will refer to the object. This must match the classname or be a superclass or an interface that the class implements. Remember that the name of the variable is designated via the id attribute. Gives the name of the bean, as supply it to the instantiate method of Beans. It is permissible to supply a type and a beanName, and omit the class attribute.
Then we can use jsp:setProperty and jsp:getProperty to modify and retrieve bean properties.
<jsp:useBean id="myName" ... /> ... <jsp:setProperty name="myName" property="someProperty" ... /> In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found. A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below: <jsp:useBean id="myName" ... > ... <jsp:setProperty name="myName" property="someProperty" ... /> </jsp:useBean> There are four possible attributes of jsp:setProperty: Attribute
name
Usage This required attribute designates the bean whose property will be set. The jsp:useBean element must appear before the jsp:setProperty element.
property
This required attribute indicates the property you want to set. However, there is one special case: a value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods. This optional attribute specifies the value for the property. String values are automatically converted to numbers, boolean, Boolean, byte, Byte, char, and Character via the standard valueOf method in the target or wrapper class. This optional attribute designates the request parameter from which the property should be derived. If the current request has no such parameter, nothing is done: the system does not pass null to the setter method of the property. Thus, it let the bean itself supply default values, overriding them only when the request parameters say to do so. E.g. <jsp:setProperty name="orderBean" property="numberOfItems" param="numItems" />
value
param
We can modify its properties via jsp:setProperty, or by using a scriptlet and calling a method explicitly on the object with the variable name specified earlier via the id attribute. Recall that with beans, when we say "this bean has a property of typeX called foo", we really mean "this class has a method called getFoo that returns something of type X, and another method called setFoo that takes an X as an argument." We can supply an explicit value, give a param attribute to say that the value is derived from the named request parameter, or just list the property to indicate that the value should be derived from the request parameter with the same name as the property. We read existing properties in a JSP expression or scriptlet by calling the appropriate getXxx method or more commonly, by using the jsp:getProperty action.
<jsp:useBean id="itemBean" ... /> ... <UL> <LI>Number of items: <jsp:getProperty name="itemBean" property="numItems" /> <LI>Cost of each: <jsp:getProperty name="itemBean" property="unitCost" /> </UL> Here is a very simple example that loads a bean and sets/gets a simple String parameter.
BeanTest.jsp
<HTML> <HEAD> <TITLE>Reusing JavaBeans in JSP</TITLE> </HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE"> Reusing JavaBeans in JSP</TABLE> </CENTER> <P> <jsp:useBean id="test" class="hall.SimpleBean" /> <jsp:setProperty name="test" property="message" value="Hello WWW" /> <H1>Message: <I> <jsp:getProperty name="test" property="message" /> </I></H1> </BODY> </HTML>
SimpleBean.java
Here's the source code for the bean used in the BeanTest JSP page. package hall; public class SimpleBean { private String message = "No message specified"; public String getMessage() {
return(message); } public void setMessage(String message) { this.message = message; } } Predefined Variables (IMPLICIT OBJECTS) To simplify code in JSP expressions and scriptlets, there are eight automatically defined variables, sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. Details for each are given below.
request
This is the HttpServletRequest associated with the request, and the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in practice. headers, even though this is not permitted in regular servlets once any output has been sent to the client.
out
This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. We can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly.
response
This is the HttpServletResponse associated with the response to the client. Note that, since the output stream is buffered, it is legal to set HTTP status codes and response
Beans and Form processing (How beans are accessed via scriplets?) Forms are a very common method of interactions in web sites. JSP makes forms processing specially easy. The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. We just need to define a class that has a field corresponding to each field in the form. The class fields must have "setters" that match the names of the form fields. For instance, consider GetName.html to collect email address and age. The new version of GetName.html is <HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR> What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR> What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML> To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter" method is just a method that starts with "set" followed by the name of the field. The first character of the field name is upper-cased. So if the field is "email", its "setter" method will be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that the setters (and getters) must be public. public class UserData { String username; String email; int age; public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value )
{ age = value; } public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } } The method names must be exactly as shown. Once we have defined the class, compile it and make sure it is available in the web-server's classpath. The server may also define special folders where we can place bean classes. Now let us change "SaveName.jsp" to use a bean to collect the data. <jsp:useBean id="user" class="UserData" scope="session"/> <jsp:setProperty name="user" property="*"/> <HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML> All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag! The useBean tag will look for an instance of the "UserData" in the session. If the instance is already there, it will update the old instance. Otherwise, it will create a new instance of UserData (the instance of the UserData is called a bean), and put it in the session. The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!
NextPage.jsp
<jsp:useBean id="user" class="UserData" scope="session"/> <HTML> <BODY> You entered<BR> Name: <%= user.getUsername() %><BR> Email: <%= user.getEmail() %><BR> Age: <%= user.getAge() %><BR> </BODY> </HTML>
Notice that the same useBean tag is repeated. The bean is available as the variable named "user" of class "UserData". The data entered by the user is all collected in the bean. SCOPES
Bean last longer than a single page through lifetime specification These lifetime is called scopes Scope is period of activity during which bean is available Types:
1. Page : Smallest scope Available only within JSP form created Spanning a single JSP file If jsp:include tag used under page scope and invokes a bean then each page gets different instance of the bean Eg: //page1.jsp <html> </body> <jsp:useBean id=bean1 class=test.AnimalBean scope=page/> At first our animal is: <jsp:getProperty name=bean1 property=animal/> <jsp:setProperty name=bean property=animal value=dog/> After setting animal is <jsp:getProperty name=bean1 property=animal/>
<jsp:include page=page2.jsp/> </body> </html> //page2.jsp <html> <body> <jsp:useBean id=bean1 class=test.AnimalBean scope=page/> After the include, the animal is: <jsp:getProperty name=bean1 property=animal/>
</body> </html> //AnimalBean.java public class AnimalBean { String animal; public void setanimal( String value ) { animal = value; } public int getanimal () { return animal; } } Suppose animal is cat that is set through AnimalBean.java the output of the jsp will be as follows: At first our animal is: cat After setting animal is: dog After the include, the animal is: cat This is because under page scope when a bean is invoked each page gets different instance of the bean.
2. Request Scope: Larger than page scope Beans created in request scope will last from the time they are first created until the last fo the data is sent to the user Same instace included in all included files //page1.jsp <html> </body> <jsp:useBean id=bean1 class=test.AnimalBean scope=request/> At first our animal is: <jsp:getProperty name=bean1 property=animal/> <jsp:setProperty name=bean property=animal value=dog/> After setting animal is <jsp:getProperty name=bean1 property=animal/> <jsp:include page=page2.jsp/> </body> </html> //page2.jsp <html> <body> <jsp:useBean id=bean1 class=test.AnimalBean scope=page/> After the include, the animal is: <jsp:getProperty name=bean1 property=animal/>
</body> </html> //AnimalBean.java public class AnimalBean { String animal; public void setanimal( String value ) { animal = value; } public int getanimal () { return animal; } } Suppose animal is cat that is set through AnimalBean.java the output of the jsp will be as follows: At first our animal is: cat After setting animal is: dog After the include, the animal is: dog This is because under session scope when a bean is invoked each page gets same instance of the bean. 3) Session scope Request and page are associated with pages or pieces of pages When users are focused, a way to tie data to a particulaer user and will be available and adjustable from the user visits Session corresponds to the period of time the user spends at a site This period is defined as extending from the first visit to the site, through the point at which the user hasnt accessed any pages on the site for more than half an hour.Hence session expire and any bean in the session scope will disappear Eg: <html> </body> <jsp:useBean id=counter class=test.CounterBean scope=session/>
<jsp:getProperty name=counter property=count value=1/> You have visited this page: <jsp:getProperty name= counter property= count/> time(s) Session scope extends multiple pages or individual pages multiple times CounterBean class increments the value when user clicks reload button and keeps bean around even after page completes. If page/request used counter gets struck at 1. 4) Application scope: Largest available scopes Available to all pages, for all users, until web application is shutdown or restarted Displays global information like quote of day(usually seen bottom of every page of a particular site