tags. The JSP page is first converted to a servlet by the JSP container before processing a client request. The document then explains the basic lifecycle of a JSP page, from translation to servlet code, compilation, initialization, request processing, and destruction. It also provides examples of simple JSP tags like scriptlets, expressions, comments, and directives."> tags. The JSP page is first converted to a servlet by the JSP container before processing a client request. The document then explains the basic lifecycle of a JSP page, from translation to servlet code, compilation, initialization, request processing, and destruction. It also provides examples of simple JSP tags like scriptlets, expressions, comments, and directives.">
Unit V
Unit V
Introduction to JSP
Que:
1. Define JSP page.
Ans:
JSP (Java Server Page) is server-side programming technology that is used to create
dynamic web page or web application.
This is mainly used for implementing presentation layer (GUI Part) of an application.
A complete JSP code is more like a HTML with bits of java code in it.
JSP can be an extension to Servlet because it provides more functionality than servlet.
Every JSP page first gets converted into servlet by JSP container before processing the
client’s request.
JSP have full access to Java technology- including threads and database connectivity.
Que:
1. How to call JSP from servlet? Explain with example.
Ans:
The following diagram shows how the web server creates the Webpage using JSP :
1
2. The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP Web Container. This is done by using the URL or JSP page which ends
with .jsp instead of .html.
3. The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements the
corresponding dynamic behavior of the page.
4. The JSP engine compiles the servlet and generate .class file and forwards the original
request to a servlet engine.
5. Then the servlet engine loads the Servlet class and executes it. During execution, the
servlet produces an output in HTML format. The output is further passed on to the web
server by the servlet engine inside an HTTP response.
6. The web server forwards the HTTP response to your browser in terms of static HTML
content.
7. Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet.
If the JSP is older than its generated servlet, the JSP container assumes that the JSP
hasn't changed and that the generated servlet still matches the JSP's contents. This
makes the process more efficient than with the other scripting languages (such as PHP)
and therefore faster.
Lifecycle of JSP
Que:
1. Explain the Life Cycle of JSP page, with methods.
2. What are JSP lifecycle methods?
3. Explain life cycle of JSP.
4. List two methods of JSP life cycle which can be overridden.
5. Explain life cycle of JSP page.
6. Explain methods of JSP life cycle.
7. Explain the architecture of JSP with neat diagram.
Ans:
A JSP life cycle is defined as the process from its creation till the destruction.
JSP Lifecycle is exactly same as the Servlet Lifecycle, with one additional first step,
which is, translation of JSP code to Servlet code.
JSP Lifecycle consists of following steps.
When a container loads a JSP it invokes the jspInit() method before servicing any
requests.
If we need to perform JSP-specific initialization, override the jspInit() method
public void jspInit(){
3
// Initialization code...
}
This method is called only once in JSP life Cycle.
We generally initialize database connections, open files, and create lookup tables in the
jspInit method.
The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request.
This method is also responsible for generating responses to all of the HTTP methods ie.
GET, POST, DELETE etc.
Que:
1. Write the Simple JSP program to print “hello”.
Ans:
To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension.
We have saved this file as index.jsp.Put it in a folder and paste the folder in the web-
apps directory in apache tomcat to run the JSP page.
index.jsp
<html>
4
<body>
<% out.print(“hello”); %>
</body>
</html>
Que:
1. Write Short note on JSP scripting elements.
2. List out types of JSP scripting elements.
Ans:
JSP Scripting element are written inside <% %> tags.
These code inside <% %> tags are processed by the JSP engine during translation of
the JSP page.
5
Any other text in the JSP page is considered as HTML code or plain text
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
There are five different types of scripting elements:
JSP Comment
JSP Comment is used to disable some statements of the JSP Page.
Syntax:
<%-- JSP comment --%>
When JSP compiler encounters the start tag <%-- of a JSP Comment, it ignores
everything from that point in the file until it finds the matching end tag --%>.
JSP comments are only seen in the JSP page. These comments are not included in
servlet source code during translation phase, nor they appear in the HTTP response.
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
6
<%
int count = 0;
%>
<body>
<%-- Code to show page count --%>
Page Count is <% out.println(++count); %>
</body
Scriptlet Tag
Que:
1. Explain <Scriptlet> tag, with syntax.
Ans:
Scriptlet Tag allows you to write java code inside JSP page.
Syntax:
<% java code %>
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
Declaration Tag
Que:
1. Explain JSP declaration tag with example.
Ans:
We can declare static member, instance variable and methods inside Declaration Tag.
Variable declare in declaration tag will be available to scriptlets,expressions and other
declaration.
Like scriplets, declarations contain Java language statements.
But Scriptlet code becomes part of the _jspService() method, while declaration code is
put outside the _jspService() method during translation of .jsp file into servlet.
Syntax:
7
<%! declaration %>
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%!
int count = 0;
%>
<body>
Page Count is: <% out.println(++count); %>
</body>
</html>
The above JSP page becomes this Servlet:
public class hello_jsp extends HttpServlet
{
int count=0;
public void _jspService(HttpServletRequest request, HttpServletResponse
response) throws IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");
Directive Tag
The jsp directives are the elements of a JSP source code that guide the web container
on how to translate the JSP page into it’s respective servlet.
8
Syntax:
<%@ directive attribute = "value" %>
Zero or more spaces,tabs and newline characters can appear after opening <%@ and
before the ending %>, and one or more whitespace characters can appear after the
directive name and between attributes/value pairs.
There are three types of directive tag:
Directive Description
%>
%>
You can place page directive anywhere in the JSP file, but it is good practice to make it
as the first statement of the JSP page.
Page Directive:
JSP page directive is used to define the properties applying the the JSP page, such as
the size of the allocated buffer, imported packages and classes/interfaces, defining what
type of page it is etc.
syntax:
<%@page attribute = "value"%>
Different properties/attributes :
The following are the different properties that can be defined using page directive :
import attribute
language attribute
extends attribute
session attribute
isThreadSafe attribute
isErrorPage attribute
errorPage attribute
contentType attribute
import attribute
The import attribute defines the set of classes and packages that must be inported in
servlet class definition.
Syntax:
<%@ page import="java.util.Date" %>
or
<%@ page import="java.util.Date,java.net.*" %>
9
Example
<html>
<body>
</body>
</html>
language attribute
It defines the scripting language to be used in the page.
The specified language will be used in scriptlets, expressions and declarations.
By default, this attribute contains the value ‘java’.
Syntax:
<%@ page language=’lang_name’ %>
extends attribute
It extends attribute defines the class name of the superclass of the servlet class that is
generated from the JSP page.
Syntax:
<%@ page extends=”package.class’ %>
session attribute
It defines whether the JSP page is participating in an HTTP session. The value is either
true or false.
If the value true,then the generated servlet will contain code that causes an HTTP
session to be created.
The default value is true.
Syntax:
<%@ Page session=”true|false” %>
isThreadSafe attribute
It declares whether the JSP can handle simultaneous requests from multiple threads or
not.
The value is either true or false
Syntax:
<%@page isThreadSafe=”true|false”%>
buffer:
It defines the size of the buffer that is allocated for handling the JSP page. The size is
defined in Kilo Bytes.
Syntax:
<%@page buffer = "size in kb"%>
10
errorPage attribute
It defines which page to redirect to, in case the current page encournters an exception.
Syntax:
<%@page errorPage = "URL"%>
Example:
Expression Tag
Que:
1. What is Expression in JSP? Give JSP example for it.
2. Explain JSP Expressions.
3. JSP Expressions.
4. Explain JSP expression tag.
Ans:
Expression Tag is used to print out java language expression that is put between the
tags.
An expression tag can hold any java language expression that can be used as an
argument to the out.print() method. Syntax of Expression Tag
Syntax:
<%= JavaExpression %>
Example:
<%= (2*5) %>
out.print((2*5));
Never end an expression with semicolon inside Expression Tag.
<%= (2*5); %>
Example of Expression Tag
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <%= ++count %>
</body>
<hml>
Implicit Objects in JSP
JSP provide access to some implicit object which represent some commonly used
objects for servlets that JSP page developers might need to use.
11
For example you can retrieve HTML form parameter data by using request variable,
which represent the HttpServletRequest object.
response The HttpServletRequest object associated with the response that is sent back to the
browser.
Out The JspWriter object associated with the output stream of the response.
Session The HttpSession object associated with the session for the given user of request.
Config The ServletConfig object associated with the servlet for current JSP page.
pageContext The PageContext object that encapsulates the enviroment of a single request for this
current JSP page
Page The page variable is equivalent to this variable of Java programming language.
exception The exception object represents the Throwable object that was thrown by some other
JSP page.
Que:
1. How to Access Database using JSP explain with example.
Ans:
Create a JSP page and write JDBC code to make database connection in the JSP page.
To retrieve the data from database table, write a SQL query "SELECT * from
tableName" and execute this query using executeQuery(sql) method of Statement
interface and store the result into ResultSet.
To insert,update and delete data from database, write a SQL query and execute this
query using executeUpdate(sql) method of Statement interface.
12
The JSP file for retrieving data from database is:
retrieve.jsp
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
String id = request.getParameter("userid");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "test";
String userid = "root";
String password = "";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!DOCTYPE html>
<html>
<body>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from users";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("first_name") %></td>
<td><%=resultSet.getString("last_name") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
</tr>
<%
13
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
Insert Data into Database Using JSP
index.html
<!DOCTYPE html>
<html>
<body>
<form method="post" action="process.jsp">
</form>
</body>
</html>
process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
try
{
14
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
"");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into users(first_name,last_name,city_name,email)
values('"+first_name+"','"+last_name+"','"+city_name+"','"+email+"')");
out.println("Data is successfully inserted!");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>
Que:
1. Difference between JSP and Servlet.
2. Give difference between servlet & JSP.
Ans:
JSP SERVLET
JSP can be compiled into servlet when accessed
Servlet is java programme that are
alreadycompiled
It’s easier to code in JSP than in java Coding is difficult compared to JSP
JSP are not preferred when there is much preferred when there is much processing of
processing of data required data required
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.
15
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.
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.
5) platform independent
JSP is built on Java technology, so it is platform Independent.
16