JSP Notes
JSP Notes
Unit-7
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files. JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested. JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc. JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.
Advantages of JSP:
Following is the list of other advantages of using JSP over other technologies:
vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers. 1
Unit-7
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like. vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc. vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
JSP - Architecture
The web server needs a JSP engine ie. container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to support JSP pages development. A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html. 2
Unit-7
The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior of the page. The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response. The web server forwards the HTTP response to your browser in terms of static HTML content. Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents. This makes the process more efficient than with other scripting languages (such as PHP) and therefore faster. So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet
Unit-7
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. The following are the paths followed by a JSP
The three major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
Unit-7
Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
Unit-7
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:
<html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html>
NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is setup as per environment setup tutorial. Let us keep above code in JSP file hello.jsp and put this file in C:\apache-tomcat7.0.2\webapps\ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate following result:
M.Gangappa, Assoc Prof, CSE, VNR VJIET
Unit-7
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Following is the syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>
JSP Expression:
A JSP 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, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file. The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
M.Gangappa, Assoc Prof, CSE, VNR VJIET
Unit-7
JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. Following is the syntax of JSP comments:
<%-- This is JSP comment --%>
Unit-7
A Test of Results
There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary: Syntax <%-- comment --%> <!-- comment --> <\% %\> \' \" Purpose A JSP comment. Ignored by the JSP engine. An HTML comment. Ignored by the browser. Represents static <% literal. Represents static %> literal. A single quote in an attribute that uses single quotes. A double quote in an attribute that uses double quotes.
JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
There are three types of directive tag: Directive <%@ page ... %> <%@ include ... %> <%@ taglib ... %> Description Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. Includes a file during the translation phase. Declares a tag library, containing custom actions, used in the page
JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
M.Gangappa, Assoc Prof, CSE, VNR VJIET
Unit-7
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available: Syntax jsp:include jsp:include jsp:useBean jsp:setProperty jsp:getProperty jsp:forward jsp:plugin jsp:element jsp:attribute jsp:body jsp:text Purpose Includes a file at the time the page is requested Includes a file at the time the page is requested Finds or instantiates a JavaBean Sets the property of a JavaBean Inserts the property of a JavaBean into the output Forwards the requester to a new page Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin Defines XML elements dynamically. Defines dynamically defined XML element's attribute. Defines dynamically defined XML element's body. Use to write template text in JSP pages and documents.
Unit-7
This is the HttpSession object associated with the request. This is the ServletContext object associated with application context. This is the ServletConfig object associated with the page. This encapsulates use of server-specific features like higher performance JspWriters. This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. The Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.
Control-Flow Statements:
JSP provides full power of Java to be embeded in your web application. You can use all the APIs and building blocks of Java in your JSP programming including decision making statements, loops etc.
Decision-Making Statements:
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between Scriptlet tags.
<%! int day = 3; %> <html> <head><title>IF...ELSE Example</title></head> <body> <% if (day == 1 | day == 7) { %> <p> Today is weekend</p> <% } else { %> <p> Today is not weekend</p> <% } %> </body> </html>
11
Unit-7
Now look at the following switch...case block which has been written a bit differentlty using out.println() and inside Scriptletas:
<%! int day = 3; %> <html> <head><title>SWITCH...CASE Example</title></head> <body> <% switch(day) { case 0: out.println("It\'s Sunday."); break; case 1: out.println("It\'s Monday."); break; case 2: out.println("It\'s Tuesday."); break; case 3: out.println("It\'s Wednesday."); break; case 4: out.println("It\'s Thursday."); break; case 5: out.println("It\'s Friday."); break; default: out.println("It's Saturday."); } %> </body> </html>
Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and dowhile blocks in your JSP programming. Let us look at the following for loop example:
<%! int fontSize; %> <html> <head><title>FOR LOOP Example</title></head> <body> <%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
12
Unit-7
JSP
Tutorial
JSP Tutorial Above example can be written using while loop as follows:
<%! int fontSize; %> <html> <head><title>WHILE LOOP Example</title></head> <body> <%while ( fontSize <= 3){ %> <font color="green" size="<%= fontSize %>"> JSP Tutorial </font><br /> <%fontSize++;%> <%}%> </body> </html>
JSP
Tutorial
JSP Tutorial
JSP Operators:
JSP supports all the logical and arithmatic operators supported by Java. Following table give a list of all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first. Category Postfix Unary Operator () [] . (dot operator) ++ - - ! ~ Associativity Left to right Right to left 13
Unit-7
Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right
JSP Literals:
The JSP expression language defines the following literals:
Boolean: true and false Integer: as in Java Floating point: as in Java String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\. Null: null
JSP - Directives
JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form:
14
Unit-7
Directives can have a number of attributes which you can list down as key-value pairs and separated by commas. The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional. There are three types of directive tag: Directive <%@ page ... %> <%@ include ... %> <%@ taglib ... %> Description Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. Includes a file during the translation phase. Declares a tag library, containing custom actions, used in the page
Attributes:
Following is the list of attributes associated with page directive: Attribute buffer autoFlush Purpose Specifies a buffering model for the output stream. Controls the behavior of the servlet output buffer. 15
Unit-7
Defines the URL of another JSP that reports on Java unchecked runtime exceptions. Indicates if this JSP page is a URL specified by another JSP page's errorPage attribute. Specifies a superclass that the generated servlet must extend Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes. Defines a string that can be accessed with the servlet's getServletInfo() method. Defines the threading model for the generated servlet. Defines the programming language used in the JSP page. Specifies whether or not the JSP page participates in HTTP sessions Specifies whether or not EL expression within the JSP page will be ignored. Determines if scripting elements are allowed for use.
Check more detail related to all the above attributes at Page Directive.
The filename in the include directive is actually a relative URL. If you just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP. You can write XML equivalent of the above syntax as follows:
<jsp:directive.include file="relative url" />
16
Unit-7
Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions. You can write XML equivalent of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
JSP - Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available: Syntax jsp:include jsp:include jsp:useBean Purpose Includes a file at the time the page is requested Includes a file at the time the page is requested Finds or instantiates a JavaBean
17
Unit-7
Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin Defines XML elements dynamically. Defines dynamically defined XML element's attribute. Defines dynamically defined XML element's body. Use to write template text in JSP pages and documents.
Common Attributes:
There are two attributes that are common to all Action elements: the id attribute and the scope attribute.
Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. Following is the list of attributes associated with include action: Attribute page Description The relative URL of the page to be included. 18
Unit-7
Example:
Let us define following two files (a)date.jps and (b) main.jsp as follows: Following is the content of date.jsp file:
<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p>
Now let us keep all these files in root directory and try to access main.jsp. This would display result something like this:
19
Unit-7
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve bean properties. Following is the list of attributes associated with useBean action: Attribute class type beanName Description Designates the full package name of the bean. Specifies the type of the variable that will refer to the object. Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid example related to these actions.
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>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found. Following is the list of attributes associated with setProperty action:
20
Unit-7
Designates the bean whose property will be set. The Bean must have been previously defined. Indicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods. The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored. The param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither.
property
value
param
Following is the list of required attributes associated with setProperty action: Attribute name property Description The name of the Bean that has a property to be retrieved. The Bean must have been previously defined. The property attribute is the name of the Bean property to be retrieved.
Example:
Let us define a test bean which we will use in our example:
/* File: TestBean.java */ package action;
21
Unit-7
Compile above code to generated TestBean.class file and make sure that you copied TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and CLASSPATH variable should also be set to this folder: Now use the following code in main.jsp file which loads the bean and sets/gets a simple String parameter:
<html> <head> <title>Using JavaBeans in JSP</title> </head> <body> <center> <h2>Using JavaBeans in JSP</h2> <jsp:useBean id="test" class="action.TestBean" /> <jsp:setProperty name="test" property="message" value="Hello JSP..." /> <p>Got message....</p> <jsp:getProperty name="test" property="message" /> </center> </body> </html>
22
Unit-7
Following is the list of required attributes associated with forward action: Attribute page Description Should consist of a relative URL of another resource such as a static page, another JSP page, or a Java Servlet.
Example:
Let us reuse following two files (a) date.jps and (b) main.jsp as follows: Following is the content of date.jsp file:
<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p>
Now let us keep all these files in root directory and try to access main.jsp. This would display result something like as below. Here it discarded content from main page and displayed content from forwarded page only. Today's date: 12-Sep-2010 14:54:22
23
Unit-7
You can try this action using some applet if you are interested. A new element, the <fallback> element, can be used to specify an error string to be sent to the user in case the component fails.
24
Unit-7
The body fo the template cannot contain other elements; it can only contain text and EL expressions ( Note: EL expressions are explained in subsequent chapter). Note that in XML files, you cannot use expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use the gt form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section.
<jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use the <jsp:text> element as follows:
25
Unit-7
26
Unit-7
27
Unit-7
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEB-INF\web.xml file
28
Unit-7
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object. The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope. The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class. One of the important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope:
pageContext.removeAttribute("attrName", PAGE_SCOPE);
29
Unit-7
The GET method is the defualt method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limtation: only 1024 characters can be in a request string. This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable which can be handled using getQueryString() and getParameter() methods of request object.
POST method:
A generally more reliable method of passing information to a backend program is the POST method. This method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. JSP handles this type of requests using getParameter() method to read simple parameters and getInputStream() method to read binary data stream coming from the client.
getParameter(): You call request.getParameter() method to get the value of a form parameter. getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames(): Call this method if you want a complete list of all parameters in the current request. getInputStream(): Call this method to read binary data stream coming from the client.
30
Unit-7
Below is main.jsp JSP program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information:
<html> <head> <title>Using GET Method to Read Form Data</title> </head> <body> <center> <h1>Using GET Method to Read Form Data</h1> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>
Now type http://localhost:8080/main.jsp?first_name=Malige&last_name=Gangappain your browser's Location:box. This would generate following result:
31
Unit-7
Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.
32
Unit-7
Now let us keep main.jsp and hello.htm in <Tomcat-installationdirectory>/webapps/ROOT directory. When you would access http://localhost:8080/Hello.htm, below is the actual output of the above form. First Name: Last Name: Try to enter First and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it would generate similar result as mentioned in the above examples.
The result of this code is the following form Maths Physics Chemistry 33
Unit-7
Below is main.jsp JSP program to handle input given by web browser for checkbox button.
<html> <head> <title>Reading Checkbox Data</title> </head> <body> <center> <h1>Reading Checkbox Data</h1> <ul> <li><p><b>Maths Flag:</b> <%= request.getParameter("maths")%> </p></li> <li><p><b>Physics Flag:</b> <%= request.getParameter("physics")%> </p></li> <li><p><b>Chemistry Flag:</b> <%= request.getParameter("chemistry")%> </p></li> </ul> </body> </html>
34
Unit-7
35