AJP U3 Notes
AJP U3 Notes
AJP U3 Notes
Features of JSP
hello.JSP :
JSP simply puts Java inside HTML pages. You can take any existing HTML
page and change its extension to “.jsp” instead of “.html”. In fact, this is the
perfect exercise for your first JSP.
Take the HTML file you used in the previous exercise. change its extension
from “.html” to “jsp”. Now load the new file, with the “.jsp” extension, in your
browser.
You will see the same output, but it will take longer! But only the first time. If
you reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a
Java file, compiled, and loaded. This compilation only happens once, so after
the first load, the file doesn’t take long to load anymore. (But every time you
change the JSP file, it will be re-compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension!
We now proceed to see what makes JSP so useful.
As we saw in the previous section, any HTML file can be turned into a JSP file
by changing its extension to .jsp . Of course , what makes JSP useful is the
ability to embed Java. Put the following text in a file. jsp extension (let us call it
hello.jsp) , place it in your JSP directory, and view it in a browser.
<HTML>
<BODY>
</BODY>
</HTML>
Notice that each time you reload the page in the browser, it comes up with the
current time. The character sequence.
<%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dynamic HTML pages
that change in response to user actions or vary from user to user.
We will learn about the various elements available in JSP with suitable
examples. In JSP elements can be divided into 4 different types.
These are:
● Expression
● Scriplets
● Directives
● Declarations
Expression:
We can use this tag to output any data on the generated page. These data
are automatically converted to string and printed on the output stream.
Syntax:
Example:
<%="HelloWorld!" %>
Scriplets:
In this tag we can insert any amount of valid java code and these codes are
placed in the _jsp Service method by the JSP engine.
Syntax:
<%//java codes%>
NOTE : JSP Scriptlets begins with <% and ends %> . We can embed any
amount of Java code in the JSP Scriptlets. JSP Engine places these codes in
the _jspService() method.
● Request
● Response
● Session
● Out
Directives:
A JSP “directive” starts with <%@ characters. In the directives, we can import
packages , and define error-handling pages or the session information of the
JSP page.
Syntax:
● page
● include
● taglib
Declarations :
This tag is used for defining the functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
NOTE : JSP Declaratives begins with <%! and ends %> with We can embed
any amount of java code in the JSP Declaratives. Variables and functions
defined in the declaratives are class-level and can be used anywhere on the
JSP page.
Example :
<%@page import="java.util.*"%>
<HTML>
<BODY>
<%!
}
%>
</BODY>
</HTML
<HTML>
<HEAD>
</HEAD>
<BODY>
<%out.println("Hello there!");%>
</BODY>
</HTML>
Step-1: Save the JSP file using “.jsp” extension (ex- “hello.jsp”)
Step-2: Start the server
Step-4: To execute the JSP script, simply start tomcat server and use a
browser to browse an URL of the JSP page i.e.
SP Architecture
JSP architecture gives a high-level view of the working of JSP. JSP
architecture is a 3 tier architecture. It has a Client, Web Server, and Database.
The client is the web browser or application on the user side. Web Server
uses a JSP Engine i.e; a container that processes JSP. For example, Apache
Tomcat has a built-in JSP Engine. JSP Engine intercepts the request for JSP
and provides the runtime environment for the understanding and processing
of JSP files. It reads, parses, build Java Servlet, Compiles and Executes Java
code, and returns the HTML page to the client. The webserver has access to
the Database. The following diagram shows the architecture of JSP.
Now let us discuss JSP which stands for Java Server Pages. It is a
server-side technology. It is used for creating web applications. It is used to
create dynamic web content. In this JSP tags are used to insert JAVA code
into HTML pages. It is an advanced version of Servlet Technology. It is a
Web-based technology that helps us to create dynamic and
platform-independent web pages. In this, Java code can be inserted in HTML/
XML pages or both. JSP is first converted into a servlet by JSP container
before processing the client’s request. JSP Processing is illustrated and
discussed in sequential steps prior to which a pictorial media is provided as a
handful pick to understand the JSP processing better which is as follows:
Step 1: The client navigates to a file ending with the .jsp extension and the
browser initiates an HTTP request to the webserver. For example, the user
enters the login details and submits the button. The browser requests a
status.jsp page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the
file. Otherwise, the request is forwarded to the JSP Engine. This is done by
recognizing the URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to
Servlet(Java code). This is done by converting all the template text into
println() statements and JSP elements to Java code. This process is called
translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is
forwarded to the Servlet engine. This process is called compilation or
request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the
Web Server. The output is an HTML file. The Servlet engine passes the output
as an HTTP response to the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.
SP Implicit Objects
There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter. In case of servlet you need to write:
1. PrintWriter out=response.getWriter();
index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
Output
It can also be used to set, get and remove attributes from the jsp request scope.
Let's see the simple example of request implicit object where we are printing the name
of the user with welcome message.
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>
Output
Let's see the example of response implicit object where we are redirecting the response
to the Google.
Example of response implicit object
index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. response.sendRedirect("http://www.google.com");
3. %>
1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. out.print("Welcome "+request.getParameter("uname"));
3.
4. String driver=config.getInitParameter("dname");
5. out.print("driver name is="+driver);
6. %>
The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.
This object can be used to get initialization parameter from configuaration file
(web.xml). It can also be used to get, set or remove attribute from the application scope.
1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2.
3. out.print("Welcome "+request.getParameter("uname"));
4.
5. String driver=application.getInitParameter("dname");
6. out.print("driver name is="+driver);
7.
8. %>
Output
index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
Output
object can be used to set,get or remove attribute from one of the following scopes:
○ page
○ request
○ session
○ application
In JSP, page scope is the default scope.
index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String
name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
Output
8) page implicit object:
In JSP, page is an implicit object of type Object class.This object is assigned to the
Object page=this;
Since, it is of type Object it is less used because you can use this object directly in
jsp.For example:
can be used to print the exception. But it can only be used in error pages.It is better to
error.jsp
JSP directives
The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
○ page directive
○ include directive
○ taglib directive
Syntax of JSP Directive
○ import
○ contentType
○ extends
○ info
○ buffer
○ language
○ isELIgnored
○ isThreadSafe
○ autoFlush
○ session
○ pageEncoding
○ errorPage
○ isErrorPage
1)import
The import attribute is used to import class,interface or all the members of a
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type
of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
3)extends
The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.
The web container will create a method getServletInfo() in the resulting servlet.For
example:
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the
JSP page.The default size of the buffer is 8Kb.
6)language
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see
8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP
page, you can use isThreadSafe attribute of page directive.The value of isThreadSafe
value is true.If you make it false, the web container will serialize the multiple requests,
i.e. it will wait until the JSP finishes responding to a request before passing another
The web container in such a case, will generate the servlet as:
9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page
Example of isErrorPage attribute
1. //myerrorpage.jsp
2. <html>
3. <body>
4.
5. <%@ page isErrorPage="true" %>
6.
7. Sorry an exception occured!<br/>
8. The exception is: <%= exception %>
9.
10. </body>
11. </html>
Code Reusability
1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>
10.
1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>
10.
The action tags are used to control the flow between pages and to use Java Bean. The
Jsp action tags are given below.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:plugin.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean
development. So we will see these tags in bean developement.
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" />
6. </body>
7. </html>
printdate.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" >
6. <jsp:param name="name" value="javatpoint.com" />
7. </jsp:forward>
8.
9. </body>
10. </html>
printdate.jsp
1. <html>
2. <body>
3.
4. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
5. <%= request.getParameter("name") %>
6.
7. </body>
8. </html>
9.
Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
JSTL Tags
There JSTL mainly provides five types of tags:
Tag Description
Name
Core tags The JSTL core tag provide variable support, URL management, flow
Formattin The Formatting tags provide support for message formatting, number
g tags and date formatting, etc. The URL for the Formatting tags is
XML tags The XML tags provide flow control, transformation, etc. The URL for the
SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags is
Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and
separates the business logic from the JSP page.
The same business logic can be used many times by the use of custom tag.
1. Eliminates the need of scriptlet tag The custom tags eliminates the need of
scriptlet tag which is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the
business logic from the JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same business
logic again and again.
There are two ways to use the custom tag. They are given below:
The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom
tag API. The JspTag is the root interface in the Custom Tag hierarchy.
JspTag interface
The JspTag is the root interface for all the interfaces and classes used in custom tag. It
is a marker interface.
Tag interface
The Tag interface is the sub interface of JspTag interface. It provides methods to
perform action at the start and end of the tag.
There are four fields defined in the Tag interface. They are:
Field Name Description
EVAL_BODY_INCLUDE
public static int EVAL_PAGE it evaluates the JSP page content after the
custom tag.
public static int SKIP_BODY it skips the body content of the tag.
public static int SKIP_PAGE it skips the JSP page content after the custom
tag.
setPageContext(PageContext
pc)
IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an
additional method to reevaluate the body.
TagSupport class
The TagSupport class implements the IterationTag interface. It acts as the base class
for new Tag Handlers. It provides some additional methods also.
1. Create the Tag handler class and perform action at the start or at the end of the
tag.
2. Create the Tag Library Descriptor (TLD) file and define tags
3. Create the JSP file that uses the Custom tag defined in the TLD file
To create the Tag Handler, we are inheriting the TagSupport class and overriding its
method doStartTag().To write data for the jsp, we need to use the JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter
class. TagSupport class provides instance of pageContext bydefault.
File: MyTagHandler.java
1. package com.javatpoint.sonoo;
2. import java.util.Calendar;
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6. public class MyTagHandler extends TagSupport{
7.
8. public int doStartTag() throws JspException {
9. JspWriter out=pageContext.getOut();//returns the instance of JspWriter
10. try{
11. out.print(Calendar.getInstance().getTime());//printing date and time using
JspWriter
12. }catch(Exception e){System.out.println(e);}
13. return SKIP_BODY;//will not evaluate the body content of the tag
14. }
15. }
Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It
must be contained inside the WEB-INF directory.
File: mytags.tld
Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it
is recommended to use the uri name instead of full path of tld file. We will learn about
uri later.
It uses taglib directive to use the tags defined in the tld file.
File: index.jsp
Output
Attributes in JSP Custom Tag
Attributes in JSP Custom Tag
Example to use attribute in JSP Custom Tag
There can be defined too many attributes for any custom tag. To define the attribute,
you need to perform two tasks:
○ Define the property in the TagHandler class with the attribute name and define
the setter method
○ define the attribute element inside the tag element in the TLD file
1. <m:cube number="4"></m:cube>
Here m is the prefix, cube is the tag name and number is the attribute.
Simple example of attribute in JSP Custom Tag
In this example, we are going to use the cube tag which return the cube of any given
number. Here, we are defining the number attribute for the cube tag. We are using the
three file here:
○ index.jsp
○ CubeNumber.java
○ mytags.tld
index.jsp
CubeNumber.java
1. package com.javatpoint.taghandler;
2. import javax.servlet.jsp.JspException;
3. import javax.servlet.jsp.JspWriter;
4. import javax.servlet.jsp.tagext.TagSupport;
5.
6. public class CubeNumber extends TagSupport{
7. private int number;
8.
9. public void setNumber(int number) {
10. this.number = number;
11. }
12.
13. public int doStartTag() throws JspException {
14. JspWriter out=pageContext.getOut();
15. try{
16. out.print(number*number*number);
17. }catch(Exception e){e.printStackTrace();}
18.
19. return SKIP_BODY;
20. }
21. }
mytags.tld
1. Cube of 4 is: 64
○ index.jsp
○ web.xml
○ mytags.tld
○ PrintDate.java
index.jsp
web.xml
mytags.tld