Introduction To JSP - Updated
Introduction To JSP - Updated
Advantage of JSP
}
}
This is just to explain, what happens internally. As a JSP developer, you do not have to worry
about how a JSP page is converted to a Servlet, as it is done automatically by the web
container.
Web server accepts the requested .jsp file and passes the JSP
file to the JSP Servlet Engine for further processing.
Just to experiment, try removing the <% %> scriplet tag from the above code and run it as JSP.
You will see that everything is printed as it is on the browser, because without the scriplet tag,
everything is considered plain HTML code.
We have been using the above example since last few lessons and in this scriptlet tags are used.
Everything written inside the scriptlet tag is compiled as java code. Like in the above example,
we initialize count variable of type int with a value of 0. And then we print it while
using ++ operator to perform addition on it.
JSP makes it so easy to perform calculations, database interactions etc directly from inside the
HTML code. Just write your java code inside the scriptlet tags.
In the above HTML file, we have created a form, with an input text field for user to enter
his/her name, and a Submit button to submit the form. On submission an HTTP Post request
( method="POST" ) is made to the welcome.jsp file ( action="welcome.jsp" ), with the form values.
<body>
Hello, <% out.println(user); %>
</body>
</html>
As we know that a JSP code is translated to Servlet code, in which _jspService method is
executed which has HttpServletRequest and HttpServletResponse as argument. So in
the welcome.jsp file, request is the HTTP Request and it has all the parameters sent from the
form in index.html page, which we can be easily get using getParameter() with name of
parameter as argument, to get its value.
The above piece of code will go inside the <body> tag of the JSP file and will work when you
initialize n with some value.
Also, observer closely we have only included the java code inside the scriptlet tag, and all the
HTML part is outside of it. Similarly we can do plenty of stuff.
Here is one more very simple example :
<%
if ( hello ) {
%>
<p>Hello, world</p>
<%
} else {
%>
<p>Goodbye, world</p>
<%
}
%>
Above code is using if-else condition to evaluate what to show, based on the value of
a booleanvariable named hello.
You can even ask user to enter the value of hello, using HTML Form and evaluate your JSP code
based on that.
In the above code, we have used the declaration tag to declare variable count. The above JSP
page becomes this Servlet :
public class hello_jsp extends HttpServlet
{
int count=0;
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
In the above servlet, we can see that variable count is declared outside the _jspservice()method.
If we declare the same variable using scriptlet tag, it will come inside the service method, as
seen in the last lesson.
While, anything we add in scriptlet tag, goes inside the _jspservice() method, therefore we
cannot add any function inside the scriptlet tag, as on compilation it will try to create a
function getCount() inside the service method, and in Java, method inside a method is not
allowed.
Directive Description
<%@ page ... %> defines page dependent properties such as language, session, errorPage etc.
<%@ taglib ... %> declares tag library used in the page
We'll discuss about include and taglib directive later. You can place page directive anywhere in
the JSP file, but it is good practice to make it as the first statement of the JSP page.The Page
directive defines a number of page dependent properties which communicates with the Web
Container at the time of translation. Basic syntax of using the page directive is <%@ page
attribute="value" %> where attributes can be one of the following :
import attribute
language attribute
extends attribute
session attribute
isThreadSafe attribute
isErrorPage attribute
errorPage attribute
contentType attribute
autoFlush attribute
•The import attribute defines the set of classes and packages that must be imported in servlet
class definition.
•Examples:
•Examples:
•The default language is Java and for this reason, there is no need to write this attribute.
•In future, if the designers would like to give support for other language, then language
attribute might come into usage.
•As on today, no other language is supported by JSP.
•The extends attribute specifies a parent class that will be inherited by the generated servlet.
•Examples:
•It specifies the URL path of another page to which a request is to be dispatched to handle run
time exceptions thrown by current JSP page.
•Examples: Hello.jsp
•Example:
When a client requests a JSP file, the container loads the JSP file, translates it to a Servlet,
compiled and then executed. For multiple clients’ requests also, the container creates multiple
objects of the same Servlet and honors. For each Servlet object, a separate service() method is
created. That is, each client will have a separate service() method. For this reason, Servlets and
JSP are implicitly thread safe.
•If the Programmer would like to create only one object for the Servlet/JSP (and not multiple
objects), then declare false.
That is, multiple clients request the same JSP (or Servlet), multiple files of the same JSP are
loaded and executed. This decreases the performance. This type coding is required when the
data is very important and critical like money transfer operations in banks.
•Syntax:
By default, this attribute is set to true and means these elements (non-EL) are recognized by
the container.
When set to false, a translation-time error will be raised if the JSP uses any scriptlets,
expressions (non-EL), or declarations.
<body>
<%@ include file="header.jsp" %>
Welcome, User
</body>
</html>
<html>
<body>
<img src="header.jpg" alt="This is Header image" / >
</body>
</html>
The example above is showcasing a very standard practice. Whenever we are building a web
application, with webpages, all of which have the top navbar and bottom footer same. We
make them as separate jsp files and include them using the include directive in all the pages.
Hence whenever we have to update something in the top navbar or footer, we just have to do
it at one place. Handy, isn't it?
One more standard application of include directive is, if you create a separate jsp file, with some
commonly used functions, kind of like a util jsp file. Which can be included in the web pages
wherever you want to use those functions.
<html>
<body>
<mytag:hello/>
</body>
</html>
There are many JSP Standard Action tag which are used to perform some
specific task.
jsp:include includes the runtime response of a JSP page into the current page.
jsp:fallback Supplies alternate text if java plugin is unavailable on the client. You can
print a message using this, if the included jsp plugin is not loaded.
jsp:body Used within standard or custom tags to supply the tag body.
Common Attributes
There are two attributes that are common to all Action elements: the id attribute
and the scope attribute.
Id attribute
The id attribute uniquely identifies the Action element, and allows the action to
be referenced inside the JSP page. If the Action creates an instance of an object,
the id value can be used to reference it through the implicit object PageContext.
This action lets you insert files into the page being generated.
The syntax looks like this −
<jsp:include page = "relative URL" flush = "true" />
Unlike the include directive, which inserts the file at the time the JSP page
is translated into a servlet, this action inserts the file at the time the page is
requested.
The include action allows you to include either a static or dynamic resource
in a JSP file. The results of including static and dynamic resources are quite
different. If the resource is static, its content is inserted into the calling JSP
file. If the resource is dynamic, the request is sent to the included
resource, the included page is executed, and then the result is included in
the response from the calling JSP page.
Example
Let us define the following two files (a)date.jsp and (b) main.jsp as follows −
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>
Let us now keep all these files in the root directory and try to access main.jsp.
You will receive the following output −
•Any Java class that follows certain design conventions is a JavaBeans component.
•A Java class with the following features is called a JavaBean:
A no-argument constructor
Properties defined with accessors and mutators (getter and setter method)
Class must not define any public instance variables
The class must implement the java.io.Serializable interface
Example of a JavaBean
JavaBeans can be used in any JSP page using the <jsp:useBean> tag
<jsp:useBean id=“myBeanAttribute” class=“myPack.MyBean”
scope=“request | page | session | application”/>
Once the bean is defined in JSP, we can get it’s properties using jsp:getProperty.
We can use jsp:setProperty to set the property values of a java bean.
•TestBean.java
TestBean.jsp
Implicit objects in jsp are the objects that are created by the container
automatically making them available to the developers.
These objects are created by JSP Engine during translation phase (while
translating JSP to Servlet). They are being created inside jspService()
method so we can directly use them within Scriptlet without initializing and
declaring them.
A variable that matches one of the implicit objects is evaluated
by ImplicitObjectResolver, which returns the implicit object.
The ImplicitObjectResolver resolves the sessionScope implicit object only.
JSP provide access to some implicit object which represent some commonly
used objects for servlets that JSP page developers might need to use.
For example you can retrieve HTML form parameter data by
using request variable, which represent the HttpServletRequest object.
1 application javax.servlet.ServletContext
2 config javax.servlet.ServletCofig
3 exception java.lang.Throwable
4 out javax.servlet.jsp.JspWriter
5 page java.lang.Object
6 PageContext javax.servlet.jsp.PageContext
7 request javax.servlet.ServletRequest
9 session javax.servlet.http.HttpSession
• Out: This object allows us to access the servlet's output stream and has a
page scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It
provides the output stream that enable access to the servlet's output
stream.
• Page: This object has a page scope and is an instance of the JSP page's
servlet class that processes the current request. Page object represents the
current page that is used to call the methods defined by the translated
servlet class, The page object represents the generated servlet instance
itself, it is same as the "this" keyword used in a Java file.
• Response: This object has a page scope that allows direct access to the
HTTPServletResponse class object. The response object also defines the
interfaces that deal with creating new HTTP headers. Through this object
the JSP programmer can add new cookies or date stamps, HTTP status
codes etc.
1. Page-centric Design : Requests are made to JSPs, and the JSPs respond to
clients
2. Dispatcher Design: Requests are sent to JSPs or servlets that then forward the
requests to another JSP or servlet
3. View Helper Strategy: The View Helper pattern specifies that you use helpers
to adapt model data to the presentation layer of an application. When developing
helpers for JSP pages, you have two choices. You could use either JavaBeans or
custom tags.
3.1 JavaBeans Helper Strategy- The built-in JSP tags that enable you
to work with JavaBeans are simple and intuitive to use. JavaBeans can do more
than simply retrieve data items from the model. They can also format specific
data items, perform calculations, or generate large blocks of content.
• http://www.studytonight.com
• https://www.javatpoint.com
• https://way2java.com
• https://docs.oracle.com