Chapter 3 Java Server Page (JSP)
Chapter 3 Java Server Page (JSP)
Chapter 3 Java Server Page (JSP)
A Java Server Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML elements, and embedded JSP actions and commands.
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, passing control between pages and sharing information
between requests, pages etc.
Following diagram shows the position of JSP container and JSP files in a Web Application.
The following steps explain how the web server creates the web page 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 that 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, which the servlet
engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static HTML
content.
• Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
That is to say, anything that can be done using JSPs can also be accomplished using Java
servlets. However, it is important to note that servlets and JSPs are complementary technologies,
NOT replacement of each other. Servlet can be viewed as "HTML inside Java", which is better
for implementing business logic - as it is Java dominant. JSP, on the other hand, is "Java inside
HTML", which is superior for creating presentation - as it is HTML dominant.
JSPs, like servlets, are server-side programs run inside a HTTP server. To support JSP/servlet, a
Java-capable HTTP server is required and we will use Apache Tomcat Server to run JSP files.
To simplify the access of the HTTP request and response messages, JSP has the following pre-
defined variables:
JSP comments <%-- comments --%> are ignored by the JSP engine. For example,
<%-- anything between opening and closing tag here will be ignored --%>
JSP Expression can be used to insert a single Java expression directly into the response
message. This expression will be placed inside out.print() method. Hence, the expression will
be evaluated and printed out as part of the response message. Any valid Java expression can be
used. There is no semi-colon at the end of the expression. For examples:
JSP scriptlets allow you to do more complex operations than inserting a single Java expression
(with the JSP expression). JSP scriptlets let you insert an arbitrary sequence of valid Java
statement(s) into the service() method of the converted servlet. All the Java statements in a
scriptlet are to be terminated with a semi-colon. For example:
<%
int x=9,y=4,sum=0;
sum=x+y;
out.print(“The sum of ”+x+ “ and ”+y+ “ is ” +sum);
%>
Notice that the Java codes inside a scriptlet are inserted exactly as they are written, and used as
the programming logic. The HTML codes are passed to an out.write() method and written out
as part of the response message.
The "page" directive lets you import classes and customize the page properties. For examples,
<%-- import package java.sql.* is similar to the next page directive code -->
<%@ page import="java.sql.*" %>
The "include" directive lets you include other file(s) at the time when the JSP page is compiled
into a servlet. You can include any JSP files, or static HTML files. You can use include
directive to include navigation bar, copyright statement, logo, etc. on every JSP pages. The
syntax is:
For example:
<%-- all content that we need to display in a web page should done here --%>
<%@include file="footer.jsp"%>
</body>
</html>
We will include header.jsp in the next examples in multiple pages to see the effect in each page
• Home.jsp
• Validateuser.jsp
• Admin_home.jsp
• Registrar_officer_home.jsp
• Register_student_profile.jsp
• Update_student_profile.jsp
• View_student_profile.jsp
• Department_head_home.jsp
• Logout.jsp
• Contactus.jsp
• Notice.jsp
Create your first jsp file called Home.jsp which contains login form under the project
Student_Profile_Registration_System_JSP. Right click on the project— point to New—select
JSP file—Give class name (Home)—Click Finish. The jsp engine generates basic html tags for
you which looks like the code shown below.
</body>
</html>
Then add html code to create login form inside body tag similar to Home.java of your servlet
class and the code is shown below
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body bgcolor=#66CCFF>
<%@include file="header.jsp"%>
<center><table width=800>
<tr><th colspan=3><h1 style=color:#cc6600> Welcome to Student Profile Registration
System</h1></th></tr>
<tr><td colspan=3 align=right>
<a href= "Contactus.jsp" style=color:white;font-size:26><input type=submit value= "Contact
Us" style=color:white;font-size:20;background-color:#cc6600></a>
<a href="Notice.jsp" style=color:white;font-size:26><input type=submit value="Notice"
style=color:white;font-size:20;background-color:#cc6600></a>
</td></tr>
<tr><td colspan=3 align=left><h2>Login</h2></td></tr>
<tr><td><form action=Validateuser.jsp method=post>
User Name:<input type=text name=username required /></td> <td></td><td></td></tr>
<tr><td>Password:<input type=password name=password required/></td>
<td></td><td></td></tr>
<tr><td><input type=submit name=submit value=Login />
<input type=Reset value=Reset /></td> <td></td><td></td></tr></form>
</table></center> </body></html>
</tr>
</table>
</body>
</html>
When you run the above file Home.jsp on server you will get the following web page
The file Validateuser.jsp is used to validate whether the user attempt to login into the system has
privilege or not and if the user is valid then the code will redirect the user to the appropriate page
like Admin_home.jsp , Registrar_officer_home.jsp or Department_head_home.jsp using
response.sendRedirect() method.
<% response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Validate user</title>
</head>
<body>
<%
try{
String username=null,password=null,submit=null;
username=request.getParameter("username");
password=request.getParameter("password");
submit=request.getParameter("submit");
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.print(e.getMessage());
}
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
stmt=conn.createStatement();
}else{ rs=stmt.executeQuery(sql);
rs.next();
String utype=rs.getString("User_Type");
String uname=rs.getString("User_Name");
//set in session variable
session.setAttribute("utype",utype);
session.setAttribute("uname",uname);
if(utype.equals("Registrar Officer"))
{
response.sendRedirect("Registrar_officer_home.jsp"); //redirect to Registrar Officer Home page
}else if (utype.equals("Department Head"))
{
response.sendRedirect("Department_head_home.jsp"); //redirect to Department head home page
}
}else if (utype.equals("Admin"))
{
response.sendRedirect("Admin_home.jsp"); //redirect to Admin home page
}
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
}
String user_name=null,user_type=null;
if(session!=null) {
user_name=(String)session.getAttribute("uname");
user_type=(String)session.getAttribute("utype");
}
%>
<center>
<table><tr>
<td><a href="Register_student_profile.jsp" style=color:white;font-size:26><input
type=submit value="Register Student Profile" style=color:white;font-size:20;background-
color:#cc6600></a></td>
<td><a href="Update_student_profile.jsp" style=color:white;font-size:26><input
type=submit value="Update Student Profile" style=color:white;font-size:20;background-
color:#cc6600></a></td>
<td><a href="View_student_profile.jsp" style=color:white;font-size:26><input
type=submit value="View Student Profile" style=color:white;font-size:20;background-
color:#cc6600></a></td>
</tr>
</table>
</center>
</body>
</html>
When you run Home.jsp on the server and login as Registrar Officer user type you will get the
following web page
<% response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
if (session.getAttribute("uname")==null||session.getAttribute("utype")==null)
{
response.sendRedirect("Home.jsp");
return;
}
%>
String driverName="com.mysql.cj.jdbc.Driver";
String dbUrl="jdbc:mysql://localhost:3306/student profile registration db";
String dbusername="root";
String dbpassword="root";
Connection conn=null;
PreparedStatement ps=null;
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.print(e.getMessage());
}
ps = conn.prepareStatement(sql);
ps.setString(1,sid);
ps.setString(2,fname);
ps.setString(3,sname);
ps.setString(4,dobirth);
ps.setInt(5,ey);
int i = ps.executeUpdate();
if(i>0) {
%>
<font color=green>The following record has been inserted into student_profile table</font>
When you click Register Student Profile link in Registrar_officer_home.jsp web page you will
get the following jsp form and works similar to Register_student_profile.java servlet class that
you have discussed in chapter 2.
Data Update:
<%--Update_student_profile.jsp --%>
<% response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
if (session.getAttribute("uname")==null||session.getAttribute("utype")==null)
{
response.sendRedirect("Home.jsp");
return;
}
%>
Connection conn=null;
Statement stmt=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.print(e.getMessage());
}
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
stmt=conn.createStatement();
if(!rs.next())
{ %>
<font color=red>There is no student profile registered with id <%=studid%></font>
<%
}else{
rs=stmt.executeQuery(sql);
rs.next();
%>
<form action= "Update_student_profile.jsp" method=post >
Student ID: <input type=text name=studid value=<%=rs.getString(1)%> size=20 readonly
/><br>
First Name: <input type=text name=firstname value=<%=rs.getString(2)%> size=30 required
/><br>
Second Name: <input type=text name=secondname value=<%=rs.getString(3)%> size=30
required /><br>
Date of Birth: <input type=date name=dob value=<%=rs.getString(4)%> required /><br>
Entry Year: <input type=number name=entryyear value=<%=rs.getInt(5)%> required /><br>
<input type=submit name=update value=Update /><input type=reset value=clear>
</form>
<%
}
}else if(search==null&&update!=null)
{
int e_year=Integer.parseInt(eyear);
String updatesql="update student_profile Set First_Name=? ,Second_Name=?,
Date_Of_Birth=?,Entry_Year=? where Student_Id=?";
ps=conn.prepareStatement(updatesql);
ps.setString(1, fname);
ps.setString(2, sname);
ps.setString(3, dob);
ps.setInt(4, e_year);
ps.setString(5, studid);
int updated=ps.executeUpdate();
if(updated>0)
{
%>
<font color=green>Updated successfully</font>
Login as Registrar Officer and Click Update Student Profile link, The code used to update specific
student record based on Student Id and it works like Update_student_profile.java servlet class
that we have discussed in chapter 2.
<% response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
if (session.getAttribute("uname")==null||session.getAttribute("utype")==null)
{
response.sendRedirect("Home.jsp");
return;
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> View Student Profile</title>
</head>
<body bgcolor=#66CCFF>
<%@include file="header.jsp"%>
<h1> Student Profile View Form </h1>
<%
String studid=request.getParameter("studid");
String studfirstname=request.getParameter("studfirstname");
%>
<form action= "View_student_profile.jsp" method=POST>
Search By: <br>
Id:<input type=text name=studid /> First Name: <input type=text name=studfirstname /> <br>
<input type=submit name=search value=Search /><input type=Reset value=Reset />
</form>
<%
String driverName="com.mysql.cj.jdbc.Driver";
String dbUrl="jdbc:mysql://localhost:3306/student profile registration db";
String dbusername="root";
String dbpassword="root";
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
%>
</body>
</html>
When you run Home.jsp and login as Registrar Officer and click View Student Profile you will get
the following web page
Once we upload the file in this directory, we should insert the file path Uploaded_Files/ File
name to database. File name is the name of the file uploaded and Uploaded_Files is the last
folder of the directory created under webapp of your project.
Note: If you use more than one word for your file name avoid space, instead use underscore
between two words.
Let us insert the file path to student_document table (document_Id(pk,auto, Student_Id(Foreign
Key), Document_Description, Document_Path). We should create relationship between
student_profile and student_document using Student_Id field of student_document table as
Foreign key
Let us create Register_student_document.jsp file under the project and write the code used to
upload file
<%-- Register_student_document.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<% response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Upload Student Document</title></head>
<body bgcolor=#66CCFF>
<%@include file="header.jsp"%>
<h1 style=color:#cc6600>Student Document Upload Page</h1>
<%
String submit = request.getParameter("submit");
try {
String filelocationpath="E:/Advanced_Programming_JSP_Example/Student Profile Registration
System/Student_Profile_Registration_System_JSP/src/main/webapp/Uploaded_Files";
%>
String studid=null,doc_description=null;
if(submit!=null)
{
String filelocationpath_for_database=null,filename=null;
String filetype=null,uploadedfile_folderpath=null;
File folderpath=null,saved_file_path=null;
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
}catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
FileItem item=null;
while(itr.hasNext())
{ item =(FileItem) itr.next();
if(item.isFormField())
{ String name=item.getFieldName();
String value=item.getString();
if(name.equals("stud_id")) {
studid=value;
}
if(name.equals("doc_description")) {
doc_description=value;
}
}else{
String name=item.getFieldName();
if(name.equals("Upload_file"))
filename=item.getName();
filetype=item.getContentType();
uploadedfile_folderpath=folderpath+"/"+filename;
saved_file_path=new File(uploadedfile_folderpath);
filelocationpath_for_database="Uploaded_Files"+"/"+filename;
if(saved_file_path.exists()) // If already created before
savedfileexist=true;
if(savedfileexist==true||!(filetype.equals("application/pdf")||filetype.equals("image/jpeg")))
{
if(savedfileexist==true)
out.print("File name of document you attempt to upload is already exist, please change document
file name and try again");
else if(!(filetype.equals("application/pdf")||filetype.equals("image/jpeg")))
out.print("File type must be in pdf or image format,Try Again <br>");
out.print("<font color=red>File Not Uploaded</font>");
}else {
item.write(saved_file_path);
String driverName="com.mysql.cj.jdbc.Driver";
String dbUrl="jdbc:mysql://localhost:3306/student profile registration db";
String dbusername="root";
String dbpassword="root";
Connection conn=null;
PreparedStatement ps=null;
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.println(e.getMessage());
}
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
String sql="insert into student_document (Student_Id,Document_Description, Document_Path)
VALUES (?,?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1,studid);
ps.setString(2,doc_description);
ps.setString(3,filelocationpath_for_database);
int i = ps.executeUpdate();
if(i>0) {
</form>
<% }
}
}
}
}
}
}catch(Exception e)
{
out.println(e.getMessage());
}%>
</body>
</html>
When you run the above file, you will get the following web page
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.print(e.getMessage());
}
<%if(docdesc.equals("Photo")) { %>
<td> <img src=<%=rs.getString("Document_Path")%> width=50 height=50 /></td>