What Is JSP?

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

JSP

What is JSP?

Java Server Pages (JSP) is a server-side programming technology that enables


the creation of dynamic, platform-independent methods for building Web-based
applications. JSP has access to the entire family of Java APIs, including the
JDBC API to access enterprise databases.

JavaServer Pages (JSP) is a technology for developing Web Pages that supports
dynamic content. This helps developers insert java code in HTML pages by
making use of special JSP tags, most of which start with <% and end with %>
JavaServer Pages component is a type of Java servlet that is designed to fulfill
the role of a user interface for a Java web application.Using JSP, you can collect
input from users through Web Page forms, present records from a database or
another source, and create Web Pages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information
from a database or registering user preferences, accessing JavaBeans
components, passing control between pages, and sharing information between
requests, pages etc.,

JSP - Architecture

The web server needs a JSP engine, i.e, a container to process JSP pages.
The JSP container is responsible for intercepting requests for JSP pages. This
tutorial makes use of Apache which has a built-in JSP container to support
JSP pages development.

A JSP container works with the Web server to provide the runtime
environment and other services a JSP needs. It knows how to understand
the special elements that are part of JSPs.

Following diagram shows the position of JSP containers and JSP files in a
Web application.
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

● As with a normal page, your browser sends an HTTP request to


the web server.
● The web server recognizes that the HTTP request is for a JSP
page and forwards it to a JSP engine. This is done by using the
URL or JSP page which ends with .jsp instead of .html.
● 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.
● The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.
● A part of the web server called 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.
● The web server forwards the HTTP response to your browser in
terms of static HTML content.
● Finally, the web browser handles the dynamically-generated
HTML page inside the HTTP response exactly as if it were a static
page.

All the above mentioned steps can be seen in the following diagram −

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.

So in a way, a JSP page is really just another way to write a servlet without
having to be a Java programming wiz. Except for the translation phase, a
JSP page is handled exactly like a regular servlet.
JSP - Lifecycle
A JSP life cycle is defined as the process from its creation till the destruction.
This is similar to a servlet life cycle with an additional step which is required
to compile a JSP into servlet.

Paths Followed By JSP


The following are the paths followed by a JSP −

● Compilation
● Initialization
● Execution
● Cleanup

The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The

four phases have been described below −


JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it
needs to compile the page. If the page has never been compiled, or if the
JSP has been modified since it was last compiled, the JSP engine compiles
the page.

The compilation process involves three steps −

● Parsing the JSP.


● Turning the JSP into a servlet.
● Compiling the servlet.

JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any

requests. If you need to perform JSP-specific initialization, override the jspInit() method

public void jspInit(){


// Initialization code...
}
Typically, initialization is performed only once and as with the servlet init
method, you generally initialize database connections, open files, and create
lookup tables in the jspInit method.

JSP Execution
This phase of the JSP life cycle represents all interactions with requests until
the JSP is destroyed.

Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as

its parameters as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {


// Service handling code...
}
The _jspService() method of a JSP is invoked on request basis. This is
responsible for generating the response for that request and this method is
also responsible for generating responses to all seven of the HTTP methods,
i.e, GET, POST, DELETE, etc.
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being
removed from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. Override jspDestroy when you need to perform any cleanup, such
as releasing database connections or closing open files.

The jspDestroy() method has the following form −

public void jspDestroy() {


// Your cleanup code goes here.
}

JSP - Syntax
basic use of simple syntax (i.e, elements) involved with JSP development.

Elements of JSP
The elements of JSP have been described below −

The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting
language.

Following is the syntax of Scriptlet −

<% code fragment %>

You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet>
code fragment
</jsp:scriptlet>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following

is the simple and first example for JSP −

<html>
<head><title>Hello World</title></head>

<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

NOTE − Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your

environment is setup as per environment setup tutorial.

Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-

tomcat7.0.2\webapps\ROOT directory. Browse through the same using URL

http://localhost:8080/hello.jsp. The above code will generate the following result −

JSP Declarations
A declaration declares one or more variables or methods that you can use in
Java code later in the JSP file. You must declare the variable or method
before you use it in the JSP file.

Following is the syntax for JSP Declarations −

<%! declaration; [ declaration; ]+ ... %>

You can write the XML equivalent of the above syntax as follows −

<jsp:declaration>
code fragment
</jsp:declaration>

Following is an example for JSP Declarations −

<%! int i = 0; %>


<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

JSP Expression
A JSP expression element 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 a line of text, whether or not it is tagged with HTML, in a
JSP file.

The expression element can contain any expression that is valid according to
the Java Language Specification but you cannot use a semicolon to end an
expression.
Following is the syntax of JSP Expression −

<%= expression %>

You can write the XML equivalent of the above syntax as follows −

<jsp:expression>
expression
</jsp:expression>

Following example shows a JSP Expression −

<html>
<head><title>A Comment Test</title></head>

<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>

The above code will generate the following result −

Today's date: 11-Sep-2010 21:24:25


JSP examples programs

Programs1:hello.jsp

<html>
<head>
<title>JSP Test Page</title>
</head>
<body>
<%
out.println("<h1>Hello World.</h1>");
out.println("<h1>This is my first JSP Program.</h1>");
%>
</body>
</html>

Program2:comment.jsp

<html>
<head>
<title>JSP Test Page</title>
</head>
<body>
<%
// This is single line comment
/*
This is multi-line comment line -1
This is multi-line comment line -2
*/
out.println("<h1>This is my first JSP Program.</h1>");
%>
</body>
</html>

Program3:print 30

<html>
<head>
<title>JSP Test Page</title>
</head>
<body>
<%@ page session = "true" %>
<%
int i = 10;
int j = 20;
int sum = i + j;
out.println("Sum of i and j will be: "+sum);
%>
</body>

</html>

Program4: In this example, we will see, how we can print a message on the browser screen

without using the out object.

<html>

<head>

<title>JSP Test Expression Page</title>

</head>

<body>

<%= "welcome to this jsp " %>

</body>expression tag

</html>

Program5:Sum of I and J valves

<html>

<head>

<title>JSP Test Initialization Page</title>

</head>

<body>

<%! int i=50; int j=50; int sum=0; %>


<%= "Sum of i and j variables will be:"+(sum = i+j) %>

</body>

</html>

Program6: Write a simple JSP program to print the current date and time

test.jsp

<html>

<head><title>JSPApp</title></head>

<body>

<form>

<fieldset style="width:20%; background-color: #ccffeb;">

<legend><b><i>JSP Application<i><b></legend>

<h3>Current Date and Time is :</h3>

<% java.util.Date d = new java.util.Date();

out.println(d.toString()); %>

</fieldset>

</form>

</body>

</html>
web.xml

<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/test.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Program7: Write a JSP program to upload the file into the server.

index.html

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<form action="upload.jsp" method="post" enctype="multipart/form-data">
<fieldset style="width:20%; background-color: #e6ff99">
<h2>File Upload Example</h2>
<hr>
Select a file to upload: <br /><br />
<input type="file" name="file" size="50" />
<br /><br />
<input type="submit" value="Upload File" />
</fieldset>
</form>
</body>
</html>
upload.jsp
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>

<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");

// Verify the content type


String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0))
{
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\temp"));

// Create a new file upload handler


ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try
{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);

// Process the uploaded file items


Iterator i = fileItems.iterator();

out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 )
{
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}
else
{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
else
{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>

web.xml

<web-app>
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
D:\TOMCAT_HOME_6\apache-tomcat-6.0.48\webapps\data\
</param-value>
</context-param>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/index.html</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Program8: Write a JSP application to count the total number of visits on your website.

count-visitor.jsp

<%@ page import="java.io.*,java.util.*" %>


<html>
<head>
<title>Count visitor</title>
</head>
<body>
<form>
<fieldset style="width:20%; background-color:#e6ffe6;">
<legend>Count visitor</legend>
<%
Integer hitsCount =
(Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 )
{
/* First visit */
out.println("Welcome to my website!!");
hitsCount = 1;
}
else
{
/* return visit */
out.println("Welcome to my website!!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<p>You are visitor number: <%= hitsCount%></p>
</fieldset>
</form>
</body>
</html>

web.xml

<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/count-visitor.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Program9: Write a JSP application to demonstrate the session tracking.

SessionDemo.jsp

<%@ page import="java.io.*,java.util.*" %>


<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("Surendra");

// Check if this is new comer on your web page.


if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking Example</h1>
</center>
<table border="1" align="center">
<tr bgcolor="#ffcccc">
<th>Session info</th>
<th>Value</th>
</tr>
<tr >
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>

web.xml

<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/SessionDemo.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Program10: Explain error handling in JSP with example.
index.html

<html>
<head>
<title>Exception Example</title>
</head>
<body>
<form action="process.jsp">
<fieldset style="width:20%; background-color:#e6ffe6;">
<center>
<h3>Exception Example</h3>
Enter number: <input type="text" name="n1" /><br/><br/>
Enter number: <input type="text" name="n2" /><br/><br/>
<input type="submit" value="Divide"/>
</center>
</fieldset>
</form>
</body>
</html>

process.jsp

<%@ page errorPage="error.jsp" %>


<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");

int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("Division of numbers is: "+c);
%>

error.jsp
<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>

web.xml

<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

JSP Programing Examples


Program11:
test.jsp
<html>
<head>
<title>useBean,setProperty and getProperty action example</title>
</head>
<body>
<h4>Enter student detail.</h4>
<form action="display.jsp" method="post">
Name: <input type="text" name="name"><br/><br/>
RollNo: <input type="text" name="rollNo"><br/><br/>
<input type="submit" value="Sign up">
</form>
</body>
</html>
StudentBean.java
/**
* This class acts as a java bean for a student.
* @author w3spoint
*/
publicclass StudentBean {
//student properties
privateString name;
privateString rollNo;

//no-argument constructor
public StudentBean(){

publicString getName(){
return name;
}

publicvoid setName(String name){


this.name= name;
}

publicString getRollNo(){
return rollNo;
}

publicvoid setRollNo(String rollNo){


this.rollNo= rollNo;
}
}
display.jsp
<html>
<head>
<title>useBean,setProperty and getProperty action example</title>
</head>
<body>
<h4>Student detail:</h4>
<jsp:useBean id="student"
class="com.w3spoint.business.StudentBean"/>
<jsp:setProperty name="student" property="*"/>
Name:<jsp:getProperty name="student" property="name"/><br>
RollNo:<jsp:getProperty name="student" property="rollNo"/><br>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>test.jsp</welcome-file>
</welcome-file-list>

</web-app>
Program12:
welcome.jsp
<%@ page autoFlush="true"%>

<html>
<head>
<title>autoFlush page directive example</title>
</head>
<body>
<h3>Hello this is a autoFlush page directive example.</h3>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>

</web-app>
Program13:
test.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
<title>c:catch JSTL core tag example</title>
</head>
<body>
<c:catch var ="exception">
<%int x =10/0;%>
</c:catch>

<c:if test ="${exception != null}">


Occurred exception is : ${exception}
</c:if>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>test.jsp</welcome-file>
</welcome-file-list>

</web-app>
Program14:
welcome.jsp
<html>
<head>
<title>Exception handling example</title>
</head>
<body>
<%
out.print(10/0);
%>
</body>
</html>
errorPage.jsp
<%@ page isErrorPage="true"%>

<html>
<head>
<title>error page</title>
</head>
<body>
Occurred exception is:<%= exception %>
</body>
</html>
web.xml
<web-app>

<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>

<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
Program15:

welcome.jsp
<html>
<head>
<title>Declaration tag example</title>
</head>
<body>
<%!
int sum(int a, int b){
return a + b;
}
%>

<%
out.println("Sum of 10 and 20 = "+ sum(10, 20));
%>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>

</web-app>
Program16:

login.jsp
<html>
<head>
<title>login</title>
</head>
<body>
<form action="welcome.jsp">
<input type="text" name="userName"/>
<input type="submit" value="login"/>
</form>
</body>
</html>
welcome.jsp
<html>
<head>
<title>pageContext implicit object example</title>
</head>
<body>
<%
String userName = request.getParameter("userName");
if(userName.equals("jai")){
pageContext.setAttribute("userName",
userName, PageContext.SESSION_SCOPE);
response.sendRedirect("home.jsp");
}else{
out.print("Wrong username.");
}
%>
</body>
</html>
home.jsp
<html>
<head>
<title>home</title>
</head>
<body>
<h3>This is user home page.</h3>
<%
String userName =(String)pageContext.getAttribute("userName",
PageContext.SESSION_SCOPE);
out.print("Logged in user: "+ userName);
%>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

</web-app>

Program17:
login.jsp
<html>
<head>
<title>login</title>
</head>
<body>
<form action="welcome.jsp">
<input type="text" name="userName"/>
<input type="submit" value="login"/>
</form>
</body>
</html>
welcome.jsp
<html>
<head>
<title>request implicit object example</title>
</head>
<body>
<%
String userName=request.getParameter("userName");
if(userName.equals("jai")){
out.print("Welcome "+ userName +",
You are successfully logged in.");
}else{
out.print("Wrong username.");
}
%>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

</web-app>
Program18:

test.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<html>
<head>
<title>fmt:timeZone JSTL formatting tag example</title>
</head>
<body>
<c:set var="currentDate" value="<%=new java.util.Date()%>"/>
<table>
<c:forEach var="timeZone"
items="<%=java.util.TimeZone.getAvailableIDs()%>">
<tr>
<td>
<c:out value="${timeZone}"/>
</td>
<td>
<fmt:timeZone value="${timeZone}">
<fmt:formatDate
value="${currentDate}" type="both"/>
</fmt:timeZone>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>test.jsp</welcome-file>
</welcome-file-list>

</web-app>
Program19:

test.jsp
<html>
<head>
<title>expression language example</title>
</head>
<body>
<h3>This is an expression language example.</h3>
20 is greater than 30: ${20>30}<br/>
Sum of 20 and 30: ${20+30}
</body>
</html>
web.xml
<web-app>
<welcome-file-list>
<welcome-file>test.jsp</welcome-file>
</welcome-file-list>

</web-app>
Program20:

welcome.jsp
<html>
<head>
<title>include action example</title>
</head>
<body>
<h3>Hello this is a include action example.</h3>
<jsp:include page="home.jsp"/>
</body>
</html>
home.jsp
<html>
<head>
<title>include action example</title>
</head>
<body>
<h4>This content is of included file.</h4>
</body>
</html>
web.xml
<web-app>

<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>

</web-app>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy