You are on page 1of 61

unit 1

1.Swing

Need for java components

https://www.studytonight.com/java/java-swing-components.php

Difference between awt and swing & components hierarchy

https://www.javatpoint.com/java-swing

Swing components

https://www.studytonight.com/java/java-swing-components.php

https://www.tutorialspoint.com/swing/swing_controls.htm

2. JDBC

Introduction JDBC and architecture

https://www.tutorialspoint.com/jdbc/jdbc-introduction.htm

Types of drivers

https://www.javatpoint.com/jdbc-driver

https://www.javatpoint.com/java-jdbc

Blob and clob

https://www.javatpoint.com/blob-full-form

https://techterms.com/definition/clobUnit II
Servlets
What are Servlets?

Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

 Performance is significantly better.


 Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.

Servlets Architecture

The following diagram shows the position of Servlets in a Web Application.


HTTP (Hyper Text Transfer Protocol)
The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol used to
establish communication between client and server.

HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is
TCP 80. It provides the standardized way for computers to communicate with each other.

The Basic Characteristics of HTTP (Hyper Text Transfer Protocol):

 It is the protocol that allows web servers and browsers to exchange data over the web.
 It is a request response protocol.
 It uses the reliable TCP connections by default on TCP port 80.
 It is stateless means each request is considered as the new request. In other words, server
doesn't recognize the user by default.

The Basic Features of HTTP (Hyper Text Transfer Protocol):

There are three fundamental features that make the HTTP a simple and powerful protocol used
for communication:

 HTTP is media independent: It specifies that any type of media content can be sent by
HTTP as long as both the server and the client can handle the data content.
 HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a
browser initiates the HTTP request and after the request is sent the client disconnects
from server and waits for the response.
 HTTP is stateless: The client and server are aware of each other during a current request
only. Afterwards, both of them forget each other. Due to the stateless nature of protocol,
neither the client nor the server can retain the information about different request across
the web pages.
The Basic Architecture of HTTP (Hyper Text Transfer Protocol):

The below diagram represents the basic architecture of web application and depicts where HTTP
stands:

HTTP is request/response protocol which is based on client/server based architecture. In this


protocol, web browser, search engines, etc. behave as HTTP clients and the Web

HTTP Methods

 GET
 POST
 PUT
 HEAD
 DELETE
 PATCH
 OPTIONS
The GET Method

GET is used to request data from a specified resource.

GET is one of the most common HTTP methods.

Note that the query string (name/value pairs) is sent in the URL of a GET request:

/test/demo_form.php?name1=value1&name2=value2

Some other notes on GET requests:

 GET requests can be cached


 GET requests remain in the browser history
 GET requests can be bookmarked
 GET requests should never be used when dealing with sensitive data
 GET requests have length restrictions
 GET requests is only used to request data (not modify)

The POST Method

POST is used to send data to a server to create/update a resource.

The data sent to the server with POST is stored in the request body of the HTTP request:

POST /test/demo_form.php HTTP/1.1


Host: w3schools.com
name1=value1&name2=value2

POST is one of the most common HTTP methods.

Some other notes on POST requests:

 POST requests are never cached


 POST requests do not remain in the browser history
 POST requests cannot be bookmarked
 POST requests have no restrictions on data length
The PUT Method

PUT is used to send data to a server to create/update a resource.

The difference between POST and PUT is that PUT requests are idempotent. That is, calling the
same PUT request multiple times will always produce the same result. In contrast, calling a
POST request repeatedly have side effects of creating the same resource multiple times.

The HEAD Method

HEAD is almost identical to GET, but without the response body.

In other words, if GET /users returns a list of users, then HEAD /users will make the same
request but will not return the list of users.

HEAD requests are useful for checking what a GET request will return before actually making a
GET request - like before downloading a large file or response body.

The DELETE Method

The DELETE method deletes the specified resource.

The OPTIONS Method

The OPTIONS method describes the communication options for the target resource.

Compare GET vs. POST

The following table compares the two HTTP methods: GET and POST.

GET POST

Data will be re-submitted (the


browser should alert the user that
BACK button/Reload Harmless
the data are about to be re-
submitted)
Bookmarked Can be bookmarked Cannot be bookmarked

Cached Can be cached Not cached

application/x-www-form-
application/x-www-form- urlencoded or multipart/form-data.
Encoding type
urlencoded Use multipart encoding for binary
data

Parameters remain in browser Parameters are not saved in


History
history browser history

Yes, when sending data, the GET


method adds the data to the URL;
Restrictions on data length and the length of a URL is limited No restrictions
(maximum URL length is 2048
characters)

No restrictions. Binary data is also


Restrictions on data type Only ASCII characters allowed
allowed

GET is less secure compared to


POST because data sent is part of
POST is a little safer than GET
the URL
because the parameters are not
Security
stored in browser history or in web
Never use GET when sending
server logs
passwords or other sensitive
information!

Data is visible to everyone in the


Visibility Data is not displayed in the URL
URL
Web Servers and Servlet Containers

A servlet is a Java-coded Web component that runs in a container. It generates HTML content. It
is pure Java, so the benefits and restrictions of regular Java classes apply. Servlets are compiled
to platform-neutral bytecode. Upon request, this bytecode file is loaded into a container. Some
containers (servlet engines) are integrated with the Web server, while others are plug-ins or
extensions to Web servers that run inside the JVM. Servlets look the same as static Web pages
(just a URL to the browser) to the client, but are really complete programs capable of complex
operations.

The servlet container is an extension of a Web server in the same way CGI, ASP, and PHP are. A
servlet functions like these, but the language is Java. The servlet doesn't talk to the client
directly. The Web server does that. In a chain of processes, the client sends a request to the Web
server, which hands it to the container, which hands it to the servlet (which sometimes hands it
off yet again to a database or a JavaBean). The response retraces the course from the servlet to
the container to the Web server to the client. Of course there are several other steps that happen
too (JSP may need to be converted to servlet, and the TCP/IP packet hops from node to node). A
snapshot of these steps is: Web server-> container-> servlet-> JavaBean-> DB.

The servlet architecture makes the container manage servlets through their lifecycle. The
container invokes a servlet upon an HTTP request, providing that servlet with request
information (stored in a request object) and the container configuration. The servlet goes about
its deed. When finished, it hands back HTML and objects that hold information about the
response. The container then forms an HTTP response and returns it to the client

All servlet containers must support HTTP/1.0 as a protocol for requests and responses. They are
not required to support HTTPS (HTTP over SSL), but may do so. Most containers implement the
HTTP/1.1 specification as well. The container provides one or more Java Virtual Machines to
support servlet execution. The servlet container instantiates objects that encapsulate client
requests and server responses. The servlet container manages the servlet life cycle from loading
and initialization, through the processing of requests and responses, to the eventual unloading
and finalization of the servlets.

The servlet interface is the central abstraction of the servlet API. All servlets implement this
interface. Usually, a servlet extends the HttpServlet class that implements the interface. In
addition, the servlet container creates the ServletContext object, through which a servlet can
log events, set and store attributes at the application level (across browsers) or session level
(across pages, but same browser), and grab file paths.
Servlet Interface
Servlet Interface provides the common methods which needs to be implemented by all the
servlets. All the servlets must implement this interface directly or indirectly. To have the
implementation of the Servlet Interface you can extend GenericServlet
Class(javax.servlet.GenericServlet) or HttpServlet Class (javax.servlet.http.HttpServlet).
Read through Running Your First Servlet Application article for the basic understanding.

Methods of Servlet Interface

1. public void init(ServletConfig config) : This method initializes the servlet and will be
called by the servlet container after instatiating the servlet. This method will be called
only once.
2. public void service(ServletRequest request,ServletResponse response) : This method
process the request and provides the response back. This method will be called for every
request from the web container.
3. public void destroy() : This method indicates the end of the servlet lifecycle. This
method will be called only once
4. public ServletConfig getServletConfig() : This method returns back the ServletConfig
object. It is used to get configuration information from web.xml file.
5. public String getServletInfo() : Returns information about servlet such as writer,
version etc.

Servlet Example Implementing Servlet Interface

ServletInterfaceExample.java

Lets see the below Servlet Example which implements the Servlet Interface

import java.io.*;
import javax.servlet.*;

public class ServletInterfaceExample implements Servlet{


ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("Initialization the Servlet");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html>");
out.print("<body>");
out.print("<h2>Welcome to Servlet Interface Example!!!</h2>");
out.print("</body>");
out.print("</html>");
}
public void destroy(){
System.out.println("End of the Servlet lifecycle");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "Servlet Example Using Servlet Interface";
}
}

web.xml

The deployment descriptor will be in XML format and called as web.xml, which sould be placed
in the WEB-INF directory of the Servlet application.

<?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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ServletsInterfaceExample</display-name>
<servlet>
<servlet-name>ServletInterfaceExample</servlet-name>
<servlet-class>com.javainterviewpoint.ServletInterfaceExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletInterfaceExample</servlet-name>
<url-pattern>/ServletInterfaceExample</url-pattern>
</servlet-mapping>
</web-app>

Output

To run our ServletInterfaceExample application hit on the below url

http://localhost:8080
/ServletTutorial
/ServletInterfaceExample
eneric Servlet

GenericServlet is an abstract class defined in the Servlet API. For implementing class we need
to implement all the methods in javax.servlet.Servlet Interface. Most of the Servlet objects do not
need initializing and destroying operations but still we need to implement all the methods in
javax.servlet.Servlet interface. To solve this problem, Servlet API provides
javax.servlet.GenericServlet which implements ServletConfig interface and provides the
implementation for the methods in this interface except the service method.

Methods of GenericServlet class

 public void init (): This method is invoked by init (ServletConfig) method of GenericServlet. It is
used to provide custom initializations without disturbing the initializations performed by
GenericServlet in the init (ServletConfig) method.
 public void init (ServletConfig) : It is used to initialize the servlet. It indicates Servlet instance in
being placed into the service.
 public abstract void service (ServletRequest request, ServletResponse response) : It is used to
process user request. It is called by servlet container to intimate servlet about client request. It
carries out single request from the client. ServletRequest object is used to collect data which is
available with client requested data. ServletResponse object is used to generate the output
content.
 public void destroy (): It indicates servlet instance is being taken out of service. It is used to
clean up any resources that servlet might have initialized.
 public ServletConfig getServletConfig (): It returns ServletConfig interface reference. It is used
to get configuration information from web.xml file.
 public ServletContext getServletContext (): It returns ServletContext object reference. It is used
to get configuration information from web.xml file. It is also used to set, get or remove attribute
from web.xml file. If information is changed then there is no need to modify the servlet. So it is
easy to maintain.
 public String getInitParameter (String name): It returns the Servlet initialization parameter of
the given name and if requested parameter is not available then it returns null.
 public Enumeration String getInitParameternames (): It returns names of all Servlet
initialization parameters defined in web.xml file.
 public String getServletInfo (): It returns information about the respective servlet. For e.g.
version, copyright.
 public String getServletName (): It returns the Servlet instance name defined in Deployment
Descriptor (web.xml).
 public void log (String msg): It writes class name of servlet and specified message to a servlet
log file.
 public void log (String msg, Throwable t): It writes explanatory message and stack trace for a
given Throwable exception to the servlet log file.

Http Servlet

HttpServlet is an abstract class defined in the Servlet API. It is abstract class with no abstract
methods. Servlet container provides support for the Http protocol. It creates HttpServletRequest
and HttpServletResponse objects if HTTP protocol is used for the sending request.
HttpServletRequest extends ServletRequest interface to provide request information for servlets.
HttpServletResponse extends ServletResponse interface which provides functionality in sending
response. HttpServlet is subtype of GenericServlet and does not override init, destroy and other
methods. However, it implements the service () method which is abstract method in
GenericServlet.

Methods of HttpServlet class

 public void service (ServletRequest request, ServletResponse response): This method is used to
process the user request. For each request the web container will issue unique request and
response to the service method.
 public void service (HttpServletRequest request, HttpServletResponse response): This method
receives requests from the service () method. It dispatches requests depending on the request
type.
 protected void doGet (HttpServletRequest request, HttpServletResponse response): By using
doGet () method we can send specific amount of data. If we use doGet () method data is shown
in address bar. We must override doGet () method depending on type of request.
 protected void doPost (HttpServletRequest request, HttpServletResponse response): We can
send large amount of data by using doPost () method. By using this method data is not viewable
in address bar. When we want to send secure data like passwords and other things doPost ()
method is used. We must override doPost () method depending on type of request.
 protected void doDelete (HttpServletRequest request, HttpServletResponse response): It is
used to delete files, web pages or documents from the server. If requests are formatted
incorrectly then it will return HTTP “Bad Request” error.
 protected void doPut (HttpServletRequest request, HttpServletResponse response): This
method is used to put files, web pages or documents in the server means for uploading files on
the server. If requests are formatted incorrectly then it will return HTTP “Bad Request” error.
 protected void doTrace (HttpServletRequest request, HttpServletResponse response): This
method is used for logging and debugging purpose. It can be used for testing the requested
message. There is no need to override this method.
 protected void doOptions (HttpServletRequest request, HttpServletResponse response): This
method handles OPTIONS request. There is no need to override this method. It determines
which HTTP method supported by server and returns correct header.
 protected long getLastModified (HttpServletRequest request, HttpServletResponse response):
It returns the time when request was last modified. This method should override GET request to
return modification time of object.
 protected void doHead (HttpServletRequest request, HttpServletResponse response): This
method request header part of the GET request without the GET response body. It receives
request from service method and handles the request. If HEAD requests are formatted
incorrectly then it will return HTTP “Bad Request” error.
Servlets - Life Cycle
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.

 The servlet is initialized by calling the init() method.


 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in detail.

The init() Method

The init method is called only once. It is called only when the servlet is created, and not called
for any user requests afterwards. So, it is used for one-time initializations, just as with the init
method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but
you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this −

public void init() throws ServletException {


// Initialization code...
}

The service() Method

The service() method is the main method to perform the actual task. The servlet container (i.e.
web server) calls the service() method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive from
the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here is
the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}

The destroy() Method

The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write cookie
lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this −

public void destroy() {


// Finalization code...
}

Architecture Diagram

The following figure depicts a typical servlet life-cycle scenario.

 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.

Servlet Config
An object of ServletConfig is created by the web container for each servlet. This object can be
used to get configuration information from web.xml file.

If the configuration information is modified from the web.xml file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from
time to time.

Advantage of ServletConfig

The core advantage of ServletConfig is that you don't need to edit the servlet file if information
is modified from the web.xml file.

Methods of ServletConfig interface

1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization
parameter names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of ServletContext.

ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the project.
This object can be used to get configuration information from web.xml file. There is only one
ServletContext object per web application.

If any information is shared to many servlet, it is better to provide it from the web.xml file using
the <context-param> element.

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available
for all the servlet. We provide this information from the web.xml file, so if the information is
changed, we don't need to modify the servlet. Thus it removes maintenance problem.

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:

1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.
Commonly used methods of ServletContext interface
There is given some commonly used methods of ServletContext interface.

1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application
scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.
5. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given name from the
servlet context.

Servlet Communication
Communication between Java servlets is called as Servlet communication. It is nothing but,
sending users request and the response object passed to a servlet to another servlet. You may ask,
what is the use of passing these objects. Well, i have an answer. As seen in the servlet examples
written till date, one common method we are using, getParameter(), used to get the user input
value in a specified field. So, when a request object is passed from one servlet to another servlet,
then you can use this method to get the input that the user has given in a HTML/JSP form.

Session Tracking Methods


Last modified on September 7th, 2014 by Joe.

Following answer is applicable irrespective of the language and platform used. Before we enter
into session tracking, following things should be understood.

What is a session?

A session is a conversation between the server and a client. A conversation consists series of
continuous request and response.
Why should a session be maintained?

When there is a series of continuous request and response from a same client to a server, the
server cannot identify from which client it is getting requests. Because HTTP is a stateless
protocol.

When there is a need to maintain the conversational state, session tracking is needed. For
example, in a shopping cart application a client keeps on adding items into his cart using
multiple requests. When every request is made, the server should identify in which client’s cart
the item is to be added. So in this scenario, there is a certain need for session tracking.

Solution is, when a client makes a request it should introduce itself by providing unique
identifier every time. There are five different methods to achieve this.

Session tracking methods:

1. User authorization
2. Hidden fields
3. URL rewriting
4. Cookies
5. Session tracking API

The first four methods are traditionally used for session tracking in all the server-side
technologies. The session tracking API method is provided by the underlying technology (java
servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is that the
user will provide username and password to login to the application. Based on that the user can
be identified and the session can be maintained.

2. Hidden Fields

<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>


Hidden fields like the above can be inserted in the webpages and information can be sent to the
server for session tracking. These fields are not visible directly to the user, but can be viewed
using view source option from the browsers. This type doesn’t need any special configuration
from the browser of server and by default available to use for session tracking. This cannot be
used for session tracking when the conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName


Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added
additional parameter will be sessionid or sometimes the userid. It will suffice to track the session.
This type of session tracking doesn’t need any special support from the browser. Disadvantage
is, implementing this type of session tracking is tedious. We need to keep track of the parameter
as a chain link until the conversation completes and also should make sure that, the parameter
doesn’t clash with other application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of
information, sent by the server to the browser. This should be saved by the browser in its space
in the client computer. Whenever the browser sends a request to that server it sends the cookie
along with it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:

Cookie cookie = new Cookie(“userID”, “7456”);


res.addCookie(cookie);

Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the
users can opt to disable cookies using their browser preferences. In such case, the browser will
not save the cookie at client computer and session tracking fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help the
developer to minimize the overhead of session tracking. This type of session tracking is provided
by the underlying technology. Lets take the java servlet example. Then, the servlet container
manages the session tracking task and the user need not do it explicitly using the java servlets.
This is the best of all methods, because all the management and errors related to session tracking
will be taken care of by the container itself.

Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java
servlets can use the session object to store and retrieve java objects across the session. Session
tracking is at the best when it is implemented using session tracking api
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:

 Translation of JSP Page


 Compilation of JSP Page
 Classloading (the classloader loads class file)
 Instantiation (Object of the Generated Servlet is created).
 Initialization ( the container invokes jspInit() method).
 Request processing ( the container invokes _jspService() method).
 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.
JSP - Implicit Objects
JSP Objects are the Java objects that the JSP Container makes available to the developers in each
page and the developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.

Object & Description


1. Request This is the HttpServletRequest object associated with the request.

2. Response This is the HttpServletResponse object associated with the


response to the client.

3. Out This is the PrintWriter object used to send output to the client.

4. Session This is the HttpSession object associated with the request.

5. Application This is the ServletContext object associated with the application


context.

6. Config This is the ServletConfig object associated with the page.

7. pageContext This encapsulates use of server-specific features like higher


performance JspWriters.

8. Page This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.

9. Exception The Exception object allows the exception data to be accessed by


designated JSP.

The request Object

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time


a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get the HTTP header information including form data,
cookies, HTTP methods etc.

We can cover a complete set of methods associated with the request object in a subsequent
chapter − JSP - Client Request.

The response Object

The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as


the server creates the request object, it also creates an object to represent the response to the
client.

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.

We will cover a complete set of methods associated with the response object in a subsequent
chapter − JSP - Server Response.

The out Object

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send
content in a response.

The initial JspWriter object is instantiated differently depending on whether the page is buffered
or not. Buffering can be easily turned off by using the buffered = 'false' attribute of the page
directive.

The JspWriter object contains most of the same methods as the java.io.PrintWriter class.
However, JspWriter has some additional methods designed to deal with buffering. Unlike the
PrintWriter object, JspWriter throws IOExceptions.

Following table lists out the important methods that we will use to write boolean char, int,
double, object, String, etc.

S.No. Method & Description

out.print(dataType dt)
1
Print a data type value
out.println(dataType dt)
2
Print a data type value then terminate the line with new line character.
3 out.flush()
Flush the stream.

The session Object

The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the


same way that session objects behave under Java Servlets.

The session object is used to track client session between client requests. We will cover the
complete usage of session object in a subsequent chapter − JSP - Session Tracking.

The application Object

The application object is direct wrapper around the ServletContext object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext object.

This object is a representation of the JSP page through its entire lifecycle. This object is created
when the JSP page is initialized and will be removed when the JSP page is removed by the
jspDestroy() method.

By adding an attribute to application, you can ensure that all JSP files that make up your web
application have access to it.

We will check the use of Application Object in JSP - Hits Counter chapter.

The config Object

The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper


around the ServletConfig object for the generated servlet.

This object allows the JSP programmer access to the Servlet or JSP engine initialization
parameters such as the paths or file locations etc.

The following config method is the only one you might ever use, and its usage is trivial −

config.getServletName();

This returns the servlet name, which is the string contained in the <servlet-name> element
defined in the WEB-INF\web.xml file.

The pageContext Object

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The


pageContext object is used to represent the entire JSP page.
This object is intended as a means to access information about the page while avoiding most of
the implementation details.

This object stores references to the request and response objects for each request. The
application, config, session, and out objects are derived by accessing attributes of this object.

The pageContext object also contains information about the directives issued to the JSP page,
including the buffering information, the errorPageURL, and page scope.

The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,


SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also
supports more than 40 methods, about half of which are inherited from the
javax.servlet.jsp.JspContext class.

One of the important methods is removeAttribute. This method accepts either one or two
arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute
from all scopes, while the following code only removes it from the page scope −

pageContext.removeAttribute("attrName", PAGE_SCOPE);

The use of pageContext can be checked in JSP - File Uploading chapter.

The page Object

This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.

The page object is really a direct synonym for the this object.

The exception Object

The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used to generate an appropriate response to the error condition.

Scope of JSP Objects


The availability of a JSP object for use from a particular place of the application is defined as the
scope of that JSP object. Every object created in a JSP page will have a scope. Object scope in
JSP is segregated into four parts and they are page, request, session and application.

 page
‘page’ scope means, the JSP object can be accessed only from within the same page
where it was created. The default scope for JSP objects created using <jsp:useBean> tag
is page. JSP implicit objects out, exception, response, pageContext, config and page have
‘page’ scope.
 request
A JSP object created using the ‘request’ scope can be accessed from any pages that
serves that request. More than one page can serve a single request. The JSP object will be
bound to the request object. Implicit object request has the ‘request’ scope.
 session
‘session’ scope means, the JSP object is accessible from pages that belong to the same
session from where it was created. The JSP object that is created using the session scope
is bound to the session object. Implicit object session has the ‘session’ scope.
 application
A JSP object created using the ‘application’ scope can be accessed from any pages across
the application. The JSP object is bound to the application object. Implicit object
application has the ‘application’ scope.

JSP Directives
What are JSP Directives?

 JSP directives are the messages to JSP container. They provide global information about an
entire JSP page.
 JSP directives are used to give special instruction to a container for translation of JSP to servlet
code.
 In JSP life cycle phase, JSP has to be converted to a servlet which is the translation phase.
 They give instructions to the container on how to handle certain aspects of JSP processing
 Directives can have many attributes by comma separated as key-value pairs.
 In JSP, directive is described in <%@ %> tags.

Syntax of Directive:

<%@ directive attribute="" %>

There are three types of directives:

1. Page directive
2. Include directive
3. Taglib directive

JSP Page directive

Syntax of Page directive:

<%@ page…%>
 It provides attributes that get applied to entire JSP page.
 It defines page dependent attributes, such as scripting language, error page, and buffering
requirements.
 It is used to provide instructions to a container that pertains to current JSP page.

Following are its list of attributes associated with page directive:

1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. autoflush
9. buffer
10. IsErrorPage
11. pageEncoding
12. errorPage
13. isELIgonored

More details about each attribute

1. language: It defines the programming language (underlying language) being used in the page.

Syntax of language:

<%@ page language="value" %>

Here value is the programming language (underlying language)

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

Explanation of code: In the above example, attribute language value is Java which is the
underlying language in this case. Hence, the code in expression tags would be compiled using
java compiler.

2. Extends: This attribute is used to extend (inherit) the class like JAVA does

Syntax of extends:

<%@ page extends="value" %>

Here the value represents class from which it has to be inherited.


Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

<%@ page extends="demotest.DemoClass" %>

Explanation of the code: In the above code JSP is extending DemoClass which is within
demotest package, and it will extend all class features.

3. Import: This attribute is most used attribute in page directive attributes.It is used to tell the
container to import other java classes, interfaces, enums, etc. while generating servlet code.It is
similar to import statements in java classes, interfaces.

Syntax of import:

<%@ page import="value" %>

Here value indicates the classes which have to be imported.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


import="java.util.Date" pageEncoding="ISO-8859-1"%>

Explanation of the code:

In the above code, we are importing Date class from java.util package (all utility classes), and it
can use all methods of the following class.

4. contentType:

 It defines the character encoding scheme i.e. it is used to set the content type and the character
set of the response
 The default type of contentType is "text/html; charset=ISO-8859-1".

Syntax of the contentType:

<%@ page contentType="value" %>

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

Explanation of the code:


In the above code, the content type is set as text/html, it sets character encoding for JSP and for
generated response page.

5. info

 It defines a string which can be accessed by getServletInfo() method.


 This attribute is used to set the servlet description.

Syntax of info:

<%@ page info="value" %>

Here, the value represents the servlet information.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


info="Guru Directive JSP" pageEncoding="ISO-8859-1"%>

Explanation of the code:

In the above code, string "Guru Directive JSP" can be retrieved by the servlet interface using
getServletInfo()

6. Session

 JSP page creates session by default.


 Sometimes we don't need a session to be created in JSP, and hence, we can set this attribute to
false in that case.The default value of the session attribute is true, and the session is created.

When it is set to false, then we can indicate the compiler to not create the session by
default.

Syntax of session:

<%@ page session="true/false"%>

Here in this case session attribute can be set to true or false

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


session="false"%>

Explanation of code:
In the above example, session attribute is set to "false" hence we are indicating that we don't
want to create any session in this JSP

7. isThreadSafe:

 It defines the threading model for the generated servlet.


 It indicates the level of thread safety implemented in the page.
 Its default value is true so simultaneous
 We can use this attribute to implement SingleThreadModel interface in generated servlet.
 If we set it to false, then it will implement SingleThreadModel and can access any shared objects
and can yield inconsistency.

Syntax of isThreadSafe:

<% @ page isThreadSafe="true/false" %>

Here true or false represents if synchronization is there then set as true and set it as false.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


isThreadSafe="true"%>

Explanation of the code:

In the above code, isThreadSafe is set to "true" hence synchronization will be done, and multiple
threads can be used.

8. AutoFlush:

This attribute specifies that the buffered output should be flushed automatically or not and
default value of that attribute is true.

If the value is set to false the buffer will not be flushed automatically and if its full, we will get
an exception.

When the buffer is none then the false is illegitimate, and there is no buffering, so it will be
flushed automatically.

Syntax of autoFlush:

<% @ page autoFlush="true/false" %>

Here true/false represents whether buffering has to be done or not

Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
autoFlush="false"%>

Explanation of the code:

In the above code, the autoflush is set to false and hence buffering won't be done and it has
manually flush the output.

9. Buffer:

 Using this attribute the output response object may be buffered.


 We can define the size of buffering to be done using this attribute and default size is 8KB.
 It directs the servlet to write the buffer before writing to the response object.

Syntax of buffer:

<%@ page buffer="value" %>

Here the value represents the size of the buffer which has to be defined. If there is no buffer, then
we can write as none, and if we don't mention any value then the default is 8KB

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


buffer="16KB"%>

Explanation of the code:

In the above code, buffer size is mentioned as 16KB wherein the buffer would be of that size

10. isErrorPage:

 It indicates that JSP Page that has an errorPage will be checked in another JSP page
 Any JSP file declared with "isErrorPage" attribute is then capable to receive exceptions from
other JSP pages which have error pages.
 Exceptions are available to these pages only.
 The default value is false.

Syntax of isErrorPage:

<%@ page isErrorPage="true/false"%>

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


isErrorPage="true"%>

Explanation of the code:


In the above code, isErrorPage is set as true. Hence, it will check any other JSPs has errorPage
(described in the next attribute) attribute set and it can handle exceptions.

11. PageEncoding:

The "pageEncoding" attribute defines the character encoding for JSP page.

The default is specified as "ISO-8859-1" if any other is not specified.

Syntax of pageEncoding:

<%@ page pageEncoding="vaue" %>

Here value specifies the charset value for JSP

Example:

<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"


isErrorPage="true"%>

Explanation of the code:

In the above code "pageEncoding" has been set to default charset ISO-8859-1

12. errorPage:

This attribute is used to set the error page for the JSP page if JSP throws an exception and then it
redirects to the exception page.

Syntax of errorPage:

<%@ page errorPage="value" %>

Here value represents the error JSP page value

Example:

<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"


errorPage="errorHandler.jsp"%>

Explanation of the code:

In the above code, to handle exceptions we have errroHandler.jsp

13. isELIgnored:

 IsELIgnored is a flag attribute where we have to decide whether to ignore EL tags or not.
 Its datatype is java enum, and the default value is false hence EL is enabled by default.

Syntax of isELIgnored:

<%@ page isELIgnored="true/false" %>

Here, true/false represents the value of EL whether it should be ignored or not.

Example:

<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"


isELIgnored="true"%>

Explanation of the code:

In the above code, isELIgnored is true and hence Expression Language (EL) is ignored here.

In the below example we are using four attributes(code line 1-2)

Example with four attributes

1. <%@ page language="java" contentType="text/html;" pageEncoding="ISO-


8859-1"
2. isELIgnored="false"%>
3. <%@page import="java.util.Date" %>
4.
5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
6. <html>
7. <head>
8. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
9. <title>Directive Guru JSP1</title>
10. </head>
11. <body>
12. <a>Date is:</a>
13. <%= new java.util.Date() %>
14. </body>
15. </html>

Explanation of the code:

Code Line 1-2: Here we have defined four attributes i.e.

 Language: It is set as Java as programming language


 contentType: set as text/html to tell the compiler that html has to be format
 pageEncoding: default charset is set in this attribute
 isELIgnored: Expression Tag is false hence it is not ignored
Code Line 3: Here we have used import attribute, and it is importing "Date class" which is from
Java util package, and we are trying to display current date in the code.

When you execute the above code, you will get the following output

Output:

 Date is: Current date using the date method of the date class

JSP Include directive

 JSP "include directive"( codeline 8 ) is used to include one file to the another file
 This included file can be HTML, JSP, text files, etc.
 It is also useful in creating templates with the user views and break the pages into
header&footer and sidebar actions.
 It includes file during translation phase

Syntax of include directive:

<%@ include….%>

Example:

Directive_jsp2.jsp (Main file)

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


2. pageEncoding="ISO-8859-1"%>
3. <%@ include file="directive_header_jsp3.jsp" %>
4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
5. <html>
6. <head>
7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
8. <title>Guru Directive JSP2</title>
9. </head>
10. <body>
11. <a>This is the main file</a>
12. </body>
13. </html>
Directive_header_jsp3.jsp (which is included in the main file)

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
7.
8. </head>
9. <body>
10. <a>Header file : </a>
11. <%int count =1; count++;
12. out.println(count);%> :
13. </body>
14. </html>

Explanation of the code:

Directive_jsp2.jsp:

Code Line 3: In this code, we use include tags where we are including the file
directive_header_jsp3.jsp into the main file(_jsp2.jsp)and gets the output of both main file and
included file.

Directive_header_jsp3.jsp:

Code Line 11-12: We have taken a variable count initialized to 1 and then incremented it. This
will give the output in the main file as shown below.

When you execute the above code you get the following output:

Output:

 The output is Header file: 2 : This is the main file


 The output is executed from the directive_jsp2.jsp file while the directive_header_jsp3.jsp
included file will be compiled first.
 After the included file is done, the main file is executed, and the output will be from the main
file "This is the main file". So you will get the output as "Header file: 2" from _jsp3.jsp and "This
is main file" from _jsp2.jsp.

JSP Taglib Directive

 JSP taglib directive is used to define the tag library with "taglib" as the prefix, which we can use
in JSP.
 More detail will be covered in JSP Custom Tags section
 JSP taglib directive is used in the JSP pages using the JSP standard tag libraries
 It uses a set of custom tags, identifies the location of the library and provides means of
identifying custom tags in JSP page.

Syntax of taglib directive:

<%@ taglib uri="uri" prefix="value"%>

Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a tag
name.

Example:

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


2. pageEncoding="ISO-8859-1"%>
3. <%@ taglib prefix="gurutag" uri="http://java.sun.com/jsp/jstl/core"
%>
4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
5. <html>
6. <head>
7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
8. <title>Guru Directive JSP</title>
9. <gurutag:hello/>
10. </head>
11. <body>
12. </body>
13. </html>

Explanation of the code:

Code Line 3: Here "taglib" is defined with attributes uri and prefix.

Code Line 9: "gurutag" is the custom tag defined and it can be used anywhere

In JSP there are three types of scripting elements:


 JSP Expressions: It is a small java code which you can include into a JSP page. The syntax is “<%=
some java code %>”
 JSP Scriptlet: The syntax for a scriptlet is “<% some java code %>”. You can add 1 to many lines
of Java code in here.
 JSP Declaration: The syntax for declaration is “<%! Variable or method declaration %>”, in here
you can declare a variable or a method for use later in the code.

Let’s take a look at these in detail.

JSP Expressions

Using the JSP Expression you can compute a small expression, always a single line, and get the
result included in the HTML which is returned to the browser. Using the code we have
previously written, let’s explore expressions.

Code

The time on the server is <%= new java.util.Date() %>

Output

The time on the server is Thursday January 21 07:21:43 GMT 2016.

Explanation

Here the “new java.util.Date()” is processed into the actual date and time shown through HTML
on the browser. Let’s explore expressions through a couple of more examples.

Examples

 In the first example we are going to see an expression for converting a string from lower case to
upper case. Here is the code:

The Expression: Converting a string to uppercase <%= new String(“Hello


World”).toUpperCase() %>

Here we are creating a “String” object with “Hello World” set as the value for object. Following
that we are calling a Java function “.toUpperCase” to convert the string from lower case to upper
case.

The HTML: Converting a string to uppercase: HELLO WORLD

 You can also make use of mathematical expressions in JSP.

The Expression: 25 multiplied to 4: <%= 25*4 %>


Using simple mathematical expressions you can always compute and get answers to your
mathematical problems embedded in your HTML.

The HTML: 25 multiplied to 4: 100

 You can also have Boolean expressions in JSP.

The Expression: Is 75 less than 69? <%= 75 <69 %>

The return type of these Boolean expressions is string which is either going to be “true” or
“false”

The HTML: Is 75 less than 69? False

JSP Scriptlets

This JSP Scripting Element allows you to put in a lot of Java code in your HTML code. This
Java code is processed top to bottom when the page is the processed by the web server. Here the
result of the code isn’t directly combined with the HTML rather you have to use “out.println()”
to show what you want to mix with HTML. The syntax is pretty much the same only you don’t
have to put in an equal sign after the opening % sign.

Let’s take a look at the code:

Code:

1. <h2> Hello World</h2>


2.
3. <%
4.
5. for(inti=0; i<= 5; i++)
6.
7. {
8.
9. out.println(“<br/> I really love counting: ” + i);
10.
11. }
12.
13. %>

Output:

I really love counting: 1


I really love counting: 2

I really love counting: 3

I really love counting: 4

I really love counting: 5

Explanation:

In this example we have set up a basic h2 heading and following that we have a “for loop” in the
scriptlet. Just to remember println means print line. In every iteration of the loop we print the “I
really love counting” and appends it with the integer value of the “i” printed through the HTML.

Just try to make sure that you don’t put in a lot of code in a scriptlet in JSP. This will make it
readable and easy to manage. If you can’t help it, try to refactor this code into different Java
classes and make use of MVC to keep it under control.

JSP Declarations

The declarations come in handy when you have a code snippet that you want executed more than
once. Using the declaration, you can declare the method in the beginning of the code and then
call the same method whenever you need in the same page. The syntax is simple:

1. <%!
2.
3. //declare a variable or a method
4.
5. %>

Code

Here is the method declaration:

1. <%!
2.
3. String makeItLower(String data)
4.
5. {
6.
7. returndata.toLowerCase();
8.
9. }
10.
11. %>

Here is how you call it

Lower case “Hello World”:<%= makeItLower(“Hello World”) %>

Output

Lower case “Hello World”: hello world

Explanation

In the method declaration you have your standard java method with the return type of a String.
You take a string as an argument and return it converted to lower case. Later we call this
function through a JSP Expression.

JSP Standard Actions


Description
The JSP Standard Actions are used within the JSP page and are used to eliminate or remove scriptlet
code in a JSP page because now-a-days, scriptlet tag is not recommended. The programmers consider
these has a bad practice to put the Java code in the JSP page. The standard tags are as follows.

 jsp:include
 jsp:forward

Description
The jsp: forward activity tag is utilized to forward the solicitation starting with one asset then onto the
next resource.The different assets are JSP, HTML.

Syntax

<jsp:forward page=“relativeURL | <%= expression %>”/>

//jsp:forwar tag with parameters

<jsp:forward page=“relativeURL | <%= expression %>”>


<jsp:param name=“parametername” value=“parametervalue | <%=expression%>” />

</jsp:forward>
Example
JSP Standard Actions – Following is an example.

index.jsp

<html>

<head>

<title>JSP forward action tag example</title>

</head>

<body>

My main JSP page

<jsp:forward page="printdata.jsp" />

</body>

</html>

Here the developer just forward tag for the page printdata.jsp .
printdata.jsp

<html>

<head><title>Display Page</title></head>

<body>

Hello this is a display.jsp Page

</body>

</html>

When compile the code from the index.jsp page printdata.jsp page text will be displayed.
Output
Now compile the code from index.jsp file, result will be as follows.
Example
JSP Standard Actions – Following is an example.

farwithpar.jsp

<html>

<head><title>JSP forward example with parameters</title></head>

<body>

<jsp:forward page="display.jsp">

<jsp:param name="name" value="Sai" />

<jsp:param name="site" value="Splessons.com" />

<jsp:param name="tutorialname" value="jsp forward action" />

<jsp:param name="reqcamefrom" value="farwithpar.jsp" />

</jsp:forward>

</body>

</html>

Here forward tag used on display.jsp page, parameters are passing here.
display.jsp

<html>

<head><title>Display Page</title></head>

<body>

<h2>Hello this is a display.jsp Page</h2>


My name is: <%=request.getParameter("name") %>

Website: <%=request.getParameter("site") %>

Topic: <%=request.getParameter("SPlesson") %>

Forward Request came from the page: <%=request.getParameter("reqcamefrom") %>

</body>

</html>

The request.getParameter() is used to retrieve the parameters.


Output
Now compile the code result will be as follows.

Description
The jsp:include tag are used to include the content of the other resource like jsp, html, servlet, The
include action tag are process or include the content at the request time, so jsp:included tag is utilized
for element pages since it may change in future. Reusability of a code is an advantgae with include tag.

JSP include directive JSP include action

At interpretation time it incorporates different assets. At solicitation time it incorporate different assets.

It better to use static pages. It better to use dynamic pages.

Syntax

<jsp:include page=“relativeURL | <%= expression %>” />

//jsp:include action tag with parameter


<jsp:include page=“relativeURL | <%= expression %>”>

<jsp:param name=“parametername” value=“parametervalue | <%=expression%>” />

</jsp:include>

Example
includetag.jsp

<html>

<body>

<h2>Hi</h2>

<h2><jsp:include page="printdata.jsp"/></h2>

</body>

</html>

Here printdata.jsp page has been included.


printdata.jsp

<html>

<head><title>Display Page</title></head>

<body>

Hello this is a display.jsp Page

</body>

</html>

The parameters have passed here.


Output
Now compile the code result will be as follows.
action tag redirect the servlet Request and Servlet Response to another resource specified in the tag.
The path of the resource is ‘relative path’. The output generated by current JSP will be discarded.
action tag process the resource as part of the current jsp. It include the output generated by resource,
which is specified in the Tag to the current JSP. In both the cases single Request process multiple
resources.

Key Points

 JSP Standard Actions – Forward tag is used to forward the request and response to other
resources.
 JSP Standard Actions – Include tag is used to insert another file like html, JSP, java

What Are Custom Actions?


Custom actions provide us with a shorthand for complex Java code within our JSP. Anything
you do with a custom action could also be accomplished with Java code inside of the scriptlet
(<% %>) tag. After all, the JSP is turned into a servlet before it is compiled and executed for
end users.

As we saw last month with JavaBean tags, custom actions are defined with XML rather than
HTML. This can be confusing and frustrating at first, especially for those of us who have
acquired bad habits when writing HTML. The following might appear to be legal:

<P><jsp:getProperty name="simple"
property="userID"></P>

But in fact, the above line will not work and will result in an exception and stack trace within
the JSP. That's because all tags in XML must be closed somehow. If a <tag> has no matching
</tag>, then it must indicate that it closes itself with <tag/>. Thus, the above line must
actually be written as:

<P><jsp:getProperty name="simple"
property="userID"/></P>
Custom actions are merely syntactic sugar for Java methods. Each tag library defines a set of
actions. For example, the jsp tag library defines three actions: “getProperty”, “setProperty”
and “useBean”. Each action is defined by a single Java class, known as a tag handler.

To define a tag library, we create an XML file known as a tag library descriptor, or TLD. The
TLD connects each action to its appropriate tag handler class, listing optional and mandatory
attributes, as well as other information about the tags.
Unit III

JavaBeans
A JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans API specifications.

Following are the unique characteristics that distinguish a JavaBean from other Java classes −

 It provides a default, no-argument constructor.


 It should be serializable and that which can implement the Serializable interface.
 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.

JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.

A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −

S.No. Method & Description

getPropertyName()
1
For example, if property name is firstName, your method name would be
getFirstName() to read that property. This method is called accessor.
setPropertyName()
2
For example, if property name is firstName, your method name would be
setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute
will have only a setPropertyName() method.

JavaBeans Example

Consider a student class with few properties −

package com.tutorialspoint;

public class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;

public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}

Struts 2
Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications.
This framework is designed to streamline the full development cycle from building, to deploying and
maintaining applications over time. Apache Struts 2 was originally known as Web Work 2. This tutorial
will teach you, how to use Apache Struts for creating enterprise-ready Java web applications in simple
and easy steps.

Basic MVC Architecture


Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following three
parts −

 Model − The lowest level of the pattern which is responsible for maintaining data.
 View − This is responsible for displaying all or a portion of the data to the user.
 Controller − Software Code that controls the interactions between the Model and View.

MVC is popular as it isolates the application logic from the user interface layer and supports
separation of concerns. Here the Controller receives all requests for the application and then
works with the Model to prepare any data needed by the View. The View then uses the data
prepared by the Controller to generate a final presentable response. The MVC abstraction can be
graphically represented as follows.
The Model

The model is responsible for managing the data of the application. It responds to the request
from the view and it also responds to instructions from the controller to update itself.

The View

It means presentation of data in a particular format, triggered by a controller's decision to present


the data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate
with AJAX technology.

The Controller

The controller is responsible for responding to the user input and perform interactions on the data
model objects. The controller receives the input, it validates the input and then performs the
business operation that modifies the state of the data model.
Struts 2 Features
Struts 2 provides many features that were not in struts 1. The important features of struts 2
framework are as follows:

1) Configurable MVC components

In struts 2 framework, we provide all the components (view components and action) information
in struts.xml file. If we need to change any information, we can simply change it in the xml file.

2) POJO based actions

In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java class. Here, you are not
forced to implement any interface or inherit any class.

3) AJAX support

Struts 2 provides support to ajax technology. It is used to make asynchronous request i.e. it
doesn't block the user. It sends only required field data to the server side not all. So it makes the
performance fast.

4) Integration Support

We can simply integrate the struts 2 application with hibernate, spring, tiles etc. frameworks.

5) Various Result Types

We can use JSP, freemarker, velocity etc. technologies as the result in struts 2.

6) Various Tag support

Struts 2 provides various types of tags such as UI tags, Data tags, control tags etc to ease the
development of struts 2 application.

7) Theme and Template support

Struts 2 MVC pattern


Struts 2 provides three types of theme support: xhtml, simple and css_xhtml. The xhtml is
default theme of struts 2. Themes and templates can be used for common look and feel

Struts2 is a pull-MVC (or MVC2) framework. The Model-ViewController pattern in Struts2 is


implemented with the following five core components −
 Actions
 Interceptors
 Value Stack / OGNL
 Results / Result types
 View technologies

Struts 2 is slightly different from a traditional MVC framework, where the action takes the role
of the model rather than the controller, although there is some overlap.

The above diagram depicts the Model, View and Controller to the Struts2 high level architecture.
The controller is implemented with a Struts2 dispatch servlet filter as well as interceptors, this
model is implemented with actions, and the view is a combination of result types and results. The
value stack and OGNL provides common thread, linking and enabling integration between the
other components.

Apart from the above components, there will be a lot of information that relates to configuration.
Configuration for the web application, as well as configuration for actions, interceptors, results,
etc.

This is the architectural overview of the Struts 2 MVC pattern. We will go through each
component in more detail in the subsequent chapters.
Request Life Cycle

Based on the above diagram, you can understand the work flow through user's request life cycle
in Struts 2 as follows −

 User sends a request to the server for requesting for some resource (i.e. pages).
 The Filter Dispatcher looks at the request and then determines the appropriate Action.
 Configured interceptor functionalities applies such as validation, file upload etc.
 Selected action is performed based on the requested operation.
 Again, configured interceptors are applied to do any post-processing if required.
 Finally, the result is prepared by the view and returns the result to the user.

Struts 2 - Configuration Files


The struts application contains two main configuration files struts.xml file and
struts.properties file.

The struts.properties file is used to override the default values of default.xml file provided by
struts framework. So it is not mandatory. Mostly, you will not use struts.properties file. We will
learn about it later.

Here, we are going to learn all about struts.xml file. First of all let us see the simple example of
struts.xml file

struts.xml

1. <?xml version="1.0" encoding="UTF-8" ?>


2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6.
7. <action name="product" class="com.javatpoint.Product">
8. <result name="success">welcome.jsp</result>
9. </action>
10.
11. </package>
12. </struts>

1) package element

We can easily divide our struts application into sub modules. The package element specifies a
module. You can have one or more packages in the struts.xml file.
Attributes of package element

 name name is must for defining any package.


 namespace It is an optional attribute of package. If namespace is not present, / is assumed as
the default namespace. In such case, to invoke the action class, you need this URI:
1. /actionName.action

If you specify any namespace, you need this URI:

1. /namespacename/actionName.action
 extends The package element mostly extends the struts-default package where interceptors
and result types are defined. If you extend struts-default, all the actions of this package can use
the interceptors and result-types defined in the struts-default.xml file.

2) action element

The action is the subelement of package and represents an action.

Attributes of action element

 name name is must for defining any action.


 class class is the optional attribute of action. If you omit the class attribute, ActionSupport will
be considered as the default action. A simple action may be as:
1. <action name="product">
 method It is an optional attribute. If you don't specify method attribute, execute method will be
considered as the method of action class. So this code:

1. <action name="product" class="com.javatpoint.Product">

will be same as:

1. <action name="product" class="com.javatpoint.Product" method="execute">

If you want to invoke a particular method of the action, you need to use method attribute.

3) result element

It is the sub element of action that specifies where to forward the request for this action.

Attributes of result element

 name is the optional attribute. If you omit the name attribute, success is assumed as the default
result name.
 type is the optional attribute. If you omit the type attribute, dispatcher is assumed as the
default result type.
Other elements

There are many other elements also such as global-exception-mappings, global-results,


include etc

Struts 2 Action
In struts 2, action class is POJO (Plain Old Java Object).

POJO means you are not forced to implement any interface or extend any class.

Generally, execute method should be specified that represents the business logic. The simple
action class may look like:

Welcome.java

1. package com.javatpoint;
2. public class Welcome {
3. public String execute(){
4. return "success";
5. }
6. }

Action Interface

A convenient approach is to implement the com.opensymphony.xwork2.Action interface that


defines 5 constants and one execute method.

5 Constants of Action Interface

Action interface provides 5 constants that can be returned form the action class. They are:

1. SUCCESS indicates that action execution is successful and a success result should be shown to
the user.
2. ERROR indicates that action execution is failed and a error result should be shown to the user.
3. LOGIN indicates that user is not logged-in and a login result should be shown to the user.
4. INPUT indicates that validation is failed and a input result should be shown to the user again.
5. NONE indicates that action execution is successful but no result should be shown to the user.

Let's see what values are assigned to these constants:

1. public static final String SUCCESS = "success";


2. public static final String ERROR = "error";
3. public static final String LOGIN = "login";
4. public static final String INPUT = "input";
5. public static final String NONE = "none";

Method of Action Interface

Action interface contains only one method execute that should be implemented overridden by the
action class even if you are not forced.

1. public String execute();

Example of Struts Action that implements Action interface

If we implement the Action interface, we can directly use the constants instead of values.

Welcome.java

1. package com.javatpoint;
2. import com.opensymphony.xwork2.Action;
3. public class Welcome implements Action{
4. public String execute(){
5. return SUCCESS;
6. }
7. }

ActionSupport class

It is a convenient class that implements many interfaces such as Action, Validateable,


ValidationAware, TextProvider, LocaleProvider and Serializable . So it is mostly used instead of
Action.

Example of Struts Action that extends ActionSupport class

Let's see the example of Action class that extends the ActionSupport class.

Welcome.java

1. package com.javatpoint;
2. import com.opensymphony.xwork2.ActionSupport;
3. public class Welcome extends ActionSupport{
4. public String execute(){
5. return SUCCESS;
6. }
7. }
Struts 2 Interceptors
nterceptor is an object that is invoked at the preprocessing and postprocessing of a request. In
Struts 2, interceptor is used to perform operations such as validation, exception handling,
internationalization, displaying intermediate result etc.

Advantage of interceptors

Pluggable If we need to remove any concern such as validation, exception handling, logging etc.
from the application, we don't need to redeploy the application. We only need to remove the
entry from the struts.xml file.

Struts 2 default interceptors

There are many interceptors provided by struts 2 framework. We have option to create our own
interceptors. The struts 2 default interceptors are as follows:

1) alias It converts similar parameters that have different names between requests.

2) autowiring

3) chain If it is used with chain result type, it makes the properties of previous action available in
the current action.

4) checkbox It is used to handle the check boxes in the form. By this, we can detect the
unchecked checkboxes.

5) cookie It adds a cookie to the current action.

6) conversionError It adds conversion errors to the action's field errors.

7) createSession It creates and HttpSession object if it doesn't exists.

8) clearSession It unbinds the HttpSession object.

9) debugging It provides support of debugging.

10) externalRef

11) execAndWait It sends an intermediate waiting page for the result.

12) exception It maps exception to a result.


13) fileUpload It provides support to file upload in struts 2.

14) i18n It provides support to internationalization and localization.

15) jsonValidation It provides support to asynchronous validation.

16) logger It outputs the action name.

17) store It stores and retrieves action messages, action errors or field errors for action that
implements ValidationAware interface.

18) modelDriven It makes other model object as the default object of valuestack.

19) scopedModelDriven It is similar to ModelDriven but works for action that implements
ScopedModelDriven.

20) params It populates the action properties with the request parameters.

21) actionMappingParams

22) prepare It performs preparation logic if action implements Preparable interface.

23) profiling It supports action profiling.

24) roles It supports role-based action.

25) scope It is used to store the action state in the session or application scope.

26) servletConfig It provides access to maps representing HttpServletRequest and


HttpServletResponse.

27) sessionAutowiring

28) staticParams It maps static properties to action properties.

29) timer It outputs the time needed to execute an action.

30) token It prevents duplication submission of request.

31) tokenSession It prevents duplication submission of request.

32) validation It provides support to input validation.

33) workflow It calls the validate method of action class if action class implements Validateable
interface.
34) annotationWorkflow

35) multiselect

Results & Result Types


he <results> tag plays the role of a view in the Struts2 MVC framework. The action is
responsible for executing the business logic. The next step after executing the business logic is to
display the view using the <results> tag.

Often there is some navigation rules attached with the results. For example, if the action method
is to authenticate a user, there are three possible outcomes.

 Successful Login
 Unsuccessful Login - Incorrect username or password
 Account Locked

In this scenario, the action method will be configured with three possible outcome strings and
three different views to render the outcome. We have already seen this in the previous examples.

But, Struts2 does not tie you up with using JSP as the view technology. Afterall the whole
purpose of the MVC paradigm is to keep the layers separate and highly configurable. For
example, for a Web2.0 client, you may want to return XML or JSON as the output. In this case,
you could create a new result type for XML or JSON and achieve this.

Struts comes with a number of predefined result types and whatever we've already seen that was
the default result type dispatcher, which is used to dispatch to JSP pages. Struts allow you to use
other markup languages for the view technology to present the results and popular choices
include Velocity, Freemaker, XSLT and Tiles.

The Dispatcher Result Type

The dispatcher result type is the default type, and is used if no other result type is specified. It's
used to forward to a servlet, JSP, HTML page, and so on, on the server. It uses the
RequestDispatcher.forward() method.

We saw the "shorthand" version in our earlier examples, where we provided a JSP path as the
body of the result tag.

<result name = "success">


/HelloWorld.jsp
</result>

We can also specify the JSP file using a <param name = "location"> tag within the <result...>
element as follows −
<result name = "success" type = "dispatcher">
<param name = "location">
/HelloWorld.jsp
</param >
</result>

We can also supply a parse parameter, which is true by default. The parse parameter determines
whether or not the location parameter will be parsed for OGNL expressions.

The FreeMaker Result Type

In this example, we are going to see how we can use FreeMaker as the view technology.
Freemaker is a popular templating engine that is used to generate output using predefined
templates. Let us now create a Freemaker template file called hello.fm with the following
contents −

Hello World ${name}

The above file is a template where name is a parameter which will be passed from outside using
the defined action. You will keep this file in your CLASSPATH.

Next, let us modify the struts.xml to specify the result as follows −

<?xml version = "1.0" Encoding = "UTF-8"?>


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name = "struts.devMode" value = "true" />
<package name = "helloworld" extends = "struts-default">

<action name = "hello"


class = "com.tutorialspoint.struts2.HelloWorldAction"
method = "execute">
<result name = "success" type = "freemarker">
<param name = "location">/hello.fm</param>
</result>
</action>

</package>

</struts>

Let us keep our HelloWorldAction.java, HelloWorldAction.jsp and index.jsp files as we have


created them in examples chapter.

Now Right click on the project name and click Export > WAR File to create a War file.
Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to
access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the
following screen .

Enter a value "Struts2" and submit the page. You should see the next page.

As you can see, this is exactly same as the JSP view except that we are not tied to using JSP as
the view technology. We have used Freemaker in this example.
The Redirect Result Type

The redirect result type calls the standard response.sendRedirect() method, causing the browser
to create a new request to the given location.

We can provide the location either in the body of the <result...> element or as a <param name =
"location"> element. Redirect also supports the parse parameter. Here's an example configured
using XML −

<action name = "hello"


class = "com.tutorialspoint.struts2.HelloWorldAction"
method = "execute">
<result name = "success" type = "redirect">
<param name = "location">
/NewWorld.jsp
</param >
</result>
</action>

So just modify your struts.xml file to define redirect type as mentioned above and create a new
file NewWorld.jpg where you will be redirected whenever hello action will return success.

JSON Tutorial
https://www.tutorialspoint.com/json/index.ht
m

You might also like