Advance Java Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

Advance java notes

Chapter 1

Servlet Introduction

Java Servlets are the Java programs that run on the Java-enabled web
server or application server. They are used to handle the request
obtained from the web server, process the request, produce the
response, and then send a response back to the web server.

Properties of Java Servlet

The properties of Servlets are as follows:


 Servlets work on the server side.
 Servlets are capable of handling complex requests obtained from the
web server.

Execution of Java Servlets

Execution of Servlets basically involves Six basic steps:


1. The Clients send the request to the Web Server.
2. The Web Server receives the request.
3. The Web Server passes the request to the corresponding servlet.
4. The Servlet processes the request and generates the response in the
form of output.
5. The Servlet sends the response back to the webserver.
6. The Web Server sends the response back to the client and the client
browser displays it on the screen.

Web Terminology
Servlet Terminology Description

Website: static vs It is a collection of related web pages that may contain text, image
dynamic and video.

HTTP It is the data communication protocol used to establish commu


between client and server.

HTTP Requests It is the request send by the computer to a web server that contains
of potentially interesting information.

Get vs Post It gives the difference between GET and POST request.

Container It is used in java for dynamically generating the web pages on the serv

Server: Web vs It is used to manage the network resources and for running the prog
Application software that provides services.

Content Type It is HTTP header that provides the description about what are you sen
the browser.

Servlet API
Servlets are the Java programs that run on the Java-enabled web server
or application server. They are used to handle the request obtained from
the webserver, process the request, produce the response, then send a
response back to the webserver. In Java, to create web applications we
use Servlets. To create Java Servlets, we need to use Servlet API which
contains all the necessary interfaces and classes. Servlet API has 2
packages namely,
 javax.servlet
 javax.servlet.http

javax.servlet

 This package provides the number of interfaces and classes to


support Generic servlet which is protocol independent.
 These interfaces and classes describe and define the contracts
between a servlet class and the runtime environment provided by a
servlet container.

javax.servlet.http

 This package provides the number of interfaces and classes to


support HTTP servlet which is HTTP protocol dependent.
 These interfaces and classes describe and define the contracts
between a servlet class running under HTTP protocol and the runtime
environment provided by a servlet container.

Servlet Interface :
javax.servlet.Servlet
The Servlet interface defines methods to initialize a servlet, to receive and
respond to client requests, and to destroy a servlet and its resources. These
are known as life-cycle methods, and are called by the network service in
the following manner:

1. Servlet is created then initialized.


2. Zero or more service calls from clients are handled
3. Servlet is destroyed then garbage collected and finalized

This interface is for developing servlets. A servlet is a body of Java code


that is loaded into and runs inside a servlet engine, such as a web server. It
receives and responds to requests from clients. For example, a client may
need information from a database; a servlet can be written that receives the
request, gets and processes the data as needed by the client, and then returns
it to the client. All servlets implement this interface.

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.

public void service(ServletRequest provides response for the incoming request.


request,ServletResponse response) It is invoked at each request by the web
container.

public void destroy() is invoked only once and indicates that


servlet is being destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as


writer, copyright, version etc.

GenericServlet class
GenericServlet class
implements Servlet, ServletConfig and Serializable interfaces. It provides the
implementation of all the methods of these interfaces except the service
method.

GenericServlet class can handle any type of request so it is protocol-


independent.

You may create a generic servlet by inheriting the GenericServlet class and
providing the implementation of the service method.

Methods of GenericServlet class

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request,
ServletResponse response) provides service for the incoming request.
It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle
and indicates that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of
ServletConfig.
5. public String getServletInfo() returns information about servlet such
as writer, copyright, version etc.
6. public void init() it is a convenient method for the servlet
programmers, now there is no need to call super.init(config)

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

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}

HttpServlet class
The HttpServlet class extends the GenericServlet class and implements
Serializable interface. It provides http specific methods such as doGet, doPost,
doHead, doTrace etc.

Methods of HttpServlet class

1. public void service(ServletRequest req,ServletResponse


res) dispatches the request to the protected service method by
converting the request and response object into http type.
2. protected void service(HttpServletRequest req,
HttpServletResponse res) receives the request from the service
method, and dispatches the request to the doXXX() method depending
on the incoming http request type.
3. protected void doGet(HttpServletRequest req,
HttpServletResponse res) handles the GET request. It is invoked by
the web container.
4. protected void doPost(HttpServletRequest req,
HttpServletResponse res) handles the POST request. It is invoked by
the web container.
5. protected void doHead(HttpServletRequest req,
HttpServletResponse res) handles the HEAD request. It is invoked by
the web container.
6. protected void doOptions(HttpServletRequest req,
HttpServletResponse res) handles the OPTIONS request. It is invoked
by the web container.

Life Cycle of a Servlet (Servlet Life


Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the
life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init m
used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Synt
init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three steps as
described above then calls the service method. If servlet is initialized, it calls
the service method. Notice that servlet is initialized only once. The syntax of
the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet
instance from the service. It gives the servlet an opportunity to clean up any
resource for example memory, thread etc. The syntax of the destroy method
of the Servlet interface is given below:

public void destroy()

Servelet with IDE


https://www.javatpoint.com/creating-servlet-in-eclipse-ide

ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a
servlet such as content type, content length, parameter names and values, header
informations, attributes etc.
Method Description

public String getParameter(String is used to obtain the value of a parameter by


name) name.

public String[] returns an array of String containing all


getParameterValues(String name) values of given parameter name. It is mainly
used to obtain values of a Multi select list
box.

java.util.Enumeration returns an enumeration of all of the request


getParameterNames() parameter names.

public int getContentLength() Returns the size of the request entity data,
or -1 if not known.

public String getCharacterEncoding() Returns the character set encoding for the
input of this request.

public String getContentType() Returns the Internet Media Type of the


request entity data, or null if not known.

public ServletInputStream Returns an input stream for reading binary


getInputStream() throws data in the request body.
IOException

public abstract String Returns the host name of the server that
getServerName() received the request.

public int getServerPort() Returns the port number on which this


request was received.

index.html
<form action="welcome" method="get">
Enter your name<input type="text" name="name"><br>
<input type="submit" value="login">
</form>
DemoServ.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

String name=req.getParameter("name");//will return value


pw.println("Welcome "+name);

pw.close();
}}
Servelet colaboration interface
RequestDespatcher Interface
The RequestDispatcher interface provides the facility of dispatching the request
to another resource it may be html, servlet or jsp. This interface can also be used
to include the content of another resource also. It is one of the way of servlet
collaboration.

Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException:Forwards a
request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.
2. public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.

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

public class Login extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
String p=request.getParameter("userPass");

if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
ServletConfig Interface
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.

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

public class DemoServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");
out.print("Driver is: "+driver);

out.close();
}
}

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.

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.

Syntax of getServletContext() method

public ServletContext getServletContext()


Example of getServletContext() method

//We can get the ServletContext object from ServletConfig object


ServletContext application=getServletConfig().getServletContext();
//Another convenient way to get the ServletContext object
ServletContext application=getServletContext();

Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one
of the following scopes:

1. request scope
2. session scope
3. application scope

The servlet programmer can pass informations from one servlet to another
using attributes. It is just like passing object from one class to another so that
we can reuse the same object again and again.

methods of ServletRequest, HttpSession and


ServletContext interface

1. public void setAttribute(String name,Object object):sets the given


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

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{

res.setContentType("text/html");
PrintWriter out=res.getWriter();

ServletContext context=getServletContext();
context.setAttribute("company","IBM");

out.println("Welcome to first servlet");


out.println("<a href='servlet2'>visit</a>");
out.close();

}catch(Exception e){out.println(e);}
}}

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple
client requests.

A cookie has a name, a single value, and optional attributes such as a


comment, path and domain qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique,
we add cookie with response from the servlet. So cookie is stored in the cache
of the browser. After that if request is sent by the user, cookie is added with
request by default. Thus, we recognize the user as the old user.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

2) Hidden Form Field


In case of Hidden Form Field a hidden (invisible) textfield is used for
maintaining the state of an user.

In such case, we store the information in the hidden field and get it from
another servlet. This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.

Advantage of Hidden Form Field

1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

1. It is maintained at server side.


2. Extra form submission is required on each pages.
3. Only textual information can be used.

3)URL Rewriting
n URL rewriting, we append a token or identifier to the URL of the next Servlet
or the next resource. We can send parameter name/value pairs using the
following format:
url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter


name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter name/value
pairs will be passed to the server. From a Servlet, we can use getParameter()
method to obtain a parameter value.

Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser


independent).
2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information.

4) HttpSession interface
In such case, container creates a session id for each user.The container uses
this id to identify the particular user.An object of HttpSession can be used to
perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
Event and Listener in Servlet
Events are basically occurrence of something. Changing the state of an object
is known as an event.

We can perform some important tasks at the occurrence of these exceptions,


such as counting total and current logged-in users, creating tables of the
database at time of deploying the project, creating database connection
object etc.

Event classes
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent

Event interfaces
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener

Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing
of a request.

It is mainly used to perform filtering tasks such as conversion, logging,


compression, encryption and decryption, input validation etc.

The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.

So maintenance cost will be less.

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException {}

public void doFilter(ServletRequest req, ServletResponse resp,


FilterChain chain) throws IOException, ServletException {

PrintWriter out=resp.getWriter();
out.print("filter is invoked before");

chain.doFilter(req, resp);//sends request to next resource

out.print("filter is invoked after");


}
public void destroy() {}
}

Usage of Filter
o recording all incoming requests
o logs the IP addresses of the computers from which the requests
originate
o conversion
o data compression
o encryption and decryption

Advantage of Filter

1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance

CRUD in Servlet
A CRUD (Create, Read, Update and Delete) application is the most important
application for any project development. In Servlet, we can easily create CRUD
application.
CRUD means Create, Read, Update and Delete. These are the basic
important operations carried out on the Database and in applications. We
will build a simple User registration application using a Servlet, MYSQL,
and JDBC for demonstration. In this example, we will be able to create
users, read users, update users and delete users.
Technology tools:
 MySQL(workbench) Database
 IDE(Intellij)
 Apache Tomcat(I used the Tomcat 9 version)

Pagination in Servlet
To divide large number of records into multiple parts, we use pagination. It
allows user to display a part of records only. Loading all records in a single
page may take time, so it is always recommended to created pagination. In
servlet, we can develop pagination example easily.

In this servlet pagination example, we are using MySQL database to fetch


records.

Here, we have created "emp" table in "test" database. The emp table has three
fields: id, name and salary. Either create table and insert records manually or
import our sql file.
ServletInputStream class
ServletInputStream class provides stream to read binary data such as image
etc. from the request object. It is an abstract class.

The getInputStream() method of ServletRequest interface returns the


instance of ServletInputStream class. So can be get as:

ServletInputStream sin=request.getInputStream();

Method of ServletInputStream class

1. int readLine(byte[] b, int off, int len) it reads the input stream.

ServletOutputStream class
ServletOutputStream class provides a stream to write binary data into the
response. It is an abstract class.

The getOutputStream() method of ServletResponse interface returns the


instance of ServletOutputStream class. It may be get as:

Methods of ServletOutputStream class

1. void print(boolean b){}


2. void print(char c){}
3. void print(int i){}
4. void print(long l){}
5. void print(float f){}
6. void print(double d){}
7. void print(String s){}
8. void println{}

Servlet with Annotation


Annotation represents the metadata. If you use annotation, deployment
descriptor (web.xml file) is not required. But you should have tomcat7 as it will
not run in the previous versions of tomcat. @WebServlet annotation is used to
map the servlet with the specified name.
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Simple")
public class Simple extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse respo


nse)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out=response.getWriter();

out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
out.print("</body></html>");
}
}

SingleThreadModel interface
The servlet programmer should implement SingleThreadModel interface to
ensure that servlet can handle only one request at a time. It is a marker
interface, means have no methods.
This interface is currently deprecated since Servlet API 2.4 because it doesn't
solves all the thread-safety issues such as static variable and session attributes
can be accessed by multiple threads at the same time even if we have
implemented the SingleThreadModel interface. So it is recommended to use
other means to resolve these thread safety issues such as synchronized block
etc.

port java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet implements SingleThreadModel{


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("welcome");
try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}
out.print(" to servlet");
out.close();
}
}

Server Side Include (SSI)


Server-side includes are instructions and directives included in a web page that the
web server may analyze when the page is provided. SSI refers to the servlet code
that is embedded into the HTML code. Not all web servers can handle SSI. so you
may read documents supported by a web server before utilizing SSI in your code.
Syntax:
<SERVLET CODE=MyGfgClassname CODEBASE=path
initparam1=initparamvalue initparam2=initparam2value>
<PARAM NAME=name1 VALUE=value1>
<PARAM NAME=name2 VALUE=value2></SERVLET>
Here the path indicates the MyGfgClassname class name path in the server. you
can set up the remote file path also. the remote file path syntax is,
http://server:port/dir
When a server that does not support SSI sees the SERVLET> tag while returning
the page, it replaces it with the servlet’s output. The server does not parse all of the
pages it returns; only those with a.shtml suffix are parsed. The class name or
registered name of the servlet to invoke is specified by the code attributes. It’s not
required to use the CODEBASE property. The servlet is presumed to be local
without the CODEBASE attribute. The PARAM> element may be used to send
any number of parameters to the servlet. The getParameter() function of
ServletRequest may be used by the servlet to obtain the parameter values.
mport java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GfgTime extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException
{
PrintWriter out = res.getWriter();
Date date = new Date();
DateFormat df = DateFormat.getInstance();

// Here write the response shtml file


out.println("Hello GEEKS, current time is:");
out.println(df.format(date));
}
}

JSP
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.

Advantages of JSP
1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic
with presentation logic. In Servlet technology, we mix our business logic with
the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project.
The Servlet code needs to be updated and recompiled if we have to change
the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

 Translation of JSP page to Servlet: This is the first step of the


JSP life cycle. This translation phase deals with the Syntactic
correctness of JSP. Here test.jsp file is translated to test.java.
 Compilation of JSP page: Here the generated java servlet file
(test.java) is compiled to a class file (test.class).
 Classloading: The classloader loads the Java class file into the
memory. The loaded Java class can then be used to serve
incoming requests for the JSP page.
 Instantiation: Here an instance of the class is generated. The
container manages one or more instances by providing
responses to requests.
 Initialization: jspInit() method is called only once during the life
cycle immediately after the generation of the Servlet instance
from JSP.
 Request processing: _jspService() method is used to serve the
raised requests by JSP. It takes request and response objects
as parameters. This method cannot be overridden.
 JSP Cleanup: In order to remove the JSP from the use by the
container or to destroy the method for servlets
jspDestroy()method is used. This method is called once, if you
need to perform any cleanup task like closing open files, or
releasing database connections jspDestroy() can be overridden.

JSP API
JSP API is a set of classes and interfaces that can be used to make a
JSP page. These classes and interfaces are contained in the javax
servlet.jsp packages.

The JSP API consists of package:

1. javax.servlet.jsp

javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.The two interfaces
are as follows:

1. JspPage
2. HttpJspPage

The classes are as follows:

o JspWriter
o PageContext
o JspFactory
o JspEngineInfo
o JspException
o JspError

The JspPage interface


According to the JSP specification, all the generated servlet classes must
implement the JspPage interface. It extends the Servlet interface. It provides
two life cycle methods.

The HttpJspPage interface


The HttpJspPage interface provides the one life cycle method of JSP. It
extends the JspPage interface.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

syntax: <% java source code %>

<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of
the response. So you need not write out.print() to write data. It is mainly used
to print the values of variable or method.

syntax: <%= statement %>

<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
JSP Declaration Tag

The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.

So it doesn't get memory at each request.

Syntax : <%! field or method declaration %>


<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

JSP Implicit Objects


There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:

Object Type
out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

out :

For writing any data to the buffer, JSP provides an implicit object named out.
It is the object of JspWriter. In case of servlet you need to write:

PrintWriter out=response.getWriter();

Request:
he JSP request is an implicit object of type HttpServletRequest i.e. created for
each jsp request by the web container. It can be used to get request information
such as parameter, header information, remote address, server name, server port,
content type, character encoding etc.
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>

Response:
In JSP, response is an implicit object of type HttpServletResponse. The
instance of HttpServletResponse is created by the web container for each jsp
request.
It can be used to add or manipulate response such as redirect response to
another resource, send error etc.

<%
response.sendRedirect("http://www.google.com");
%>

Config:
In JSP, config is an implicit object of type ServletConfig. This object can be
used to get initialization parameter for a particular JSP page. The config object
is created by the web container for each jsp page.

Generally, it is used to get initialization parameter from the web.xml file.

<%
out.print("Welcome "+request.getParameter("uname"));

String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>

Application:
In JSP, application is an implicit object of type ServletContext.

The instance of ServletContext is created only once by the web container


when application or project is deployed on the server.

<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>

Session:
In JSP, session is an implicit object of type HttpSession.The Java developer can
use this object to set,get or remove attribute or to get session information.
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>

PageContext:
In JSP, pageContext is an implicit object of type PageContext class.The
pageContext object can be used to set,get or remove attribute from one of
the following scopes:
o page
o request
o session
o application

<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>

Page:
In JSP, page is an implicit object of type Object class.This object is assigned to the reference
generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For example:
<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object directly in jsp.For exampl
<% this.log("message"); %>

Exception:
In JSP, exception is an implicit object of type java.lang.Throwable class. This
object can be used to print the exception. But it can only be used in error
pages.It is better to learn it after page directive.
<%@ page isErrorPage="true" %>
<html>
<body>

Sorry following exception occured:<%= exception %>

</body>
</html>

JSP directive elements


The jsp directives are messages that tells the web container how to translate
a JSP page into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Attributes of JSP page directive

o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

Jsp Include Directive


The include directive is used to include the contents of any resource it may be jsp
file, html file or text file. The include directive includes the original content of the
included resource at page translation time (the jsp page is translated only once so
it will be better to include static resource).

Syntax of include directive

<%@ include file="resourceName" %>

JSP Taglib directive


The JSP taglib directive is used to define a tag library that defines many tags. We
use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag
section we will use this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

You might also like