What Is JSP?
What Is JSP?
What Is JSP?
What is JSP?
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 −
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.
● Compilation
● Initialization
● Execution
● Cleanup
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The
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
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 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.
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.
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
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-
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.
You can write the XML equivalent of the above syntax as follows −
<jsp:declaration>
code fragment
</jsp:declaration>
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.
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 −
You can write the XML equivalent of the above syntax as follows −
<jsp:expression>
expression
</jsp:expression>
<html>
<head><title>A Comment Test</title></head>
<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>
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
<html>
<head>
</head>
<body>
</body>expression tag
</html>
<html>
<head>
</head>
<body>
</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>
<legend><b><i>JSP Application<i><b></legend>
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");
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
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
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
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" %>
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>
//no-argument constructor
public StudentBean(){
publicString getName(){
return name;
}
publicString getRollNo(){
return rollNo;
}
<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>
<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>