0% found this document useful (0 votes)
10 views31 pages

JSP Tutorial: Basics and Advantages

Uploaded by

Sudha Kore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views31 pages

JSP Tutorial: Basics and Advantages

Uploaded by

Sudha Kore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JSP Tutorial

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of
the Servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of
JSP translator. The JSP translator is a part of the web server which is responsible for
translating the JSP page into Servlet. After that, Servlet page is compiled by the
compiler and gets converted into the class file. Moreover, all the processes that happen
in Servlet are performed on JSP later like initialization, committing response to the
browser and destroy.
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 saved this file as [Link]. Put it in a folder and paste the folder in
the web-apps directory in apache tomcat to run the JSP page.
[Link]
Let's see the simple example of JSP where we are using the scriptlet tag to put Java
code in the JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% [Link](2*5); %>
4. </body>
5. </html>
It will print 10 on the browser.
How to run a simple JSP Page?
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 [Link] for
example, [Link]

Do I need to follow the 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.
However, if you are using Bean class, Servlet or TLD file, the directory structure is
required.

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP page
outside the WEB-INF folder or in any directory.
JSP Index

JSP Tutorial
o Life cycle of JSP
o JSP API
o JSP in Eclipse
JSP scripting elements
o JSP scriptlet tag
o JSP expression tag
o JSP declaration tag
9 Implicit Objects
o JSP Out
o JSP Request
o JSP Response
o JSP Config
o JSP Application
o JSP Session
o JSP PageContext
o JSP Page
o JSP Exception
JSP Directive Elements
o JSP page directive
o JSP include directive
o JSP taglib directive
JSP Exception
Action Elements
o jsp:forward
o jsp:include
o Java Bean class
o jsp:useBean
o set & getProperty
o Displaying applet in JSP
Expression Language
MVC in JSP
JSTL
JSP Custom tags
o Example of Custom Tag
o Attributes
o Iteration
o Custom URI
JSP Pagination
o JSP Pagination Example
JSP CRUD
o JSP CRUD Example
Development in JSP
o Registration Form
o Login Form
o Uploading File
o Downloading File
Interview Questions
o JSP Interview Questions
JSP Quiz
o Jsp Basics Quiz-1
o Jsp Basics Quiz-2
o Jsp Basics Quiz-3
o Jsp Basics Quiz-4
o Jsp Basics Quiz-5
JSP Advance Quiz
o Jsp Advance Quiz-1
o Jsp Advance Quiz-2
o Jsp Advance Quiz-3
o Jsp Advance Quiz-4
JSP Misc. Quiz
o Jsp Misc. Quiz-1
o Jsp Misc. Quiz-2
o Jsp Misc. Quiz-3
The JSP API
1. The JSP API
2. [Link] package
3. The JspPage interface
4. The HttpJspPage interface
The JSP API consists of two packages:
1. [Link]
2. [Link]
[Link] package
The [Link] package has two interfaces and [Link] two interfaces are as
follows:
1. JspPage
2. HttpJspPage
The classes are as follows:
 JspWriter
 PageContext
 JspFactory
 JspEngineInfo
 JspException
 JspError

The JspPage interface


According to the JSP specification, all the generated servlet classes must implement the
JspPage interface. It extends the Servlet interface. It provides two life cycle methods.
Methods of JspPage interface
1. public void jspInit(): It is invoked only once during the life cycle of the JSP
when JSP page is requested firstly. It is used to perform initialization. It is same
as the init() method of Servlet interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP
before the JSP page is destroyed. It can be used to perform some clean up
operation.

The HttpJspPage interface


The HttpJspPage interface provides the one life cycle method of JSP. It extends the
JspPage interface.
Method of HttpJspPage interface:
1. public void _jspService(): It is invoked each time when request for the JSP
page comes to the container. It is used to process the request. The underscore _
signifies that you cannot override this method.
We will learn all other classes and interfaces later.
Creating JSP in Eclipse IDE with Tomcat server
1. Creating JSP in Eclipse IDE with Tomcat
1. Create a Dynamic web project
2. create a jsp
3. start tomcat server and deploy the project
Advertisement
 Create a Dynamic web project
 create a jsp
 start tomcat server and deploy the project

1) Create the dynamic web project


For creating a dynamic web project click on File Menu -> New -> dynamic web project -
> write your project name e.g. first -> Finish.
Backward Skip 10sPlay VideoForward Skip 10s
2) Create the JSP file in eclipse IDE
For creating a jsp file explore the project by clicking the + icon -> right click on
WebContent -> New -> jsp -> write your jsp file name e.g. index -> next -> Finish.
Now JSP file is created, let's write some code.
3) Start the server and deploy the project:
For starting the server and deploying the project in one step Right click on your project -
> Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish.

If you are using Eclipse IDE first time, you need to configure the tomcat server First.
Click for How to configure tomcat server in eclipse IDE
Now start the tomcat server and deploy project
For starting the server and deploying the project in one step Right click on your project -
> Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish.
Advertisement
Yes, Let's see JSP is successfully running now.
JSP Scriptlet tag (Scripting elements)
1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see
what are the scripting elements first.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are
three types of scripting elements:
Advertisement
Advertisement
o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
1. <% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
1. <html>
2. <body>
3. <% [Link]("welcome to jsp"); %>
4. </body>
5. </html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files [Link] and [Link]. The [Link]
file gets the username from the user and the [Link] file prints the username with
the welcome message.
File: [Link]
1. <html>
2. <body>
3. <form action="[Link]">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: [Link]
1. <html>
2. <body>
3. <%
4. String name=[Link]("uname");
5. [Link]("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
JSP expression tag
The code placed within JSP expression tag is written to the output stream of the
response. So you need not write [Link]() to write data. It is mainly used to print the
values of variable or method.
Syntax of JSP expression tag
1. <%= statement %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome message.
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of expression tag.
Example of JSP expression tag that prints current time
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.
[Link]
Advertisement
1. <html>
2. <body>
3. Current Time: <%= [Link]().getTime() %>
4. </body>
5. </html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The [Link]
file gets the username and sends the request to the [Link] file, which displays the
username.
File: [Link]
1. <html>
2. <body>
3. <form action="[Link]">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: [Link]
1. <html>
2. <body>
3. <%= "Welcome "+[Link]("uname") %>
4. </body>
5. </html>
JSP Declaration Tag
1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of
auto generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
1. <%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variab
methods. methods.

The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is pl
_jspService() method. the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value
of the declared field using the jsp expression tag.
[Link]
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the
cube of given number and calling this method from the jsp expression tag. But we can
also use jsp scriptlet tag to call the declared method.
[Link]
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>

Common questions

Powered by AI

Setting up a JSP project in Eclipse with Tomcat involves several steps. First, create a dynamic web project through "File -> New -> Dynamic Web Project", then write the project's name and complete the wizard. Create a JSP file by right-clicking on "WebContent", selecting "New -> JSP", and providing a name, such as index.jsp. To run the application, right-click the project, choose "Run As -> Run on Server", select the configured Tomcat server, and finish the deployment setup. This process will start the server and deploy the project, making it essential that the Tomcat server is properly configured within Eclipse for successful execution .

JSP scriptlet tags (<% %>) allow embedding Java code within a JSP file to be executed as part of the service method, making it suitable for control flow and complex operations. Expression tags (<%= %>), on the other hand, are used for outputting values directly to the client's response without explicit calling of out.print(). Expression tags are ideal for inserting content like variables or method returns into the HTML directly. Scriptlet tags are useful when blocks of Java code need to be executed, such as loops or conditionals, whereas expression tags simplify the printing of dynamic content such as variable values or results of methods directly .

The lifecycle of a JSP page involves translation into a Servlet, compilation, class loading, instantiation, initialization, request processing, and destruction, similar to a Servlet. The key difference is in the initialization phase where JSP uses jspInit(), _jspService(), and jspDestroy() methods for lifecycle management. The JSP page is first translated into a Servlet by a JSP translator, then compiled, loaded by the classloader, and instantiated. During initialization, jspInit() is called, and each request invokes the _jspService() method. The lifecycle concludes with jspDestroy() for cleanup, akin to the init(), service(), and destroy() methods used in Servlets .

Using scriptlet tags in JSP allows embedding Java code directly into JSP pages, providing flexibility for performing logic within the presentation layer. However, overuse or misuse of scriptlet tags can negatively affect code maintainability by cluttering pages with business logic, making them harder to read and debug. This conventional method opposes the MVC pattern, which advocates for a clear separation between logic and view. Since scriptlet tags intertwine these concerns, they may increase the complexity and error-proneness of web applications, highlighting the need for better structuring through frameworks or technologies like JSTL to enhance maintainability .

The JSP API aids JSP development by providing structured interfaces and classes that support the execution of JSP pages. It comprises two main packages: javax.servlet.jsp and javax.servlet.jsp.tagext. The javax.servlet.jsp package includes interfaces like JspPage and HttpJspPage, which define lifecycle methods (e.g., jspInit(), _jspService(), jspDestroy()) that are critical for JSP execution. Key classes include JspWriter, for output streaming, and PageContext, for sharing data across JSP components. These APIs standardize interactions between JSP elements and the web container, ensuring cohesive operations of JSP pages in a web application .

JSTL (JavaServer Pages Standard Tag Library) complements traditional JSP scripting elements by providing a comprehensive set of tags that increment streamlined access to common web tasks, such as looping, conditionals, internationalization, and formatting. Unlike direct Java scripting in JSP, which can lead to cluttered and error-prone pages, JSTL offers a clean, readable alternative by abstracting complex logic into standardized tags. This enhances productivity and code readability, making web pages easier to develop and maintain. JSTL's significance lies in its ability to unify the design and business logic aspects of JSP into a coherent, efficient templating system .

To run a simple JSP page on a local server, you must first start the server and then deploy the JSP file by placing it in a directory and accessing it via a URL in the browser, such as "http://localhost:portno/contextRoot/jspfile." Directory structure becomes critical when using components like Bean classes, Servlets, or TLD files. If these components are used, the directory structure ensures that the server can correctly locate and utilize these components during execution. For simple JSP files without these dependencies, the directory structure is not strictly necessary, and files can be placed in any accessible folder .

JSP offers several advantages over Servlets, including: 1) It's an extension to Servlets, allowing the use of implicit objects, predefined tags, expression language, and custom tags which facilitate easier development. 2) JSP allows for business logic and presentation logic to be separated, making maintenance easier compared to Servlets where these are mixed. 3) JSP does not require recompilation and redeployment if pages are modified, leading to faster development. 4) JSPs have less code due to the use of tags such as action tags, JSTL, and custom tags, in addition to expression language and implicit objects .

Implicit objects in JSP, such as request, response, out, session, application, config, pageContext, page, and exception, provide built-in access to Java objects representing various scopes and contexts within a web application. These objects simplify the development process by abstracting the underlying complexities of dealing with HTTP requests and responses, and managing session and application data. For instance, the 'request' object allows easy retrieval of client input data, while the 'response' object handles the output. The session and application objects support data persistence across requests. Implicit objects thus enhance JSP's ease of use and richness over Servlets, where such functionality would need to be explicitly coded .

Custom tags in JSP extend JSP's functionality by allowing developers to create reusable components that encapsulate complex operations, similar to functions or methods in programming. They help in maintaining clean JSP pages by decoupling the business logic from the presentation logic. Implementing custom tags requires defining a tag handler class, which manages the tag's behavior, and a tag library descriptor (TLD) file, which describes the tag's attributes and properties. The usage of custom tags, declared via taglib directive in JSP, promotes modular, maintainable, and scalable web applications by reducing code redundancy and establishing clear separation between functionalities .

You might also like