SERVLETS
1. Using the java programming language we can develop different types of
applications, and they are:
Stand Alone Applications:
Standalone applications are also known as desktop applications.
➢ These applications has to be installed in every manchine.
➢ It can execute only in a single machine where it is installed.
➢ The installation/uninstallation of application is specific to a client.
Mobile Applications:
➢ An application which is created for mobile devices is called a mobile
application.
➢ Currently, Android and Java ME are used for creating mobile applications.
➢ The mobile applications can execute only in that platform for which they are
developed.
Web Based Applications:
➢ An application that runs on the server side and creates a dynamic page is called a
web application.
➢ These applications are also called as client server applications.
➢ Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used
for creating web applications in Java.
Every web based application requires 2 types of software’s, and they are:
1) Client Software, 2) Server Software.
Client Software: It can be any browser that we use in our machine like internet
explorer, chrome, firefox etc. Every operating system will provide one default
browser.
Server Software: These servers are available in the market like tomcat, weblogic,
glassfish, websphere etc.
➢ The user will send the request to the server by using the client software, the server
software will receive the request and process the request and then send the
response to the client.
➢ A web based application consists of web resources (html, images, css, js files etc)
and web components (servlets and jsp).
➢ To make the communication between client and server in a application we use a
protocol called HTTP.
➢ The web based applications that we develop are classified into Static web
application and Dynamic web application.
➢ Static: The Application which won't be changed from person to person and time
to time, such type of response is called as Static. Ex: Login page, Registration
page etc. [html]
➢ Dynamic: The Application which is varied from person to person and time to
time, such type of response is called as Dynamic. Ex: Inbox, Bank Balance etc.
[servlet, jsp etc...]
Servlet:
Servlet API is a part of JEE API, Servlet is an API for developing web based application.
To develop interactive and dynamic web applications we use servlets. Servlet is a server
side java program, which extends the functionality of web server. Servlets are writing
once and deploy any where. Servlets are by default multi threaded. Servlets run on the
server side.
The servlet API is pprovided to the programmer in the form of two packages.
javax.servlet
javax.servlet.http
Developing a servlet application means implementing the Servlet Interface either directly
or indirectly.
A servlet program can be developed in 3 ways:
A servlet program can be developed by implementing Servlet Interface.
A servlet program can be developed by extending GenericServlet class.
A servlet program can be developed by extending HttpServlet class.
Servlet Interface
The Servlet interface belongs to javax.servlet package and it contains the following 5
methods which has to be implemented.
Methods of Servlet interface:
o public void init(ServletConfig) : This method will be executed only onetime, when the servlet object is created or when the first request is sent to
the servlet.
o public void service(ServletRequest, ServletResponse) : This method is themain method to perform the actual task i.e it will contain the business
logic. The servlet container calls the service() method to handle requests
coming from the client and to send the response back to the client. The
service method checks the HTTP request type (GET, POST, PUT,
DELETE, etc) and calls doGet, doPost, doPut, doDelete, etc which is
appropriate.
o public void destroy() : This method is executed only one time, when theservlet is destroyed.
o public ServletConfig getServletConfig() : This method returns an object
of ServletConfig.
o public String getServletInfo() : This method returns the description aboutthe object.
HttpServlet Class
A GenericServlet is a protocol independent Servlet that should always override the
service() method to handle the client request. You may create a generic servlet by
inheriting the GenericServlet class and providing the implementation of the service
method.
Methods of Servlet interface to override:
public void service(ServletRequest, ServletResponse) : This method is the main methodto perform the actual task i.e it will contain the business logic. The servlet container calls
the service() method to handle requests coming from the client and to send the response
back to the client.
We can create a servlet by extending HttpServlet class. This is protocol dependent server,
it works only on HTTP protocol.
The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Unlike Generic Servlet, the HTTP Servlet doesn’t override the service() method. Instead
it overrides the doGet() method or doPost() method or both. The doGet() method is used
for getting the information from server while the doPost() method is used for sending
information to the server.
If the servlet gets HTTP GET request then it will automatically call doGet() method, and
if the servlet get HTTP POST request then it will automatically call doPost() method.
Methods of HttpServlet :
protected void doGet(HttpServletRequest request, HttpServletResponse response): Thismethod is called by servlet service method to handle the HTTP GET request from client.
While we are submitting a form by using get method then automatically doGet() method
will execute. By using this method we are sending values to server through URL. Mainly
this method will use when we want to get the information from the server. By using the
get method we can send only limited data to the server.
protected void doPost(HttpServletRequest req, HttpServletResponse resp): This methodis called by servlet service method to handle the POST request from client. While we are
submitting a form by using post method then automatically doPost() method will execute.
Mainly this is useful when we want to submit the data to the server. By using this method
we can send unlimited data to the server.
protected void doPut(HttpServletRequest req, HttpServletResponse resp): This method iscalled by servlet service method to handle the PUT request from client. This method is
GenericServlet Class
similar to doPost method but unlike doPost method where we send information to the
server, this method sends file to the server, this is similar to the FTP operation from client
to server.
protected void doDelete(HttpServletRequest req, HttpServletResponse resp): Called byservlet service() method to handle the DELETE request from client that allows a client to
delete a document, webpage or information from the server.
Init-param:
This tag has two child tags that are paramname and paramvalue.These initialization
parameters can be retrieved with in the Servlet by using servlet config object by calling
getInitParameter () on the config object.
Syntax:
Config. getInitParameter (“paramname”);
This Init-param tag will be there in web.xml. i.e
<init-param> <param-name> name </param-name> <param-value > Srianjaneya </param-value> </init-param>
In Servlet program by using Config object we can get the param-value.
i.e String str=Config.getInitParameter(“name”); now str=“Srianjaneya” ;
Single Thread Model
Ensures that servlet handle only one request at a time. This interface has no methods. If a
servlet implements this interface, you are guaranteed that no two threads will execute
concurrently in service method.
How do u implement thread in servlets
Internally.
Server.xml:
The contents of the server holds in a server.xml file
It is also called as servlets configuration file, for every server contain their individual
server configuration file.
Web.xml:
When we deploy the web application web container reads Web.xml
Then Web.xml file describes about the web application to the container so it is called as
DD (deployment Descriptor)
Syntax:
<web-app>
<servlet>
<servlet-name> Puji</servlet-name>
<servlet-class>com.slc.javaservlets.SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>puji</servlet-name>
<url-pattern>/InserServletProgram</url-pattern>
</servlet-mapping>
</web-app>In Tomcat when servlet object will be deallocated & destroyed
When you stop web application or you reload the web application or you undeploy the
web application.
How many times instantiation phase executed in servlet
Only once for Servlet initialization
Servlet Life Cycle:
1. When client sends a request to web container, web container creates request, response
and config objects.
2. After that it reads web.xml files from this one , it will find the URL pattern for
matching url pattern it will find the servlet-name for this servlet-name it will load the
appropriate servlet-class from servlet tag.
3. After servlet loading into web server memory connection will established to servlet
and web container. This communication is called instantiation. It will happen one time.
4. After instantiation web server calls the init() method is called once and used for
initialization purpose. If you are not writing init() method, init() method will provided by
web server. If you write init() method it will override the init() method.
5. For every request directly calls the service() method by passing request, response
objects by web server.
6. In service() method Http servlet request object translated into business logic.
7. When you stop web application or you reload the web application or you undeploy the
web application destroy() method will called by web server. We can’t call destroy()
method.
ServletConfig – SevletContext:
Servlet context object can be considered as global memory area should repository for the
web application. Servlet context is a one per web application. By using context object we
can call param-name, and param-value. This <cotext-param> will be present in web.xml.
<web-app>
<context-param>
<param-name>sai</param-name>
<param-value>Pujitha</param-value>
</context-param>
</web-app>In Servlet program by using context object we can call the context-param value.
String name=context.getInitParameter(“sai”);
ServletConfig used by the container provider initialization information and context
information to the servlets. Servlet config is one per servlet. Servlet config object always
holds the reference to the servlet context object
Syntax:
Config. getInitParameter (“paramname”);
This Init-param tag will be there in web.xml. i.e
<init-param> <param-name> name </param-name> <param-value > Srianjaneya </param-value> </init-param>
In Servlet program by using Config object we can get the param-value.
i.e String str=Config.getInitParameter(“name”); now str=“Srianjaneya” ;
Can you explicitly destroy servlet Object?
No
Can I write init – param in Web.xml?
Yes using Config. getInitParameter (“paramname”);
Can you write constructor in Servlet
There is a constructor in servlet default constructor. Every class in java has one whether
you write or not. The compiler will give you default constructor if you don’t provide any.
It will instantiate all private data members and initialize to their default value. The servlet
class only has a default constructor because all it needs. Servlet run in Servlet Container
and now where else. The container is calling the constructor for you and managing the
life cycle of servlet.
Can you use constructor instead of init () method to initialize Servlet
No. You can’t. It’s the container who manages the life cycle of the servlet not you. Also
you must call super.init () for init () to work properly.
Can you write parameterized constructor in servlet
Yes. Before that you write default constructor. But no use to writing parameterized
constructor in Servlet.
Load-on-startup: This tag specifies that the servlet should be loaded automatically when
the web application started. The value is a single positive integer which specifying the
loading order. You can load any number of servlets on the startup. Normally this is done
for an initialization purpose. Lower positive values loaded first. If the value is negative or
unspecified then the container can load the servlet at any time during startup.
Welcome-file-list: This tag configures the web application’s entry point. When a request
URL refers to a directory, the default servlet looks for a welcome file. Within that
directory and if present to the corresponding resource URL for display. If no welcome
file is present, the default servlet either serves a directory listing or returns 404 statuses
depending on how it is configured.
Servlet chaining:
Processing one request with multiple servlets as a chain of request processing is called
Send redirect - Request dispatcher forward:
In forward the request to be forwarded to the resource, which are available in same web
server. It will append the URL to the query string..
In sendredirect () the request to be forwarded to another resource, which are available to
the same web server or another web server.
In this URL will be changed. Performance wise forward is better than sendredirect (). In
sendRedirect() the request ,response objects will create two times, where as in forward
the request, response objects will create only one time.
Session tracking:
Basically http protocol is stateless protocol. We have to make our application as state full,
we can use session tracking. In servlets session tracking is implementing through
• Hidden form fields
• Cookies
• Sessions
• URL rewriting
Hidden Fields on the pages can maintain state and they are not visible on the browser.
The server treats both hidden and non-hidden fields the same way.
<INPUT type=”hidden” name=”First name” value=”Peter”> <INPUT type=”hidden” name=”Last name” value=”Smith”>
The disadvantage of hidden fields is that they may expose sensitive or private
information to others.
Example:
package com.java2s;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HiddenFieldServlet extends HttpServlet {/**
*
*/
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
super.init(config);
}// Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>HiddenFieldServlet" + "</title></head>");
out.println("<body>");// Create the Form with Hidden Fields
out.println("<FORM ACTION="+ "\"/sample/HiddenFieldServlet\" METHOD=\"POST\">");
// These values would be uniquely generated
out.println("<INPUT TYPE=\"hidden\" NAME="
+ "\"user\" VALUE=\"James\">"); out.println("<INPUT TYPE=\"hidden\" NAME=" + "\"session\" VALUE=\"12892\">");
// These are the currently selected movies
out.println("<INPUT TYPE=\"hidden\" NAME=" + "\"movie\" VALUE=\"Happy Gilmore\">"); out.println("<INPUT TYPE=\"hidden\" NAME="
+ "\"movie\" VALUE=\"So I Married an Axe
Murderer\">"); out.println("<INPUT TYPE=\"hidden\" NAME=" + "\"movie\" VALUE=\"Jaws\">"); out.println("<INPUT TYPE=\"submit\" VALUE=" + "\"Submit\">"); out.println("</FORM>"); out.println("</body></html>"); out.close(); }
// Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>HiddenFieldServlet" + "</title></head>");
out.println("<body>");// Get the hidden inputs and echo them
String user = request.getParameter("user"); System.out.println(user); String session = request.getParameter("session"); System.out.println(session); out.println("<H3>" + user
+ ", the contents of your Shopping Basket
are:</H3><BR>"); String[] movies = request.getParameterValues("movie"); if (movies != null) { for (int x = 0; x < movies.length; x++) { out.println(movies[x] + "<BR>"); } } out.println("</body></html>"); out.close(); }
// Get Servlet information
public String getServletInfo() {
return "HiddenFieldServlet Information";} }
Cookies
It is small piece of info sent by the server and resides in the client location as a file. It is
key value pair.
Cookies are created at server side and stored at client side.
Cookie max capacity 4kb.
A cookie is a piece of text that a Web server can store on a user’s hard disk. Cookies
allow a website to store information on a user’s machine and later retrieve it. These
pieces of information are stored as name-value pairs. The cookie data moves in the
following manner:
❖ If you type the URL of a website into your browser, your browser sends the
request to the Web server. When the browser does this it looks on your machine
for a cookie file that URL has set. If it finds it, your browser will send all of the
name-value pairs along with the URL. If it does not find a cookie file, it sends no
cookie data.
❖ The URL’s Web server receives the cookie data and requests for a page. If
name-value pairs are received, the server can use them. If no name-value pairs
are received, the server can create a new ID and then sends name-value pairs to
your machine in the header for the Web page it sends. Your machine stores the
name value pairs on your hard disk.
❖ Cookies can be used to determine how many visitors visit your site. It can also
determine how many are new versus repeated visitors. The way it does this is by
using a database. The first time a visitor arrives; the site creates a new ID in the
database and sends the ID as a cookie. The next time the same user comes back,
the site can increment a counter associated with that ID in the database and know
how many times that visitor returns. The sites can also store user preferences so
that site can look different for each visitor.
There are two types –
• Inmemory
• Persistant.
Cookie [] c = req.getCookie ();
Creating the cookie:
Cookie (String name, String value); res.addCookie ();
Writing with cookie:
getName () – returns the name of the cookie value.
getValue ()
setMaxAge ()
What is the difference between request parameters and request attributes?
Request parameters
Parameters are form data that are sent in the request from the HTML page. These
parameters are generally form fields in an HTML form like:
<input type=”text” name=”param1” /> <input type=”text” name=”param2” />
Form data can be attached to the end of the URL as shown below for GET requests
http://MyServer:8080/MyServlet?
param1=Peter¶m2=Smith or sent to the sever in the request body for
POST requests. Sensitive form data should be sent as a POST request.
You can get them but cannot set them.
request.getParameter("param1"); request.getParameterNames();
Request attributes
Once a servlet gets a request, it can add additional attributes,
then forward the request off to other servlets or JSPs for
processing. Servlets and JSPs can communicate with each
other by setting and getting attributes.
request.setAttribute(“calc-value”, new Float(7.0)); request.getAttribute(“calc-value”);
JAVA SERVER PAGES
❖ A Jsp is a text based document that describes how to process a request to create a
response
JSP ELEMENTS
❖ Scriptlet <% ......................... %>
❖ Directive <%@
❖ Declarative <%!
❖ Expression <%=
❖ Comment <%--
Declarations: Declarations are used to declare variables and methods to be used In JSP
page. Declarations have the following form.
<%! %>A declaration declares one or more variables or methods for use later in the JSP source
file. A declaration must contain at least one complete declarative statement. You can
declare any number of variables or methods within one declaration tag, as long as they
are separated by semicolons. The declaration must be valid in the scripting language used
in the JSP file.
<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>Anything declared inside declarations goes directly into the class body of generated
servlet class, outside of any method.
Declarations can not produce any output. Declarations are initialized when the JSP page
is initialized.
Mostly declarations are used to declare variables that will be available to all scriptlets in
the JSP page.
Examples of declarations
<%! int i; %>
<%! int i = 0; %><%! public String methodA(int a) {return "some string"
} %>
Comments in Jsp:
In a jsp we should always try to use jsp- style comments unless you want the comments
to appear in the HTML. Jsp comments are converted by the jsp engine into java
comments in the source code of the servlet that implements the Jsp page. The jsp
comment don't appear in the output produced by the jsp page when it runs. Jsp comments
do not increase the size of the file, jsp page are useful to increase the readability of the
jsp page.
In Jsp two types of comments are allowed in the Jsp page:
1) Hidden comment: This comment will not appear in the output.
<%-- Hidden comment --%>2) Output comment: This type of comment will appear in the output.
<!-- Output comment>
Example:
<html>
<HEAD>
<TITLE>Comments in a JSP</TITLE>
</HEAD>
<BODY>
<% // A Java comment inside a scriptlet - copied into the generated servlet %>The exemplar that generated this page uses a combination of HTML, Java and JSP
comments.
<%-- A JSP comment - not copied to the servlet, or the output --%>
</BODY>
</HTML>Scriptlets:
A scriptlet can contain any number of language statements, variable or method
declarations, or expressions that are valid in the page scripting language.Within scriptlet
tags, you can
1. Declare variables or methods to use later in the file (see also Declaration).
2. Write expressions valid in the page scripting language (see also Expression).
3. Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request.
If the scriptlet produces output, the output is stored in the out object, from which you can
display it.
Scriptlets has following syntax
<% %>Scriptlets can contain any Java code and are used to generate the output dynamically.
Everything inside the Scriptlets goes into the _jspService() method of generated servlet
class.
Hence scriptlets are executed at request processing time.
Scriptlets can be used to do iteration and conditional executions.
Scriptlets has access to all the variables and methods declared in declarations. Scriptlets
has access to all of the JSP implicit objects.
<%//This is a scriptlet
log("The lifecycle jsp has received a request"); counter++; %> In the example above, we have used a Scriptlet to increment the value of
counter variable.
It is important to remember that scriptlets will be executed each time the JSP
receives a request.
Scriptlet Examples:
Display welcome message if request attribute with name username is present
<% if(request.getAttribute("username") != null) {
%>
<div>Welcome <% out.write(request.getAttribute("username")); %></div>
<%} %>Display 1 to 5 using loop
<%
for(int i=1; i<6; i++) {%> <div><%= i %> </div> <%}%>Expressions
JSP expressions has following syntax
An expression tag contains a scripting language expression that is evaluated, converted to
a String, and inserted where the expression appears in the JSP file. Because the value of
an expression is converted to a String, you can use an expression within text in a JSP file.
Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>You cannot use a semicolon to end an expression
<%= %>An expression is evaluated, converted to string and then emitted to output each time a
request is received.
It is important to remember that the expressions must evaluate to string, or the expression
result must be able to be converted to string, otherwise an Exception would occur.
<p>This page has been called <%=counter %> times </p>In the example above, we have
used an expression to print the value of the
counter variable to the output. Expressions are evaluated at run time and hence has
access to all of the JSP implicit objects.
Expressions Examples:
Display value of username request attribute.
<div>Welcome <%= request.getAttribute("username") %></div>Display value of a
variable
<div><%= variablename %> </div>Display value of a session attribute <div><%= session.getAttribute("name") %></div>
Directive tag:
The directive tag gives special information about the page to JSP Engine.
This changes the way JSP Engine processes the page. Using directive tag, user can import
packages,
define error handling pages or session information of JSP page.
There are three types of directive tag.
page
Include
Tag Lib
Syntax and usage of directive tag
page directive:
General syntax for the page directive is
<%@ page optional attribute ... %>Example:
<%@ page language="java"import="java.util.List, java.util.Date"
session="true" buffer="24kb"
autoFlush="true"
info="JSP page directive tutorial"
errorPage="error.jsp"
isErrorPage="false"
isThreadSafe="true"
contentType="text/html"
pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>This is a JSP to test the page directive</h1>
</body>
</html>Include Directive:
General syntax for the include directive is
<%@ include optional attribute ... %>Example:
Includedirective.jsp:
<%@page language="java" session="false" %>
<html>
<head>
<title>The include directive tutorial </title>
</head>
<body bgcolor="wheat">
<div>
<%@include file="header.jsp"%>
<div style="padding:15% 33% 15% 33%; margin: 3px 03px 0; border:1px solid;">
<h2>This is main body </h2> </div> </div> </body> </html>
Header.jsp:
<%@include file="footer.jsp"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div style="width:100%; border:1px solid;">
<h2> This is Header </h2>
</div>
</body>
</html>Footer.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div style="width:100%; border:1px solid">
<h2> This is Footer </h2>
</div>
</body>
</html>Implicit Objects or Pre defined Objects
Certain objects those are available for the use in JSP documents without being declared
first. These objects are parsed by the JSP engine and inserted into the generated servlet.
The implicit objects re listed below
❖ Request
❖ Response
❖ Page Context
❖ Session
❖ Application
❖ Out
❖ Config
❖ Page
❖ Exception
1. request implicit object:
The JSP implicit request object is an instance of a java class that implements the
javax.servlet.http.HttpServletRequest interface.
It represents the request made by the client. The request implicit object is generally used
to get request parameters, request attributes,
header information and query string values.
Example:
Index.jsp:
<html>
<head>
<title>Form</title>
<style>
* { font-size: 12px; font-family: Verdana }
input { border: 1px solid #ccc }
</style>
</head>
<body bgcolor="wheat">
<center>
<form method="get" action="requestImplicitObject.jsp">
<p>Enter a book name
</p> <input type="text" name="bookname"><br> <input type="submit" value="submit"> </form> </center> </body> </html>
Requestimplicitobject.jsp:
<html>
<head>
<title>Book</title>
<style>
* { font-size: 12px; font-family: verdana }
</style>
</head>
<body>
<p>You have entered: <%= request.getParameter("bookname") %>
</p> </body> </html>
2. response implicit object:
The JSP implicit response object is an instance of a java class that implements the
javax.servlet.http.HttpServletResponse interface.
It represents the response to be given to the client. The response implicit object is
generally used to set the response content type,
add cookie and redirect the response.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Response implicit object</title>
</head>
<body>
<%
response.sendRedirect("index.jsp");
%>
</body>
</html>The index.jsp will be there in request implicit object example.
3. out implicit object:
The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class.
It represents the output content to be sent to the client. The out implicit object is used to
write the output content.
Example:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.List" %>
<%@page import="java.util.ArrayList" %>
<html>
<head>
<title>Implicit Out Object</title>
<style>
* { font-size: 12px; font-family: Verdana }
td { border: 1px solid #ccc; padding: 3px }
th { border: 1px solid #4B8699; padding: 3px;
background: #4B8699; color: white }
</style>
</head><body> <h2>Out Object</h2> <%! List students = new ArrayList(); %> <% if (students.isEmpty()) { students.add("Poojitha"); students.add("Thulasi"); students.add("Pavani"); students.add("Rakesh"); students.add("Mounica"); students.add("Reddy Rani"); students.add("Sree Veda"); students.add("Sailaja"); students.add("Vijaya Lakshmi"); students.add("Nagarani"); students.add("Sudhakar"); students.add("Mamatha"); } out.println("<table>"); out.println("<th>"); out.println(“SLC STAFF”); out.println(“Srikanth”); out.println(“ Loga “); out.println(“ Sivaganesh Reddy”); out.println("SLC STUDENTS "); out.println("</th>"); for (int i = 0; i < students.size(); i++) { out.println("<tr>"); out.println("<td>"); out.println(students.get(i)); out.println("</td>"); out.println("</tr>"); } out.println("</table>"); %>
</body> </html>
4. session implicit object
The JSP implicit session object is an instance of a java class that implements the
javax.servlet.http.HttpSession interface.
It represents a client specific conversation. The session implicit object is used to store
session state for a single user.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="wheat">
<%
session.setAttribute("city","KADAPA");
out.println(session.getAttribute("city"));
out.println("<br>");
out.println("Created Time of Session is: " + session.getCreationTime());
out.println("<br>");
out.println("Last Accessed Time of Session is: " + session.getLastAccessedTime());
out.println("<br>");
out.println("The Session ID is: " + session.getId());
out.println("<br>");
out.println("Maximum Inactive Interval of Session in Seconds is : "
+session.getMaxInactiveInterval());
%>
</body>
</html>5. application implicit object:
The JSP implicit application object is an instance of a java class that implements the
javax.servlet.ServletContext interface.
It gives facility for a JSP page to obtain and set information about the web application in
which it is running.
Example:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>application object</title>
<style>
* { font-size: 12px; font-family: Verdana }
</style>
</head>
<body>
<h2>application object</h2>
<p>Resource paths:
</p> <%= application.getResourcePaths("/") %> <br> <%= application.getResourcePaths("/WEB-INF") %><br> <%= application.getResourcePaths("/META-INF") %> <p>
Server:
</p> <%= application.getServerInfo() %> <p>
Context path:
</p> <%= application.getContextPath() %> </body> </html>
6. exception implicit object:
The JSP implicit exception object is an instance of the java.lang.Throwable class.
It is available in JSP error pages only. It represents the occured exception that caused the
control to pass to the JSP error page.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@page errorPage="errorPage.jsp" %>
<%
int i=10;/*Divide by zero, generates an error */
out.print(i/0); %> </body> </html>
errorPage.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ page isErrorPage='true' %>
<%
out.print("<h1> Here is the error message </h1>");
out.print(exception.getMessage());
%>
</body>
</html>7. config implicit object:
The JSP implicit config object is an instance of the java class that implements
javax.servlet.ServletConfig interface.
It gives facility for a JSP page to obtain the initialization parameters available.
Example:
Web.xml:
<web-app><init-param> <param-name>hello</param-name> <param-value>Srianjaneya</param-value> </init-param> </web-app>
Cofigimplicitobject.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="configImplicitObject" method="post">
<%= config.getInitParameter("hello")%>
</form>
</body>
</html>8. page implicit object:
The JSP implicit page object is an instance of the java.lang.Object class. It represents the
current JSP page.
That is, it serves as a reference to the java servlet object that implements the JSP page on
which it is accessed.
It is not advisable to use this page implict object often as it consumes large memory.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Object page = this;
<% this.log("log message"); %>
<% ((HttpServlet)page).log("anothermessage"); %></body> </html>
9. pageContext implicit object:
The JSP implicit pageContext object is an instance of the javax.servlet.jsp.PageContext
abstract class.
It provides useful context information. That is it provides methods to get and set
attributes in different scopes and for transfering requests to other resources.
Also it contains the reference to to implicit objects.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<b><font color="purple">
<%// Check if attribute has been set
Object o = pageContext.getAttribute("com.mycompany.name1",
PageContext.PAGE_SCOPE); if (o == null) { out.println("'com.mycompany.name1' is not 'null'"); }
// Save data
pageContext.setAttribute("com.mycompany.name0", "value0"); // PAGE_SCOPE is the
default
pageContext.setAttribute("com.mycompany.name1", "value1", PageContext.PAGE_SCOPE);
pageContext.setAttribute("com.mycompany.name2", "value2", PageContext.REQUEST_SCOPE); pageContext.setAttribute("com.mycompany.name3", "value3", PageContext.SESSION_SCOPE); pageContext.setAttribute("com.mycompany.name4", "value4", PageContext.APPLICATION_SCOPE); out.println("<br>"); out.println("<br>"); out.println("SHOWING VALUES OF ATTRIBUTE :-"); %> <br> <%-- Show the values --%> <%= pageContext.getAttribute("com.mycompany.name0") %> <%-- PAGE_SCOPE -- %> <br> <%= pageContext.getAttribute("com.mycompany.name1", PageContext.PAGE_SCOPE) %> <br> <%= pageContext.getAttribute("com.mycompany.name2",
PageContext.REQUEST_SCOPE) %>
<br> <%= pageContext.getAttribute("com.mycompany.name3",
PageContext.SESSION_SCOPE) %>
<br> <%= pageContext.getAttribute("com.mycompany.name4",
PageContext.APPLICATION_SCOPE) %>
</font></b>
</body> </html>
Explicit Objects: They are declared and created in JSP code. Typically explicit objects
are instance of java Beans.
Life-cycle methods in JSP
The generated servlet class for a JSP page implements the HttpJspPage interface of the
javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which
in turn extends the Servlet interface of the javax.servlet package. The generated servlet
class thus implements all the methods of the three interfaces.
The JspPage interface declares only two methods → jspInit () and jspDestroy () that
must be implemented by all JSP pages regardless of the client-server protocol. However
the JSP specification has provided the HttpJspPage interface specifically for the Jsp pages
serving HTTP requests. This interface declares one method _jspService ().
The jspInit () - The container calls the jspInit () to initialize the Servlet instance. It is
called before any other method, and is called only once for a servlet instance.
The _jspservice () - The container calls the _jspservice () for each request, passing it the
request and the response objects.
The jspDestroy () - The container calls this when it decides take the instance out of
service. It is the last method called in the servlet instance.
How do I prevent the output of my JSP or Servlet pages from being cached by the
browser?
❖ You will need to set the appropriate HTTP header attributes to prevent the dynamic
content output by the JSP page from being cached by the browser. Just execute the
following Scriptlet at the beginning of your JSP pages to prevent them from being
cached at the browser. You need both the statements to take care of some of the older
browser versions.
❖ <%
response.setHeader ("Cache-Control”,” no-store"); //HTTP 1.1response.setHeader ("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0);//prevents caching at the proxy server
%>
How does JSP handle run-time exceptions
You can use the error Page attribute of the page directive to have uncaught run-time
exceptions automatically forwarded to an error processing page. For example:
<%@ page error Page=\"error.jsp\" %> redirects the browser to the JSP page error.jsp ifan uncaught exception is encountered during request processing. Within error.jsp, if you
indicate that it is an error-processing page, via the directive: <%@ page
isErrorPage=\"true\" %> Throwable object describing the exception may be accessed
within the error page via the exception implicit object. Note: You must always use a
relative URL as the value for the error Page attribute
How can I implement a thread-safe JSP page
You can make your Jsp thread-safe by having them implement the
SingleThreadModel interface. This is done by adding the directive <%@ page
isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of
the servlet generated for your JSP page loaded in memory, you will have N instances of
the servlet loaded and initialized, with the service method of each instance effectively
synchronized. You can typically control the number of instances (N) that are instantiated
for all servlets implementing SingleThreadModel through the admin screen for your JSP
engine. More importantly, avoid using the tag for variables. If you do use this tag, then
you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that
page will access those variables, causing a nasty race condition. SingleThreadModel is
not recommended for normal use. There are many pitfalls, including the example above
of not being able to use <%! %>. You should try really hard to make them thread-safe the
old fashioned way: by making them thread-safe.