Chapter 3 Java Server Page (JSP)

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

Chapter 3: Java Server Pages (JSP)

What is Java Server Pages?


Java Server Pages (JSP) is a technology for developing web pages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags,
most of which start with <% and end with %>.

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.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 1


JSP Processing

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.

JSPs are Internally Compiled into Java Servlets

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.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 2


JSP Scripting Elements

JSP provides the following scripting elements:

• JSP Comment <%-- comments --%>


• JSP Expression <%= Java Expression %>
• JSP Scriptlet<% Java Statement(s) %>
• JSP Directive <%@ page|include ... %>

To simplify the access of the HTTP request and response messages, JSP has the following pre-
defined variables:

• request: corresponds to the HTTP request message.


• response: corresponds to the HTTP response message.
• out: corresponds to the HTTP response message’s output stream.
• session: object used to call methods to set and get session variables

JSP comment : <%- - comments - -%>

JSP comments <%-- comments --%> are ignored by the JSP engine. For example,

<%-- anything between opening and closing tag here will be ignored --%>

JSP Expression: <%= Java Expression %>

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:

<p>The square root of 5 is <%= Math.sqrt(5) %></p>

<p>Current time is: <%= new java.util.Date() %></p>

The above JSP expressions will be converted to:

out.write("<p>The square root of 5 is ");


out.print(Math.sqrt(5) );
out.write("</p>");
out.write("<p>Current time is: ");
out.print( new java.util.Date() );
out.write("</p>");

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 3


JSP Scriptlet<% Java statement(s) %>

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.

JSP page Directive

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.*" %>

<%-- Set the output MIME type --%>


<%@ page contentType="image/gif" %>

<%-- Set an information message for getServletInfo() method --%>


<%@ page info="Hello-world example" %>

JSP include Directive

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:

<%@ include file="url" %>

For example:

<%@ include file="header.html" %>


......
<%@ include file="footer.html" %>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 4


In web-based development we may have multiple web pages and all pages should have the same
logo, header, footer, copyright messages and other. The following example shows you how to
include css_setting.jsp, header.jsp and footer.jsp files in a given jsp page.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@include file=" css_setting.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@include file="header.jsp"%>

<%-- 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

JSP Database connection, session management and page Redirection


To connect JSP application to data source use JDBC techniques. So, we should use the JDBC
package java.sql.* to manipulate database in JSP. The package java.sql. * in JSP should be
imported before <!DOCTYPE html> tag and the syntax is given below
<%@page import=”java.sql.*” %>
The ability to share values between JSP pages at application level using session management can
greatly enhance your JSP application and to design more interactive web-based system, we
should interconnect web pages using hyperlink. A web-based system may have more than one
user and page redirection based on a certain condition is mandatory.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 5


In the following example we will see database connection, session management, hyperlink and
page redirection in JSP. In the examples we will implement what we have done in Servlet topic
using JSP So, we will use the same database (student profile registration db) and tables
student_profile and user.

First create Dynamic Web Project called Student_Profile_Registration_System_JSP


File—New— Dynamic Web Project —Give Project Name—Select Apache Tomcat Server 9.0—
select jdk 20 and Click Finish. Then we will create and implement the following jsp files step by
step

• 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.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 6


<%@ page language="java" contentType="text/html;
charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

</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>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 7


header.jsp file has the following code

<%-- header.jsp --%>


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>header page</title>
</head>
<body>
<table>
<tr>
<td><img src="Uploaded_Files/DMU_Logo.png" width=50 height=50 alt= "Logo image"
/></td>
<td><img src="Uploaded_Files/header.png" width=1000 height=50 alt="Header image" />
</td>

</tr>
</table>
</body>
</html>

When you run the above file Home.jsp on server you will get the following web page

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 8


Session Management and Page Redirection Example
Assume you have Admin_home.jsp, Registrar_officer_home.jsp, Department_head_home.jsp
and table user(User_Name,Password,User_Type,Status). Let users are Admin,Registrar
Officer,Department Head, Registrar Director, Student etc

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.

Create Validateuser.jsp file under the project Student_Profile_Registration_System_JSP. The


code that used to handle the tasks described in the above paragraph is given below.

<%-- Validateuser.jsp --%>


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%@ page import="java.sql.*"%>

<% 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");

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 9


if(submit!=null)
{ String status="Active";
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;
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.print(e.getMessage());
}

conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
stmt=conn.createStatement();

String sql="select * from user where User_Name='"+username+"' and Password='"+password+"'


and Status='"+status+"'";
rs=stmt.executeQuery(sql);
if(!rs.next())
{
out.print("<font color=red>Wrong user name or password, try again or your status may be
blocked by system admin</font>");
response.sendRedirect("Home"); //redirect to Home page

}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
}

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 10


// You can add other cases here
}
}
}catch(Exception e)
{ out.print(e.getMessage());
}
%>
</body>
</html>

Next create Registrar_officer_home.jsp that contains hyperlink that used to accesses


Register_student_profile.jsp, Update_student_profile.jsp ,View_student_profile.jsp and
Logout.jsp files. The code for Registrar_office_home.jsp is given below

<%-- Registrar_officer_home.jsp --%>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>

<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);

// For session management


if (session.getAttribute("uname")==null||session.getAttribute("utype")==null)
{
response.sendRedirect("Home.jsp");
return;
}
if(!session.getAttribute("utype").equals("Registrar Officer")) {
response.sendRedirect("Home.jsp"); //redirect to home page

}
String user_name=null,user_type=null;
if(session!=null) {
user_name=(String)session.getAttribute("uname");
user_type=(String)session.getAttribute("utype");
}
%>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 11


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Registrar Officer Home Page </title>
</head>
<body bgcolor=#66CCFF>
<%@include file="header.jsp"%>
<h2 align=center> <%=user_type%> Home Page </h2>
<p align=right> Welcome <%=user_name%> <a href=Logout.jsp style=color:white;font-
size:26><input type=submit value=Logout style=color:white;font-size:20;background-
color:#cc6600></a></p>

<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

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 12


Data Insertion:
After creating hyperlink on Regisrar_officer_home.jsp page try to create the following files
Register_student_profile.jsp, Update_student_profile.jsp, View_student_profile.jsp and
Logout.jsp under your project to accesses them through the link.

<%-- Register_student_profile.jsp --%>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>

<% 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;
}
%>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 13


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registration Student Profile</title></head>
<body bgcolor=#66CCFF>
<%@include file="header.jsp"%>
<h1 style=color:#cc6600>Student Profile Registration Page</h1>
<%
String submit = request.getParameter("submit");
if(submit==null)
{ %>
<form action= "Register_student_profile.jsp" method=post >
Student ID: <input type=text name=studid size=20 required /><br>
First Name: <input type=text name=firstname size=30 required /><br>
Second Name: <input type=text name=secondname size=30 required /><br>
Date of Birth: <input type=date name=dob required /><br>
Entry Year: <input type=number name=entryyear required /><br>
<input type=submit name=submit value=Register /><input type=reset value=Clear>
</form>
<%
}else {
String sid = request.getParameter("studid");
String fname = request.getParameter("firstname");
String sname = request.getParameter("secondname");
String dobirth = request.getParameter("dob");
String eyear = request.getParameter("entryyear");
int ey=Integer.parseInt(eyear);

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());
}

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 14


try {
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);

String sql="insert into student_profile (Student_Id, First_Name,Second_Name,


Date_Of_Birth,Entry_Year) VALUES (?,?,?,?,?)";

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>

<form action= "Register_student_profile.jsp" method=post >


Student ID: <input type=text name=studid value=<%=sid%> readonly /><br>
First Name: <input type=text name=firstname value=<%=fname%> readonly /><br>
Second Name: <input type=text name=secondname value=<%=sname%> readonly /><br>
Date of Birth: <input type=date name=dob value=<%=dobirth%> readonly /><br>
Entry Year: <input type=number name=entryyear value=<%=eyear%> readonly /><br>
<input type=submit value=Close />
</form>
<%
}else{
%>
<font color=red>Failed to insert data</font>
<% }
}catch (SQLException e){
out.print(e.getMessage());
}
}
%>
</body>
</html>

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.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 15


Try to fill data and click submit button labeled as Register, the code read data from the form
and insert to student_profile table and displays the inserted data for the user in a form that
contains submit button labeled as Close. When you click this button, the code shifts you to the
blank form to register additional data.

Data Update:
<%--Update_student_profile.jsp --%>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>

<% 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;
}
%>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 16


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Update Student Profile</title>
</head>
<body bgcolor=#66CCFF>
<%@include file="header.jsp"%>
<h1> Student Profile Update Form </h1>
<%
try {
String search=request.getParameter("search");
String studid=request.getParameter("studid");
String update=request.getParameter("update");
String fname=request.getParameter("firstname");
String sname=request.getParameter("secondname");
String dob=request.getParameter("dob");
String eyear=request.getParameter("entryyear");
%>
<form action= "Update_student_profile.jsp" method=POST>
Search By Student Id: <input type=text name=studid required />
<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;
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();

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 17


if(search!=null&&update==null)
{

String sql="select * from student_profile where Student_Id='"+studid+"'";


rs=stmt.executeQuery(sql);

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>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 18


<form action= "Update_student_profile.jsp" method=post >
Student ID: <input type=text name=studid value=<%=studid%> readonly /><br>
First Name: <input type=text name=firstname value=<%=fname%> readonly /><br>
Second Name: <input type=text name=secondname value=<%=sname%> readonly /><br>
Date of Birth: <input type=date name=dob value=<%=dob%> readonly /><br>
Entry Year: <input type=number name=entryyear value=<%=eyear%> readonly /><br>
<input type=submit value=Close />
</form>
<% }else{
%>
<font color=red>Failed to update</font>
<% }
}
} catch(Exception e) {
out.print(e.getMessage());
}
%>
</body> </html>

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.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 19


View Data:
<%-- View_student_profile.jsp --%>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>

<% 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;

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 20


try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.println(e.getMessage());
}
try {
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
stmt=conn.createStatement();
if(studid==""&&studfirstname=="")
{
%>
<font color=red>Please enter student Id or First name to view specific student record</font>
<%
}else if(studid!=""&&studfirstname=="")
{
rs=stmt.executeQuery("select * from student_profile where Student_Id='"+studid+"'");
if(!rs.next()){
%>
<font color=red>There is no student registered with Id <%=studid%></font>
<%
}else{
rs=stmt.executeQuery("select * from student_profile where Student_Id='"+studid+"'");
%>
<table border= 2>
<tr>
<th>Student Id </th><th>First Name </th> <th>Second Name </th>
<th>Date Of Birth</th><th>Entry Year </th>
</tr>
<%
while(rs.next())
{ %>
<tr>
<td><%=rs.getString("Student_Id") %></td><td><%=rs.getString("First_Name")%></td>
<td><%=rs.getString("Second_Name")%></td><td><%=rs.getString("Date_Of_Birth")%></td>
<td><%=rs.getString("Entry_Year")%></td>
</tr>
<% } %>
</table>
<%
}
}else if(studid==""&&studfirstname!="")
{
rs=stmt.executeQuery("select * from student_profile where First_Name='"+studfirstname+"'");
if(!rs.next()){
%>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 21


<font color=red>There is no student registered with first name <%=studfirstname%></font>
<%
}else{
rs=stmt.executeQuery("select * from student_profile where First_Name='"+studfirstname+"'");
%>
<table border= 2>
<tr>
<th>Student Id </th><th>First Name </th> <th>Second Name </th>
<th>Date Of Birth</th><th>Entry Year </th>
</tr>
<%
while(rs.next())
{ %>
<tr>
<td><%=rs.getString("Student_Id") %></td><td><%=rs.getString("First_Name")%></td>
<td><%=rs.getString("Second_Name")%></td><td><%=rs.getString("Date_Of_Birth")%></td>
<td><%=rs.getString("Entry_Year")%></td>
</tr>
<% } %>
</table>
<%
}
}else if(studid!=""&&studfirstname!="") {
%>
<font color=red>Please enter either student id or student first name </font>
<%
}

}catch (Exception e){


out.println(e.getMessage());
}

%>
</body>
</html>

When you run Home.jsp and login as Registrar Officer and click View Student Profile you will get
the following web page

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 22


Enter either student id or First name and click submit button labeled by Search. For instance,
enter student Id TER/1221/2015 and click Search button, the following record is retrieved from
studet_profile table

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 23


Enter first name Abel and click Search button. The following record is retrieved from
studet_profile table

<%-- Logout.jsp --%>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<% 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>Insert title here</title>
</head>
<body>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 24


<%
session.invalidate();
response.sendRedirect("Home.jsp");
out.print("You are successfully logged out!");
%>
</body>
</html>

JSP File Uploading and inserting its path to database


In this topic we will see how to upload file to specific directory and insert the file path to
database and finally we will see how to retrieve the file from database using JSP.

First create directory let it be


E:/Advanced_Programming_JSP_Example/Student Profile Registration
System/Student_Profile_Registration_System_JSP/src/main/webapp/Uploaded_Files.

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" %>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 25


<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="java.sql.*" %>

<% 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";
%>

<form action="Register_student_document.jsp?submit=1" method=post


enctype="multipart/form-data" >
Student Id: <input type=text name=stud_id required />
<br>
Document Description:
<select name=doc_description required />
<option value="Photo" selected>Photo</option>
<option value="Grade 8 Result" >Grade 8 Result</option>
<option value="Grade 9-12 Transcript" >Grade 9-12 Transcript</option>
<option value="Grade 12 Result" >Grade 12 Result</option>
</select>
<br>
Select File: <input type=file name=Upload_file />
<br>
<input type=submit name=submit value=Upload />
</form>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 26


<%

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;

boolean isMultipart = ServletFileUpload.isMultipartContent(request);


if(!isMultipart)
{

}
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();

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 27


boolean savedfileexist=false;
folderpath=new File(filelocationpath);
if(!folderpath.exists())
folderpath.mkdirs();

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) {

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 28


%>
<font color=green>Student Document inserted into student_document table</font>

<form action= "Register_student_document.jsp" method=post >


Student ID: <input type=text name=studid value=<%=studid%> readonly /><br>
Document Description: <input type=text name=doc_description
value=<%=doc_description%> readonly /><br>
Document: <%
if(filetype.equals("application/pdf")){
%>
<a href="filelocationpath_for_database" target=_blank >View Document</a>
<%
}else if(filetype.equals("image/jpeg")){%>
<img src="filelocationpath_for_database" width=50 height=50 />
<% } %>
<input type=submit value=Close />

</form>
<% }
}
}
}
}
}
}catch(Exception e)
{
out.println(e.getMessage());
}%>
</body>
</html>
When you run the above file, you will get the following web page

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 29


Once we upload file to a given directory and insert the file path to database let us display the file
from the directory using the file path inserted to database during uploading.

<%-- View_student_document --%>


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>View Uploaded File</title></head>
<body bgcolor=#66CCFF>
<%@include file="header.jsp"%>
<%
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;

try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
out.print(e.getMessage());
}

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 30


try {
conn=DriverManager.getConnection(dbUrl,dbusername,dbpassword);
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from student_document");
%>

<table border= 2>


<tr>
<th>Student Id </th> <th>Document Description </th><th>Document</th>
</tr>
<%
while(rs.next())
{
String docdesc=rs.getString("Document_Description");
%>
<tr>
<td><%=rs.getString("Student_Id") %></td>
<td><%=rs.getString("Document_Description")%></td>

<%if(docdesc.equals("Photo")) { %>
<td> <img src=<%=rs.getString("Document_Path")%> width=50 height=50 /></td>

<%}else {%> <td><a href=<%=rs.getString("Document_Path")%> target=_blank>View


Document</a></td>
<%} %>
</tr>
<% } %>
</table>
<%
}catch (Exception e){
out.println(e.getMessage());
}
%>
</body>
</html>

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 31


If there are files inserted in student_document table you will get output shown below.

COMPILED BY: GETNET M. DEBRE MARKOS UNIVERSITY 32

You might also like