25
JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document types. Released in 1999 by Sun Microsystems, [1] JSP is similar to PHP and ASP, but it uses the Java programming language. To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as Apache Tomcat or Jetty, is required. Overview The JSP Model 2 architecture. Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSPs are translated into servlets at runtime, therefore JSP is a Servlet; each JSP servlet is cached and re-used until the original JSP is modified. [2] JSP can be used independently or as the view component of a server-side modelviewcontroller design, normally with JavaBeans as the model and Java servlets (or a framework such as Apache Struts) as the controller. This is a type of Model 2architecture. [3] JSP allows Java code and certain pre-defined actions to be interleaved with static web markup content, such as HTML, with the resulting page being compiled and executed on the server to deliver a document. The compiled pages, as well as any dependent Java libraries, contain Java bytecode rather than machine code. Like any other Java program, they must be executed within a Java virtual machine (JVM) that interacts with the server's host operating system to provide an abstract, platform-neutral environment. JSPs are usually used to deliver HTML and XML documents, but through the use of OutputStream, they can deliver other types of data as well. [4] The Web container creates JSP implicit objects like request, response, session, application, config, page, pageContext, out and exception. JSP Engine creates these objects during translation phase. Syntax JSP pages use several delimiters for scripting functions. The most basic is <% ... %>, which encloses a JSP scriptlet. A scriptlet is a fragment of Java code that is run when the user requests the page. Other common delimiters include <%= ... %>for expressions, where the scriptlet and delimiters are replaced with the result of evaluating the expression, and directives, denoted with <%@ ... %>. [5] Java code is not required to be complete or self-contained within a single scriptlet block. It can straddle markup content, provided that the page as a whole is syntactically correct. For example, any Java if/for/while blocks opened in one scriptlet must be correctly closed in a later scriptlet for the page to successfully compile.

JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

  • Upload
    others

  • View
    14

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document types. Released in 1999 by Sun Microsystems,[1] JSP is similar to PHP and ASP, but it uses the Java programming language.

To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as Apache Tomcat or Jetty, is required.

Overview

The JSP Model 2 architecture.

Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSPs are translated into servlets at runtime, therefore JSP is a Servlet; each JSP servlet is cached and re-used until the original JSP is modified.[2]

JSP can be used independently or as the view component of a server-side model–view–controller design, normally with JavaBeans as the model and Java servlets (or a framework such as Apache Struts) as the controller. This is a type of Model 2architecture.[3]

JSP allows Java code and certain pre-defined actions to be interleaved with static web markup content, such as HTML, with the resulting page being compiled and executed on the server to deliver a document. The compiled pages, as well as any dependent Java libraries, contain Java bytecode rather than machine code. Like any other Java program, they must be executed within a Java virtual machine (JVM) that interacts with the server's host operating system to provide an abstract, platform-neutral environment.

JSPs are usually used to deliver HTML and XML documents, but through the use of OutputStream, they can deliver other types of data as well.[4]

The Web container creates JSP implicit objects like request, response, session, application, config, page, pageContext, out and exception. JSP Engine creates these objects during translation phase.

Syntax

JSP pages use several delimiters for scripting functions. The most basic is <% ... %>, which encloses a JSP scriptlet. A scriptlet is a fragment of Java code that is run when the user requests the page. Other common delimiters include <%= ... %>for expressions, where the scriptlet and delimiters are replaced with the result of evaluating the expression, and directives, denoted with <%@ ... %>.[5]

Java code is not required to be complete or self-contained within a single scriptlet block. It can straddle markup content, provided that the page as a whole is syntactically correct. For example, any Java if/for/while blocks opened in one scriptlet must be correctly closed in a later scriptlet for the page to successfully compile.

Page 2: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

Content that falls inside a split block of Java code (spanning multiple scriptlets) is subject to that code. Content inside an if block will only appear in the output when the if condition evaluates to true. Likewise, content inside a loop construct may appear multiple times in the output, depending upon how many times the loop body runs.

The following would be a valid for loop in a JSP page:

<p>Counting to three:</p>

<% for (int i=1; i<4; i++) { %>

<p>This number is <%= i %>.</p>

<% } %>

<p>OK.</p>

The output displayed in the user's web browser would be:

Counting to three:

This number is 1.

This number is 2.

This number is 3.

OK.

Expression Language[edit]

Version 2.0 of the JSP specification added support for the Expression Language (EL), used to access data and functions in Java objects. In JSP 2.1, it was folded into the Unified Expression Language, which is also used in JavaServer Faces.[6]

An example of EL Syntax:

The value of "variable" in the object "javabean" is ${javabean.variable}.

Additional tags[edit]

The JSP syntax add additional tags, called JSP actions, to invoke built-in functionality.[5] Additionally, the technology allows for the creation of custom JSP tag librariesthat act as extensions to the standard JSP syntax.[7] One such library is the JSTL, with support for common tasks such as iteration and conditionals (the equivalent of "for" and "if" statements in Java.)[8]

1. What is JSP?

JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionally User INTERFACE components for Web Applications.

2. What do you understand by JSP Actions?

JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "JSP" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:

< JSP : include / >

< JSP : forward / >

< JSP : plugin / >

< jsp : usebean / >

Page 3: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

< jsp : setProperty / >

< jsp : getProperty / >

Compiler[edit]

A JavaServer Pages compiler is a program that parses JSPs, and transforms them into executable Java Servlets. A program of this type is usually embedded into the application server and run automatically the first time a JSP is accessed, but pages may also be precompiled for better performance, or compiled as a part of the build process to test for errors.[9]

Some JSP containers support configuring how often the container checks JSP file timestamps to see whether the page has changed. Typically, this timestamp would be set to a short interval (perhaps seconds) during software development, and a longer interval (perhaps minutes, or even never) for a deployed Web application.[10]

3. What is a JSP and what is it used for?

Ans. Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE

platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files.

A JSP compiler is used in the background to generate a Servlet from the JSP page.

4. What is difference between custom JSP tags and beans?

Ans. Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then

group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags,

you need to define three separate components:

1. the tag handler class that defines the tag\'s behavior

2. the tag library descriptor file that maps the XML element names to the tag implementations

3. the JSP file that uses the tag library

When the first two components are done, you can use the tag by using taglib directive:

<%@ taglib uri="xxx.tld" prefix="..." %>

Then you are ready to use the tags you defined. Let's say the tag prefix is test:

MyJSPTag or

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare

a bean and use to set value of the bean class and use to get value of the bean class.

<%=identifier.getclassField() %>

Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible

forms. There are several differences:

Custom tags can manipulate JSP content; beans cannot.

Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags

require quite a bit more work to set up than do beans.

Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used

in a different servlet or JSP page.

Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

5. What are the two kinds of comments in JSP and what's the difference between them ?

Ans. <%-- JSP Comment --%>

<!-- HTML Comment -->

6. What is JSP technology?

Ans. he JavaServer Pages technology enables you to generate dynamic web content, such as HTML, DHTML, XHTML,

and XML files, to include in a Web application. JSP files are one way to implement server-side dynamic page content.

JSP files allow a Web server, such as Apache Tomcat, to add content dynamically to your HTML pages before they are

sent to a requesting browser.

When you deploy a JSP file to a Web server that provides a servlet engine, it is preprocessed into a servlet that runs on

the Web server. This is in contrast with client-side JavaScript™ (within SCRIPT tags), which is run in a browser. A JSP page

Page 4: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

is ideal for tasks that are better suited to execution on the server, such as accessing databases or calling Enterprise

Java™ beans. You can create and edit a JSP file in the HTML editor by adding your own text and images using HTML,

JSP tagging, or JavaScript, including Java source code inside of scriptlet tags. Typically, JSP files have the file extension

.jsp. Additionally, the JSP specification suggests that JSP fragment files should have file extension .jspf. If this convention

is not followed, the JSP validator will treat JSP fragments as regular standalone JSP files, and compilation errors might be

reported.

7. What is JSP page?

Ans. A JSP page is a text-based document that contains two types of text: static template data, which can be

expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which co

8. How many JSP scripting elements and what are they?

Ans. There are three scripting language elements:

--declarations

--scriptlets

--expressions

9. Ques 8. Why are JSP pages the preferred API for creating a web-based client program?

Ans. Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable

cleaner and more module application design because they provide a way to separate applications programming

from web page design. This means personnel involved in web page design do not need to understand Java

programming language syntax to do their jobs.

10. Ques 9. Can we use the constructor, instead of init(), to initialize servlet?

Ans. Yes , of course you can use the constructor instead of init(). There?s nothing to stop you. But you shouldn?t. The

original reason for init() was that ancient versions of Java couldn?t dynamically invoke constructors with arguments, so

there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call

your no-arg constructor. So you won?t have access to a ServletConfig or ServletContext.

11. Ques 10. How can a servlet refresh automatically if some new data has entered the database?

Ans. You can use a client-side Refresh or Server Push.

12. Creating a simple JSP Page

To create the first jsp page, write some html code as given below, and save it by .jsp extension. We have save

this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in apache tomcat to run the jsp page.

index.jsp

Let's see the simple example of JSP, here we are using the scriptlet tag to put java code in the JSP page. We will learn scriptlet tag later.

<html>

<body>

<% out.print(2*5); %>

</body>

</html>

It will print 10 on the browser.

13. How to run a simple JSP Page ?

Page 5: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

Follow the following steps to execute this JSP page:

o Start the server

o put the jsp file in a folder and deploy on the server

o visit the browser by the url http://localhost:portno/contextRoot/jspfile e.g.

http://localhost:8888/myapplication/index.jsp

14. Do I need to follow directory structure to run a simple JSP ?

No, there is no need of directory structure if you don't have class files or tld files. For example, put jsp files in a

folder directly and deploy that folder.It will be running fine.But if you are using bean class, Servlet or tld file then directory structure is required.

15. Directory structure of JSP

The directory structure of JSP page is same as servlet. We contains the jsp page outside the WEB-INF folder or in any directory.

Page 6: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

16. First JSP Example - "Java inside HTML"

Let's begin with a simple JSP example. We shall use the webapp called "hello" that we have created in our earlier

exercise. Use a programming text editor to enter the following HTML/JSP codes and save as "first.jsp" (the file type

of ".jsp" is mandatory) in your webapp (web context) home directory (i.e., "webapps\hello". <html> <head><title>First JSP</title></head> <body> <% double num = Math.random(); if (num > 0.95) { %> <h2>You'll have a luck day!</h2><p>(<%= num %>)</p> <% } else { %> <h2>Well, life goes on ... </h2><p>(<%= num %>)</p> <% } %> <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a> </body> </html>

To execute the JSP script: Simply start your Tomcat server and use a browser to issue an URL to browse the JSP page

(i.e., http://localhost:8080/hello/first.jsp).

From your browser, choose the "View Source" option to check the response message. It should be either of the

followings depending on the random number generated.

<html> <h2>You'll have a luck day!</h2> <p>(0.987)</p> <a href="first.jsp"><h3>Try Again</h3></a> </html> <html> <h2> Well, life goes on ... </h2> <p>(0.501)</p> <a href="first.jsp"><h3>Try Again</h3></a> </html>

It is important to note that the client is not able to "view" the original JSP script (otherwise, you may have security

exposure), but merely the result generated by the script.

Explanations

1. A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java inside HTML" (whereas servlet

is "HTML inside Java"). The Java statements are enclosed by <% ... %> (called JSP scriptlet) or <%= ... %> (called JSP

expression).

2. JSP Scriptlet <% ... %> is used to include Java statements.

3. JSP Expression <%= ... %> is used to evaluate a single Java expression and display its result.

4. The method request.getRequestURI() is used to retrieve the URL of the current page. This is used in the anchor

tag <a> for refreshing the page to obtain another random number.

Behind the Scene

When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet, and execute the servlet. Check

out the generated servlet for "first.jsp", and study the JSP-to-servlet conversion. Look under Tomcat's

"work\Catalina\localhost\hello" for "first_jsp.java".

The relevant part of the generated servlet is extracted as follows (with some simplifications): out.write("<html>\r\n "); double num = Math.random(); if (num > 0.95) { out.write("<h2>You will have a luck day!"); out.write("</h2><p>("); out.print( num ); out.write(")</p>\r\n");

Page 7: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

} else { out.write("\r\n "); out.write("<h2>Well, life goes on ... "); out.write("</h2><p>("); out.print( num ); out.write(")</p>\r\n "); } out.write("<a href=\""); out.print( request.getRequestURI() ); out.write("\">"); out.write("<h3>Try Again</h3></a>\r\n"); out.write("</html>\r\n");

Explanation

1. The HTML statements are written out as part of the response via out.write(), as "it is".

2. The JSP scriptlets <% ... %> are kept, as "it is", in the converted servlet as the program logic.

3. The JSP expressions <%= ... %> are placed inside a out.print(). Hence, the expression will be evaluated, and the

result of the evaluation written out as part of the response message.

Compare the JSP script and the internally generated servlet, you shall understand that servlet is "HTML inside Java",

whereas JSP is "Java inside HTML".

Subsequent accesses to the same JSP will be much faster, because they will be re-directed to the converted and

compiled servlet directly (no JSP-to-servlet conversion and servlet compilation needed again), unless the JSP has been

modified.

17. Revisit Java Servlets

A typical Java servlet (as shown below) contains three kinds of methods: init(), destroy(), and one or

more service() methods such as doGet() and doPost(). init() runs when the servlet is loaded. destroy() runs when

the servlet is unloaded. service() runs once per HTTP request. The service() methods takes two

arguments: request and response, corresponding to the HTTP request and response messages respectively.

A PrintWriter called out is created for writing out the response to the network. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ...Servlet extends HttpServlet { // Runs when the servlet is loaded onto the server. public void init() { ...... } // Runs on a thread whenever there is HTTP GET request // Take 2 arguments, corresponding to HTTP request and response public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Set the MIME type for the response message response.setContentType("text/html"); // Write to network PrintWriter out = response.getWriter(); // Your servlet's logic here out.println("<html>"); out.println( ...... ); out.println("</html>"); } // Runs as a thread whenever there is HTTP POST request public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // do the same thing as HTTP GET request doGet(request, response); } // Runs when the servlet is unloaded from the server.

Page 8: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

public void destroy() { ...... } // Other instance variables and methods }

Java servlet produces HTML codes by calling out.print() methods. You have to hardcode all the HTML tags (and

cannot use any WYSIWYG web authoring tools). Any change to the web page's presentation (such as background

color and font size) requires re-coding and re-compilation of servlet program. Servlet, in a nutshell, is "HTML inside

Java", whereas JSP is "Java inside HTML".

18. Second JSP example - Echoing HTML Request Parameters

Enter the following JSP script and save as "echo.jsp" in your webapp's root directory. <html> <head> <title>Echoing HTML Request Parameters</title> </head> <body> <h3>Choose an author:</h3> <form method="get"> <input type="checkbox" name="author" value="Tan Ah Teck">Tan <input type="checkbox" name="author" value="Mohd Ali">Ali <input type="checkbox" name="author" value="Kumar">Kumar <input type="submit" value="Query"> </form> <% String[] authors = request.getParameterValues("author"); if (authors != null) { %> <h3>You have selected author(s):</h3> <ul> <% for (int i = 0; i < authors.length; ++i) { %> <li><%= authors[i] %></li> <% } %> </ul> <a href="<%= request.getRequestURI() %>">BACK</a> <% } %> </body> </html>

Browse the JSP page created and study the generated servlet.

Explanations

1. This HTML page has a form with 3 checkboxes. The "name=value" pair of the checkboxes is "author=so_and_so". No

"action" attribute is specified, the default "action" is the current page (i.e. the query will be sent to the same page).

2. The JSP scriptlet checks if the query parameter "author" exists to decide whether to dynamically generate the

enclosed codes. "author" parameter is absent when the page is first requested. Once the client fills in the form (by

checking the boxes) and submits the form, "author" will be present in the HTTP request, and submitted to

the same page for processing (with the default <form>’s "action" attribute).

3. The request.getParameterValues() is used to retrieve all the values of the query parameter. The values are echoed

back using an unordered list.

19. JSP Scripting Elements

JSP provides the following scripting elements:

JSP Comment <%-- comments -->

JSP Expression <%= Java Expression %>

Page 9: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

JSP Scriptlet <% Java Statement(s) %>

JSP Directive <%@ page|include ... %>

To simplify the access of the HTTP request and response messages, JSP has pre-defined the following variables:

request: corresponds to the HTTP request message.

response: corresponds to the HTTP response message.

out: corresponds to the HTTP response message’s output stream.

others such as session, page, application, pageContext, which are outside the scope of this tutorial.

20. JSP comment <%-- comments --%>

JSP comments <%-- comments --%> are ignored by the JSP engine. For example,

<%-- anything but a closing tag here will be ignored -->

Note that HTML comment is <!-- comments -->. JSP expression within the HTML comment will be evaluated. For

example,

<!-- HTML comments here <%= Math.random() %> more comments -->

21. JSP Expression <%= Java Expression %>

JSP Expression can be used to insert a single Java expression directly into the response message. This expression will

be placed inside a out.print() method. Hence, the expression will be evaluated and printed out as part of the

response message. Any valid Java expression can be used. There is no semi-colon at the end of the expression. For

examples:

<p>The square root of 5 is <%= Math.sqrt(5) %></p>

<h5><%= item[10] %></h5>

<p>Current time is: <%= new java.util.Date() %></p>

The above JSP expressions will be converted to:

out.write("<p>The square root of 5 is "); out.print( Math.sqrt(5) ); out.write("</p>"); out.write("<h5>"); out.print( item[10] ); out.write("</h5>"); out.write("<p>Current time is: "); out.print( new java.util.Date() ); out.write("</p>");

You can use the pre-defined variables, such as request, in the expressions. For examples:

<p>You have choose author <%= request.getParameter("author") %></p>

<%= request.getRequestURI() %>

<%= request.getHeader("Host") %>

22. JSP Scriptlet <% Java statement(s) %>

JSP scriptlets allow you to do more complex operations than inserting a single Java expression (with the JSP

expression). JSP scriptlets let you insert an arbitrary sequence of valid Java statement(s) into the service() method of

the converted servlet. All the Java statements in a scriptlet are to be terminated with a semi-colon. For example:

<%

String author = request.getParameter("author");

if (author != null && !author.equals(""))) {

%>

<p>You have choose author <%= author %></p>

<%

}

Page 10: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

%>

In the converted servlet, the above will be inserted into the service() method as follows:

String author = request.getParameter("author");

if (author != null && !author.equals(""))) {

out.write("<p>You have choose author ");

out.print( author );

out.write("</p>");

}

Notice that the Java codes inside a scriptlet are inserted exactly as they are written, and used as the programming

logic. The HTML codes are passed to an out.write() method and written out as part of the response message.

23. JSP Directive <%@ page|include ... %>

JSP directives provide instructions to the JSP engine. The syntax of the JSP directive is:

<%@ directive_name

attribute1="value1"

attribute2="value2"

......

attributeN="valueN" %>

JSP page Directive

The "page" directive lets you import classes and customize the page properties. For examples,

<%-- import package java.sql.* -->

<%@ page import="java.sql.*" %>

<%-- Set the output MIME type -->

<%@ page contentType="image/gif" %>

<%-- Set an information message for getServletInfo() method -->

<%@ page info="Hello-world example" %>

JSP include Directive

The "include" directive lets you include another file(s) at the time when the JSP page is compiled into a servlet. You

can include any JSP files, or static HTML files. You can use include directive to include navigation bar, copyright

statement, logo, etc. on every JSP pages. The syntax is:

<%@ include file="url" %>

For example:

<%@ include file="header.html" %>

......

<%@ include file="footer.html" %>

JSP Database Example

24. Let's revisit our e-shop, which was created using Java Servlet.

Database

Database: ebookshop

Table: books

Page 11: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

+-------+----------------------------+---------------+---------+-------+

| id | title | author | price | qty |

| (INT) | (VARCHAR(50)) | (VARCHAR(50)) | (FLOAT) | (INT) |

+-------+----------------------------+---------------+---------+-------+

| 1001 | Java for dummies | Tan Ah Teck | 11.11 | 11 |

| 1002 | More Java for dummies | Tan Ah Teck | 22.22 | 22 |

| 1003 | More Java for more dummies | Mohammad Ali | 33.33 | 33 |

| 1004 | A Cup of Java | Kumar | 44.44 | 44 |

| 1005 | A Teaspoon of Java | Kevin Jones | 55.55 | 55 |

+-------+----------------------------+---------------+---------+-------+

Querying - "query.jsp"

Let's create the query page called "query.jsp". <html> <head> <title>Book Query</title> </head> <body> <h1>Another E-Bookstore</h1> <h3>Choose Author(s):</h3> <form method="get"> <input type="checkbox" name="author" value="Tan Ah Teck">Tan <input type="checkbox" name="author" value="Mohd Ali">Ali <input type="checkbox" name="author" value="Kumar">Kumar <input type="submit" value="Query"> </form> <% String[] authors = request.getParameterValues("author"); if (authors != null) { %> <%@ page import = "java.sql.*" %> <% Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check! // Connection conn = // DriverManager.getConnection("jdbc:odbc:eshopODBC"); // Access Statement stmt = conn.createStatement(); String sqlStr = "SELECT * FROM books WHERE author IN ("; sqlStr += "'" + authors[0] + "'"; // First author for (int i = 1; i < authors.length; ++i) { sqlStr += ", '" + authors[i] + "'"; // Subsequent authors need a leading commas } sqlStr += ") AND qty > 0 ORDER BY author ASC, title ASC"; // for debugging System.out.println("Query statement is " + sqlStr); ResultSet rset = stmt.executeQuery(sqlStr); %> <hr> <form method="get" action="order.jsp"> <table border=1 cellpadding=5> <tr> <th>Order</th> <th>Author</th> <th>Title</th> <th>Price</th> <th>Qty</th> </tr> <% while (rset.next()) { int id = rset.getInt("id"); %> <tr> <td><input type="checkbox" name="id" value="<%= id %>"></td> <td><%= rset.getString("author") %></td> <td><%= rset.getString("title") %></td> <td>$<%= rset.getInt("price") %></td>

Page 12: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

<td><%= rset.getInt("qty") %></td> </tr> <% } %> </table> <br> <input type="submit" value="Order"> <input type="reset" value="Clear"> </form> <a href="<%= request.getRequestURI() %>"><h3>Back</h3></a> <% rset.close(); stmt.close(); conn.close(); } %> </body> </html>

Explanations

1. This HTML page has a form with 3 checkboxes. The "name=value" pair of the checkboxes is "author=so_and_so". No

"action" attribute is specified, hence, it defaulted to current page. The processing script is contained in

the same page.

2. The method request.getParameter("author") is used to check if the query parameter "author" exists. "author" is

absent during the first reference of the page.

3. The <%@ page .. %> contains a JSP "page" directive to import the java.sql package.

4. The scriptlet performs the database query operation. The steps are:

a. Establish a database connection via a java.sql.Connection object;

b. Allocate a java.sql.Statement object under the Connection;

c. Prepare a SQL SELECT string;

d. Execute the SQL SELECT using executeQuery() method. The result of query is returned in an object

of java.sql.ResultSet;

e. Process the ResultSet row by row via ResultSet.next();

f. Free resources and close the Connection.

5. The query result is tabulated in a HTML table. Note the mixing of HTML and Java in producing the table.

Notice that JSP carries out the presentation much better and neater than servlet. The presentation can be changed

easily with JSP. The JSP pages can be created and modified using a WYSIWYG web authoring tool and reload to see

the effect on the presentation. Whereas, in the case of servlet, you have to explicitly code all the HTML tags inside the

servlet program and re-compile the program.

Ordering - "order.jsp"

Let's write the "order.jsp" for processing the order, by updating the appropriate records in the database. <html> <head> <title>Order Book</title> </head> <body> <h1>Another E-Bookstore</h1> <h2>Thank you for ordering...</h2> <% String[] ids = request.getParameterValues("id"); if (ids != null) { %> <%@ page import = "java.sql.*" %> <% Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check! // Connection conn = // DriverManager.getConnection("jdbc:odbc:eshopODBC"); // Access Statement stmt = conn.createStatement(); String sqlStr;

Page 13: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

int recordUpdated; ResultSet rset; %> <table border=1 cellpadding=3 cellspacing=0> <tr> <th>Author</th> <th>Title</th> <th>Price</th> <th>Qty In Stock</th> </tr> <% for (int i = 0; i < ids.length; ++i) { // Subtract the QtyAvailable by one sqlStr = "UPDATE books SET qty = qty - 1 WHERE id = " + ids[i]; recordUpdated = stmt.executeUpdate(sqlStr); // carry out a query to confirm sqlStr = "SELECT * FROM books WHERE id =" + ids[i]; rset = stmt.executeQuery(sqlStr); while (rset.next()) { %> <tr> <td><%= rset.getString("author") %></td> <td><%= rset.getString("title") %></td> <td>$<%= rset.getInt("price") %></td> <td><%= rset.getInt("qty") %></td> </tr> <% } rset.close(); } stmt.close(); conn.close(); } %> </table> <a href="query.jsp"><h3>BACK</h3></a> </body> </html>

25. Advantages of JSP over Servlets?

We can generate HTML response from servlets also but the process is cumbersome and error prone, when it comes to writing a complex HTML response, writing in a servlet will be a nightmare. JSP helps in this situation and provide us flexibility to write normal HTML page and include our java code only where it’s required.

JSP provides additional features such as tag libraries, expression language, custom tags that helps in faster development of user views.

JSP pages are easy to deploy, we just need to replace the modified page in the server and container takes care of the deployment. For servlets, we need to recompile and deploy whole project again.

Actually Servlet and JSPs compliment each other. We should use Servlet as server side controller and to communicate with model classes whereas JSPs should be used for presentation layer.

26. Life cycle of JSP Page

JSP life cycle is also managed by container. Usually every web container that contains servlet container also contains JSP container for managing JSP pages.

JSP pages life cycle phases are:

Translation – JSP pages doesn’t look like normal java classes, actually JSP container parse the JSP pages and

translate them to generate corresponding servlet source code. If JSP file name is home.jsp, usually its named as home_jsp.java.

Compilation – If the translation is successful, then container compiles the generated servlet source file to generate

class file.

Page 14: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

Class Loading – Once JSP is compiled as servlet class, its lifecycle is similar to servlet and it gets loaded into memory.

Instance Creation – After JSP class is loaded into memory, its object is instantiated by the container.

Initialization – The JSP class is then initialized and it transforms from a normal class to servlet. After initialization,

ServletConfig and ServletContext objects become accessible to JSP class.

Request Processing – For every client request, a new thread is spawned with ServletRequest and ServletResponse to

process and generate the HTML response.

Destroy – Last phase of JSP life cycle where it’s unloaded into memory.

27. Life cycle methods of JSP

JSP lifecycle methods are:

11. jspInit() declared in JspPage interface. This method is called only once in JSP lifecycle to initialize config params. 12. _jspService(HttpServletRequest request, HttpServletResponse response) declared in HttpJspPage interface and

response for handling client requests. 13. jspDestroy() declared in JspPage interface to unload the JSP from memory.

28. What is the difference between < jsp : include page = ... > and < % @ include file = ... >?

Both the tags include information from one JSP page in another. The differences are:

< jsp : include page = ... >

This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically.

< % @ include file = ... >

In this case the content of the included file is textually embedded in the page that has < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required including in multiple jsp files.

29. What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)?

The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file or a servlet, as long as it is in the same application context as the forwarding JSP file.

sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables.

30. Name one advantage of JSP over Servlets?

Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.

However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.

31. What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page or application. The JSP implicit objects are:

application

config

exception

out

page

pageContext

request

response and

session

Page 15: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

32. What are all the different scope values for the < jsp : useBean > tag?

< jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:

a) page

b) request

c) session and

d) application

33. What is JSP Output Comments?

JSP Output Comments are the comments that can be viewed in the HTML source file. They are comments that are enclosed within the < ! - - Your Comments Here - - >

34. What is expression in JSP?

Expression tag is used to insert Java values directly into the output.

Syntax for the Expression tag is: < %= expression % >

An expression tag contains a scripting language expression that is evaluated, converted to a String and inserted where the expression appears in the JSP file. The most commonly used language is regular Java.

35. What types of comments are available in the JSP?

There are two types of comments that are allowed in the JSP. They are hidden and output comments.

A hidden comment does not appear in the generated HTML output, while output comments appear in the generated output.

Example of hidden comment:

< % - - This is a hidden comment - - % >

Example of output comment:

< ! - - This is an output comment - - >

36. What is a JSP Scriptlet?

JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP Page. Scriptlets begins with <% tag and ends with %>

tag. Java code written inside Scriptlet executes every time the JSP is invoked.

37. What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are:

a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a

servlet instance.

b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method

can’t be overridden.

c) jspDestroy(): The container calls this when its instance is about to destroyed.

The jspInit() and jspDestroy() methods can be overridden within a JSP page.

38. What are JSP Custom tags?

JSP Custom tags are user defined JSP language elements. JSP custom tags are user-defined tags that can encapsulate common functionality. For

example you can write your own tag to access the database and performing database operations. You can also write custom tags to encapsulate

both simple and complex behaviors in an easy to use syntax. The use of custom tags greatly enhances the functionality and simplifies the

readability of JSP pages.

39. What is the role of JSP in MVC Model?

JSP is mostly used to develop the user INTERFACE , It plays are role of View in the MVC Model.

40. What do you understand by context initialization parameters?

The context-param element contains the declaration of a web application's servlet context initialization parameters.

Page 16: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

< context - param >

< param - name > name < / param - name > < param - value > value < / param - value >

< / context-param >

The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and

ServletContext.getInitParameter methods.

41. Can you extend JSP technology?

Yes. JSP technology lets the programmer to extend the jsp to make the programming easier. JSP can be extended and custom actions & tag

libraries can be developed to enhance/extend its features.

42. What do you understand by JSP translation?

JSP translation is an action that refers to the conversion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with

features for JSP functionality.

43. How can you prevent the Browser from Caching data of the Pages you visit?

By setting properties that prevent caching in your JSP Page. They are:

<% response.setHeader("pragma","no-cache");//HTTP 1.1 response.setHeader("Cache-Control","no-

cache"); response.setHeader("Cache-Control","no-store"); response.addDateHeader("Expires", -1);

response.setDateHeader("max-age", 0); //response.setIntHeader ("Expires", -1); //prevents

caching at the proxy server response.addHeader("cache-Control", "private"); %>

44. How will you handle the runtime exception in your jsp page?

The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error-processing

page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. In addition, there

should be another JSP that plays the role of the error page, which has the flag isErrorPage set to True.

45. What is JavaServer Pages Standard Tag Library (JSTL) ?

A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as

iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and

functions.

46. What is JSP container ?

A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

47. What is JSP custom action ?

A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom

actions are used to encapsulate recurring tasks in writing JSP pages.

48. What is JSP custom tag ?

A tag that references a JSP custom action.

49. What is JSP declaration ?

A JSP scripting element that declares methods, variables, or both in a JSP page.

50. What is JSP directive ?

A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

51. What is JSP document ?

A JSP page written in XML syntax and subject to the constraints of XML documents.

52. What is JSP element ?

A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action or a scripting element.

Page 17: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

53. What is JSP expression ?

A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the

implicit out object.

54. What is JSP expression language ?

A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any

standard or custom tag attribute that can accept an expression.

55. What is JSP page ?

A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is

translated into and handles requests as a servlet.

56. What is JSP scripting element ?

A JSP declaration, Scriptlet or expression whose syntax is defined by the JSP specification and whose content is written according to the

scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute

is "java".

57. What is JSP Scriptlet ?

A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification

describes what a valid Scriptlet for the case is where the language page attribute is "java".

58. What is JSP tag file ?

A source files containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

59. What is JSP tag handler ?

A Java programming language object that implements the behavior of a custom tag.

60. Explain include Directive and include Action of JSP

Ans: This is a very popular interview question on JSP, which has been asked from long time and still asked in various interview. This question is good to test some fundamental concept like translation of JSP and difference between translation time and run time kind of concept.

Syntax for include Directive is <%@ include file="fileName" %> which means we are including some file to our JSP Page when we use include directive contents of included file will be added to calling JSP page at translation time means when the calling JSP is converted to servlet ,all the contents are added to that page .one important thing is that any JSP page is compiled if we make any changes to that particular page but if we have changed the included file or JSP page the main calling JSP page will not execute again so the output will not be according to our expectation, this one is the main disadvantage of using the include directive that why it is mostly use to add static resources, like Header and footer .

Syntax for include action is <jsp:include page=”relativeURL” /> it’s a runtime procedure means the result of the JSP page which is mentioned in relative URL is appended to calling JSP at runtime on their response object at the location where we have used this tag

So any changes made to included page is being effected every time, this is the main advantage of this action but only relative URL we can use here ,because request and response object is passed between calling JSP and included JSP.

61. Difference Between include Directive and include Action of JSP

The JSP interview question is a continuation of earlier question I just made it a separate one to write answer in clear tabular format.

Include Directive Include Action

include directive is processed at the translation time

Include action is processed at the run time.

include directive can use relative or absolute path

Include action always use relative path

Include directive can only include contents of resource it will not process the dynamic resource

Include action process the dynamic resource and result will be added to calling JSP

Page 18: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

We cannot pass any other parameter Here we can pass other parameter also using JSP:param

We cannot pass any request or response object to calling jsp to included file or JSP or vice versa

In this case it’s possible.

62. Is it possible for one JSP to extend another java class if yes how?

Ans: Yes it is possible we can extends another JSP using this <%@ include page extends="classname" %> it’s a perfectly

correct because when JSP is converted to servlet its implements javax.servlet.jsp.HttpJspPage INTERFACE , so for jsp

page it’s possible to extend another java class . This question can be tricky if you don’t know some basic fact , though it’s not

advisable to write java code in jsp instead it’s better to use expression language and tag library.

63. What is < jsp:usebean >tag why it is used.

Ans: This was very popular JSP interview question during early 2000, it has lost some of its shine but still asked now and then on interviews.

JSP Syntax

<jsp:useBean

id="beanInstName"

scope="page | request | session | application"

class="package.class" type="package.class"

</jsp:useBean>

This tag is used to create an instance of java bean first of all it tries to find out the bean if bean instance already exist assign stores a reference to it in the variable. If we specified type, gives the Bean that type.otherwise instantiates it from the class we specify, storing a reference to it in the new variable.so jsp:usebean is simple way to create a java bean.

Example:

<jsp:useBean id="stock" scope="request" class="market.Stock" />

<jsp:setProperty name="bid" property="price" value="0.0" />

a <jsp:useBean> element contains a <jsp:setProperty> element that sets property values in the Bean, we have <jsp:getProperty>element also to get the value from the bean.

Explanation of Attribute

id="beanInstanceName"

A variable that identifies the Bean in the scope we specify. If the Bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.

scope="page | request | session | application"

The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:

page – we can use the Bean within the JSP page with the <jsp:useBean> element

request – we can use the Bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another file.

session – we can use the Bean from any JSP page in the same session as the JSP page that created the Bean. The Bean

exists across the entire session, and any page that participates in the session can use it..

application – we can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean.

class="package.class"

Instantiates a Bean from a class, using the new keyword and the class CONSTRUCTOR. The class must not be abstract and

must have a public, no-argument CONSTRUCTOR.

type="package.class"

If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated.

Page 19: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

64. How can one Jsp Communicate with Java file.

Ans: we have import tag <%@ page import="market.Stock.*” %> like this we can import all the java file to our jsp and use them as a regular class another way is servlet can send the instance of the java class to our jsp and we can retrieve that object from the request obj and use it in our page.

65. what is the implicit Object

Ans: This is a fact based interview question what it checks is how much coding you do in JSP if you are doing it frequently you definitely know them. Implicit object are the object that are created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated. They are by default available in JSP page.

They are: request, response, pageContext, session and application, out, config, page and exception.

66. In JSP page how can we handle runtime exception?

Ans: This is another popular JSP interview question, which has asked to check how candidate used to handle Error and Exception in JSP. We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error-processing page.

Example: <%@ page errorPage="error.jsp" %>

It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within

error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage="true" %>

67. Why is _jspService() method starting with a '_' while other life cycle methods do not?

Ans: main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever content we write in our jsp page will go inside the _jspService() method by the container if again will try to override this method JSP compiler will give error but we can override other two life cycle method as we have implementing this two in jsp so making this difference container use _ in jspService() method and shows that we can’t override this method.

68. How can you pass information form one jsp to included jsp:

Ans: This JSP interview question is little tricky and fact based. Using < Jsp: param> tag we can pass parameter from main jsp to included jsp page

Example:

<jsp:include page="newbid.jsp" flush="true">

<jsp:param name="price" value="123.7"/>

<jsp:param name="quantity" value="4"/>

69. what is the need of tag library?

Ans tag library is a collection of custom tags. Custom actions helps recurring tasks will be handled more easily they can be reused across more than one application and increase productivity. JSP tag libraries are used by Web application designers who can focus on presentation issues rather than being concerned with how to access databases and other enterprise services. Some of the popular tag libraries are Apache display tag library and String tag library.

2.

70. Simple JSP Example with Eclipse and Tomcat

We can use Eclipse IDE for building dynamic web project with JSPs and use Tomcat to run it. Please read Java Web Applications tutorial to learn how can we easily create JSPs in Eclipse and run it in tomcat.

A simple JSP example page example is:

home.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>First JSP</title>

Page 20: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

</head> <%@ page import="java.util.Date" %> <body> <h3>Hi Pankaj</h3><br> <strong>Current Time is</strong>: <%=new Date() %> </body>

</html>

If you have a simple JSP that uses only JRE classes, we are not required to put it as WAR file. Just create a directory in the tomcat webapps folder and place your JSP file in the newly created directory. For example, if your JSP is

located at apache-tomcat/webapps/test/home.jsp, then you can access it in browser with

URL http://localhost:8080/test/home.jsp. If your host and port is different, then you need to make changes in

URL accordingly.

71. JSP Files location in Web Application WAR File

We can place JSP files at any location in the WAR file, however if we put it inside the WEB-INF directory, we wont be able to access it directly from client.

We can configure JSP just like servlets in web.xml, for example if I have a JSP example page like below inside WEB-INF directory:

test.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Test JSP</title> </head> <body> Test JSP Page inside WEB-INF folder.<br> Init Param "test" value =<%=config.getInitParameter("test") %><br> HashCode of this object=<%=this.hashCode() %> </body> </html>

And I configure it in web.xml configuration as:

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>FirstJSP</display-name> <servlet> <servlet-name>Test</servlet-name> <jsp-file>/WEB-INF/test.jsp</jsp-file> <init-param> <param-name>test</param-name> <param-value>Test Value</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Test</servlet-name> <url-pattern>/Test.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>Test1</servlet-name> <jsp-file>/WEB-INF/test.jsp</jsp-file> </servlet>

Page 21: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

<servlet-mapping> <servlet-name>Test1</servlet-name> <url-pattern>/Test1.do</url-pattern> </servlet-mapping> </web-app>

Then I can access it with both the URLs http://localhost:8080/FirstJSP/Test.do and http://localhost:8080/FirstJSP/Test1.do

Notice that container will create two instances in this case and both will have their own servlet config objects, you can confirm this by visiting these URLs in browser.

For Test.do URI, you will get response like below.

Test JSP Page inside WEB-INF folder.

Init Param "test" value =Test Value

HashCode of this object=1839060256

For Test1.do URI, you will get response like below.

Test JSP Page inside WEB-INF folder.

Init Param "test" value =null

HashCode of this object=38139054

Notice the init param value in second case is null because it’s not defined for the second servlet, also notice the hashcode is different. If you will make further requests, the hashcode value will not change because the requests are processed by spawning a new thread by the container.

Did you noticed the use of config variable in above JSP example but there is no variable declared, it’s because its

one of the 9 implicit objects available in JSP page, read more about them at JSP Implicit Objects.

JSP API Interfaces and Classes

All the core JSP interfaces and classes are defined in javax.servlet.jsp package. Expression Language API

interfaces are classes are part of javax.servlet.jsp.el package. JSP Tag Libraries interfaces and classes are

defined in javax.servlet.jsp.tagext package.

Here we will look into interfaces and classes of Core JSP API.

JspPage Interface

JspPage interface extends Servlet interface and declares jspInit() and jspDestroy() life cycle methods of the JSP pages.

HttpJspPage Interface

HttpJspPage interface describes the interaction that a JSP Page Implementation Class must satisfy when using the HTTP protocol. This interface declares the service method of JSP page for HTTP protocol as public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException.

JspWriter abstract Class

Similar to PrintWriter in servlets with additional facility of buffering support. This is one of the implicit variables in a JSP page with name “out”. This class extends java.io.Writer and container provide their own implementation for this abstract class and use it while translating JSP page to Servlet. We can get it’s object using PageContext.getOut() method. Apache Tomcat concrete class for JspWriter

is org.apache.jasper.runtime.JspWriterImpl.

Page 22: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

JspContext abstract Class

JspContext serves as the base class for the PageContext class and abstracts all information that is not specific to servlets. The JspContext provides mechanism to obtain the JspWriter for output, mechanism to work with attributes and API to manage the various scoped namespaces.

PageContext abstract Class

PageContext extends JspContext to provide useful context information when JSP is used for web applications. A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically.

JspFactory abstract Class

The JspFactory is an abstract class that defines a number of factory methods available to a JSP page at runtime for the purposes of creating instances of various interfaces and classes used to support the JSP implementation.

JspEngineInfo abstract Class

The JspEngineInfo is an abstract class that provides information on the current JSP engine.

ErrorData final Class

Contains information about an error, for error pages.

JspException Class

A generic exception known to the JSP container, similar to ServletException.If JSP pages throw JspException then errorpage mechanism is used to present error information to user.

JspTagException Class

Exception to be used by a Tag Handler to indicate some unrecoverable error.

SkipPageException Class

Exception to indicate the calling page must cease evaluation. Thrown by a simple tag handler to indicate that the remainder of the page must not be evaluated. This exception should not be thrown manually in a JSP page.

JSP Comments

Since JSP is built on top of HTML, we can write comments in JSP file like html comments as

<-- This is HTML Comment -->

These comments are sent to the client and we can look it with view source option of browsers.

We can put comments in JSP files as:

<%-- This is JSP Comment--%>

This comment is suitable for developers to provide code level comments because these are not sent in the client response.

JSP Scriptlets

Scriptlet tags are the easiest way to put java code in a JSP page. A scriptlet tag starts with <% and ends with %>.

Any code written inside the scriptlet tags go into the _jspService() method.

For example:

<%

Date d = new Date();

System.out.println("Current Date="+d);

%>

Page 23: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

JSP Expression

Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this

through JSP Expressions. JSP Expression starts with <%= and ends with %>.

<% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>

Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.

JSP Directives

JSP Directives are used to give special instructions to the container while JSP page is getting

translated to servlet source code. JSP directives starts with <%@ and ends with %>

For example, in above JSP Example, I am using page directive to to instruct container JSP translator

to import the Date class.

JSP Declaration

JSP Declarations are used to declare member methods and variables of servlet class. JSP

Declarations starts with <%! and ends with %>.

For example we can create an int variable in JSP at class level as <%! public static int count=0; %>

JSP transformed Servlet Source Code and Class File location in Tomcat

Once JSP files are translated to Servlet source code, the source code (.java) and compiled classes

both are place in Tomcat/work/Catalina/localhost/FirstJSP/org/apache/jsp directory. If the

JSP files are inside other directories of application, the directory structure is maintained.

For JSPs inside WEB-INF directory, its source and class files are

inside Tomcat/work/Catalina/localhost/FirstJSP/org/apache/jsp/WEB_002dINF directory.

Here is the source code generated for above test.jsp page.

test_jsp.java

/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.32 * Generated at: 2013-08-21 03:40:59 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() {

Page 24: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=US-ASCII"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"); out.write("<html>\n"); out.write("<head>\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=US-ASCII\">\n"); out.write("<title>Test JSP</title>\n"); out.write("</head>\n"); out.write("<body>\n"); out.write("Test JSP Page inside WEB-INF folder.<br>\n"); out.write("Init Param \"test\" value ="); out.print(config.getInitParameter("test") ); out.write("<br>\n"); out.write("HashCode of this object="); out.print(this.hashCode() ); out.write("\n"); out.write("</body>\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); }

Page 25: JavaServer Pages (JSP) - Gregg Roeten...JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pagesbased on HTML, XML, or other document

} }

Notice following points in above servlet code;

The package of class starts with org.apache.jsp and if JSPs are inside other folders, it includes directory hierarchy too. Usually we dont care about it.

The generates servlet class is final and can’t be extended.

It extends org.apache.jasper.runtime.HttpJspBase that is similar to HttpServlet except that it’s

internal to Tomcat JSP Translator implementation. HttpJspBase extends HttpServlet and implements HttpJspPage interface.

Notice the local variables at the start of _jspService() method implementation, they are automatically added by JSP translator and available for use in service methods, i.e in scriptlets.

As a java programmer, sometimes it helps to look into the generated source for debugging purposes.

JSP init parameters

We can define init parameters for the JSP page as shown in above example and we can retrieve them

in JSP using config implicit object, we will look into implicit objects in JSP in more detail in future

posts.

Overriding JSP init() method

We can override JSP init method for creating resources to be used by JSP service() method using JSP Declaration tags, we can override jspInit() and jspDestroy() or any other methods also. However we should never override _jspService() method because anything we write in JSP goes into service method.

Attributes in a JSP

Apart from standard servlet attributes with request, session and context scope, in JSP we have another scope for attributes, i.e Page Scope that we can get from pageContext object. We will look it’s importance in custom tags tutorial. For normal JSP programming, we don’t need to worry about page scope.

Thats all for JSP example tutorial for beginners. I hope it helps you in understanding the basic concepts of JSPs and help you in getting started. We will look into other JSP features in future posts.