0% found this document useful (0 votes)
112 views

Advance Java Lab: Ssipmt

This document contains information about the Advance Java Lab course including: 1. A certificate template to certify completion of required Java experiments. 2. An index listing 10 Java programs/experiments covering topics like factorials, forms, SQL connections and more. 3. Details and code for Experiment 1 - Hello World and date/time programs in JSP/Servlet.

Uploaded by

VISHAL YADAV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

Advance Java Lab: Ssipmt

This document contains information about the Advance Java Lab course including: 1. A certificate template to certify completion of required Java experiments. 2. An index listing 10 Java programs/experiments covering topics like factorials, forms, SQL connections and more. 3. Details and code for Experiment 1 - Hello World and date/time programs in JSP/Servlet.

Uploaded by

VISHAL YADAV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

ADVANCE JAVA LAB

SSIPMT

ADVANCE JAVA LAB

Department of Computer Science &Engineering Page 1


Shri Shankaracharya Institute Of Professional Management & Technology, Raipur
ADVANCE JAVA LAB

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CERTIFICATE

This is to certify that

Mr./Ms._________Bhumika Pankaj Bhandari____________

has satisfactorily completed the required number of

experiments in ADVANCE JAVA LAB as per the University

syllabus of B.E. VI Semester for the academic Session

2020-21.

Signature of Faculty

Date:

Department of Computer Science &Engineering Page 2


Shri Shankaracharya Institute Of Professional Management & Technology, Raipur
ADVANCE JAVA LAB

Index

S.NO PROGRAM Remark

a) Program for printing Hello World


1 b) Program for Printing System Date & Time
JSP/SERVLET

Write a server-side program for Finding Factorial of


2 number.

Write a Server-side program in JSP/SERVLET for


3 performing Addition of two no accept numbers from
client side by using HTML form
Write a Server-side program in JSP/SERVLET for
4. Income Tax Calculation.

Write a JSP/SERVLET which does the following job:


5
Login and Registration of the user.
Write a JSP/SERVLET which does the following job:
6
MYSQL Connection and Insertion.
Write a Server-side program in JSP/SERVLET
7 program: For Telephone Directory.

Write a Server-side program in JSP/SERVLET for


8 solving Quadratic Equation accept necessary
parameters from HTML form.
Develop JSP program to display the grade of a
9 student by accepting the marks of five subject.

Create tables in the database which contain the


10
details of items of each category.

DATE OF FINAL SUBMISSION : _________________________

GRADE : _________________________

SIGNATURE OF TEACHER : _________________________

Department of Computer Science &Engineering Page 3


Shri Shankaracharya Institute Of Professional Management & Technology, Raipur
Experiment 1
a) Program for printing Hello World
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** * Servlet implementation class HelloWorld */


public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;

/** * Default constructor. */


public HelloWorld() {
}

/* * This method will handle all GET request. */


protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hello World");
}

/* * This method will handle all POST request */


protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>HelloWorldServlet</display-name>
<servlet>
<description></description>
<display-name>HelloWorld</display-name>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.jbt.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
b) Program for Printing System Date & Time JSP/SERVLET
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayingDate extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
Date today = new Date();
pw.println("<html>"+"<body><h1>Today Date is</h1>");
pw.println("<b>"+ today+"</b></body>"+ "</html>");
}
}

XML File for this program

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>DateDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/DateDisplay</url-pattern>
</servlet-mapping>
</web-app>
Experiment 2
Write a server-side program for Finding Factorial of number.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FactorialServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int num = Integer.parseInt(request.getParameter("text1"));
out.println(this.fact(num));

long fact(long a) {
if (a <= 1)
return 1;
else {
a = a * fact(a - 1);
return a;
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>servletBasicExample</display-name>
<servlet>
<servlet-name>FactorialServlet</servlet-name>
<servlet-class>simpleServletExample.FactorialServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FactorialServlet</servlet-name>
<url-pattern>/factorialServlet</url-pattern>
</servlet-mapping>

</web-app>
Experiment 3
Write a Server-side program in JSP/SERVLET for performing
Addition of two no accept numbers from client side by using
HTML form
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class First extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
int sum;
int x,y;
String a = request.getParameter("num1");
String b = request.getParameter("num2");
x = Integer.parseInt(a);
y = Integer.parseInt(b);
sum = x + y;
out.println("The sum is" + sum);
}
}
}
Test.html
<html>
<head>
<title>Supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="First">
Number1:<input type="text" name="num1" /><br/>
Number2:<input type="text" name="num2" /><br/>
<input type="submit" value="button" />
</form>
</body>
</html>
Experiment 4
Write a Server-side program in JSP/SERVLET for Income Tax
Calculation.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Calculate Interest JSP</title>
</head>
<body>
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String gender = request.getParameter("gender");
String profession = request.getParameter("profession");
String prefix = " ";
if (gender.equals("Male")) { prefix = "Mr."; }
else if (gender.equals("Female")) { prefix = "Ms."; } %>
<FONT COLOR = "Blue">Hello <%=prefix
%>&nbsp;<%=fname%>&nbsp;<%=lname%> &nbsp; who works in a
<%=profession %></FONT>
<% String sincome = request.getParameter("income");
float income = Float.parseFloat(sincome);
out.println("<BR>Your Annual Income is <FONT COLOR = Blue> " +income +
"</FONT>");
float tax;
float diff;
if(income <= 100000)
{
out.println("<BR>You are below the Tax Bracket!!");
}
else if(income >100000 && income <= 200000)
{
out.println("<BR>Your Tax Bracket is between Rs.1,00000 to Rs.2,00000");
out.println("<BR><B><U> Tax Rule: </U></B>10% of income above Rs.1 Lakh");
diff = income - 100000;
tax = (float)0.1*diff;
out.println("<BR>Tax to be paid is <FONT COLOR = Blue> "+tax+ "</FONT>");
}
else if(income >200000 && income <= 300000)
{
out.println("<BR>Your Tax Bracket is between between Rs.1,00000 to Rs.3,00000");
out.println("<BR><B><U>Tax Rule: </U></B> 10% of income upto Rs.1 Lakh and
20% of rest of income");
diff = income - 200000;
tax = (float)0.2*diff + (float)0.1*100000;
out.println("<BR>Tax to be paid is <FONT COLOR = Blue> "+tax+ "</FONT>");
}
else if(income >100000 && income <= 400000)
{
out.println("<BR>Your Tax Bracket is between Rs.1,00000 to Rs.4,00000");
out.println("<BR><B><U>Tax Rule: </U></B>10% of income upto Rs.1 Lakh 20%
of income upto Rs.3 Lakh and 30% of rest of income");
diff = income - 300000;
tax = (float)0.3*diff + (float)0.2*200000 + (float)0.1*100000;
out.println("<BR>Tax to be paid is <FONT COLOR = Blue> "+tax);
}
else if(income > 400000)
{
out.println("<BR>You fall in the tax bracket greater than Rs.4,00000");
diff = income - 400000;
tax = diff + (float)0.3*300000 + (float)0.2*200000 + (float)0.1*100000;
out.println("<BR><B><U>Tax Rule:</U></B> 10% of income upto Rs.1 Lakh 20%
of income upto 3Lakh, 30% of income upto Rs.4 lakh and 100% of rest of income");
out.println("<BR>Tax to be paid is <FONT COLOR = Blue> "+tax+ "</FONT>");
}//end if %>
</body>
</html>

JSP code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" import = "java.util.* , java.text.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%!
HashMap hm;
String uname;
String pwd;
Map.Entry entry;
%>
<%
boolean login = false;
hm = new HashMap();
uname = request.getParameter("username");
pwd = request.getParameter("password");
hm.put("Archie","Riverdale");
hm.put("Haddock", "Marlinspike");
hm.put("Hermione","Hogwarts");
Set s = hm.entrySet();
Iterator it = s.iterator();
while(it.hasNext())
{
entry = (Map.Entry) it.next();
if(uname.equals(entry.getKey()) && pwd.equals(entry.getValue()))
{
login=true;
}
}//end while
if(login==true)
{
out.println("<B><FONT COLOR = Blue>");
out.println("Welcome </FONT></B>");
out.println(uname);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
out.println("<BR><FONT COLOR = Green>");
out.println("Today is </FONT>"+dateFormat.format(date));
%>
<form action="CalculateInterest.jsp" method = "post">
<FONT COLOR = "Magenta"> First Name:</FONT>
<input type = "text" size = "15" name = "fname">
<br>
<FONT COLOR = "Brown">Last Name: </FONT>
<input type = "text" size = "15" name = "lname">
<br>
<FONT COLOR = "Purple">Select your Place of Work:</FONT>
<br>
<select name="profession" size="3">
<option>IT Company</option>
<option>Private Bank</option>
<option>Insurance Company</option>
</select>
<br>
<input type="radio" name="gender" value="Male"> Male<br>
<input type="radio" name="gender" value="Female" checked>Female<br>
<br>
<FONT COLOR = "Red"> Annual Income(in Rupees):</FONT>
<input type = "text" size = "15" name = "income">
<br>
<br>
<input type = "submit" value = "Calculate Tax">
</form>
<%
}
else
{
%>
<jsp:forward page="Login.jsp">
<jsp:param name="FailReason" value="Wrong Username or Password"/>
</jsp:forward>
<%
}
%>
</body>
</html>
Experiment 5
Write a JSP/SERVLET which does the following job: Login and
Registration of the user.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form action="dataCapture.jsp" method = "post">
User Name:
<input type = "text" size = "15" name = "username">
<br>
Password:
<input type = "password" size = "15" name = "password">
<br>
<input type = "submit" value = "Login">
</form>
<%
String reason = request.getParameter("FailReason");
if(reason !=null)
out.println(reason); %>
</body>
</html>
Experiment 6
Write a JSP/SERVLET which does the following job: MYSQL
Connection and Insertion.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// This class can be used to initialize the database connection


public class DatabaseConnection {
protected static Connection initializeDatabase()
throws SQLException, ClassNotFoundException
{
// Initialize all the information regarding
// Database Connection
String dbDriver = "com.mysql.jdbc.Driver";
String dbURL = "jdbc:mysql:// localhost:3306/";
// Database name to access
String dbName = "demoprj";
String dbUsername = "root";
String dbPassword = "root";

Class.forName(dbDriver);
Connection con = DriverManager.getConnection(dbURL + dbName,

dbUsername,

dbPassword);
return con;
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Import Database Connection Class file


import code.DatabaseConnection;

// Servlet Name
@WebServlet("/InsertData")
public class InsertData extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
try {

// Initialize the database


Connection con = DatabaseConnection.initializeDatabase();

// Create a SQL query to insert data into demo table


// demo table consists of two columns, so two '?' is used
PreparedStatement st = con
.prepareStatement("insert into demo values(?, ?)");

// For the first parameter,


// get the data using request object
// sets the data to st pointer
st.setInt(1, Integer.valueOf(request.getParameter("id")));

// Same for second parameter


st.setString(2, request.getParameter("string"));

// Execute the insert command using executeUpdate()


// to make changes in database
st.executeUpdate();

// Close all the connections


st.close();
con.close();

// Get a writer pointer


// to display the successful result
PrintWriter out = response.getWriter();
out.println("<html><body><b>Successfully Inserted"
+ "</b></body></html>");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Experiment 7
Write a Server-side program in JSP/SERVLET program: For
Telephone Directory.
import java.io.*;
import java.util.*;
class Directory implements Comparable {
int id;
String name;
String address;
int phoneNo;

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

public int getPhoneNo() {


return phoneNo;
}

public void setPhoneNo(int phoneNo) {


this.phoneNo = phoneNo;
}

public int compareTo(Object ob) throws ClassCastException {


if (!(ob instanceof Directory))
throw new ClassCastException("Error");
int ide = ((Directory) ob).getId();
return this.id - ide;
}
}

public class TelephoneDirectory {

public static void main(String[] args) throws Exception {


Scanner scan = new Scanner(System.in);
int menu = 0;
System.out.println("Telephone Directory Management System");
System.out.println();
System.out.println("1. Accept Data");
System.out.println("2. Search");
System.out.println("3. Sort Data");
System.out.println("4. List of all persons");
System.out.println("5. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = scan.nextInt();
System.out.println();

switch (menu) {
case 1:
System.out.print("Enter student ID: ");
int ID = scan.nextInt();
System.out.print("Enter Name: ");
String name = scan.next();
System.out.print("Enter Address: ");
String address = scan.next();
System.out.println("Enter Phone No: ");
int no = scan.nextInt();
FileWriter fw = new FileWriter(new File("directory.txt"), true);
BufferedWriter out = new BufferedWriter(fw);
out.write(ID + " " + name + " " + address + " " + no);
out.newLine();
out.close();
break;
case 2:
System.out.print("Enter name to search information: ");
String n = scan.next();
File f = new File("directory.txt");
try {
BufferedReader freader = new BufferedReader(new
FileReader(f));
String s;
while ((s = freader.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String nm = st[1];
String add = st[2];
String phoneNo = st[3];
if (n.equals(nm)) {
System.out .println(********Information********");
System.out.println("Address : " + add);
System.out.println("PhoneNo : " + phoneNo);
}
}
freader.close();
} catch (Exception e) {
}
break;
case 3:
File file = new File("directory.txt");
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
ArrayList list = new ArrayList();
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
int j = 0;
Directory data[] = new Directory[list.size()];
try {
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split(" ");
String id = "", nn = "", add = "", pno = "";
for (int i = 0; i < splitSt.length; i++) {
id = splitSt[0];
nn = splitSt[1];
add = splitSt[2];
pno = splitSt[3];

}
data[j] = new Directory();
data[j].setId(Integer.parseInt(id));
data[j].setName(nn);
data[j].setAddress(add);
data[j].setPhoneNo(Integer.parseInt(pno));

j++;
}

BufferedWriter bw = new BufferedWriter(new


FileWriter(file,
true));
Arrays.sort(data);
System.out.println("********Sorted by id********");
String strVal = "";
for (int i = 0; i < 8; i++) {
Directory show = data[i];
int ide = show.getId();
String nnn = show.getName();
String add = show.getAddress();
int phone = show.getPhoneNo();
System.out.println(ide + " " + nnn + " " + add + " " +
phone);
}
} catch (Exception e) {
}
break;

case 4:
FileInputStream fis = new FileInputStream(new File(
"directory.txt"));
DataInputStream dis = new DataInputStream(fis);
BufferedReader reader = new BufferedReader(
new InputStreamReader(dis));
String st;
ArrayList al = new ArrayList();
while ((st = reader.readLine()) != null) {
al.add(st);
}
Iterator itr;
for (itr = al.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split(" ");
String id = "", na = "", ada = "", ph = "";
for (int i = 0; i < splitSt.length; i++) {
id = splitSt[0];
na = splitSt[1];
ada = splitSt[2];
ph = splitSt[3];
}
System.out.println(id + " " + na + " " + ada + " " + ph);
}
break;
case 5:
quit = true;
break;
default:
System.out.println("Invalid Entry!");
}
} while (!quit);
}
}

HTML CODE

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="login.jsp" method="post">
User name :<input type="text" name="usr" /><br>
password :<input type="password" name="password" /><br>
<input type="submit" /> </form>
<p>New user. <a href="register.html">Login Here</a>. </body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String userid=request.getParameter("userid");
session.putValue("userid",userid);
String password=request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root",""
);
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where userid='"+userid+"'
and password='"+password+"'");
try{
rs.next();
if(rs.getString("password").equals(password)&&rs.getString("userid").equals(
userid))
{
out.println("Welcome " +userid);
}
else{
out.println("Invalid password or username.");
}
}
catch (Exception e) {
e.printStackTrace();
}
%>
register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>new registration</title>
</head>
<body>
<form action="reg-process.jsp" method="post">
First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
Email ID :<input type="text" name="email" />
User name :<input type="text" name="userid" />
password :<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>
reg-process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
String userid=request.getParameter("userid");
String password=request.getParameter("password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root",
"");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into
users(fname,lname,email,userid,password)values('"+fname+"','"+lname+"','"+
email+"','"+userid+"','"+password+"')");
out.println("Thank you for register ! Please <a href='index.html'>Login</a> to
continue.");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>
Experiment 8
Write a Server-side program in JSP/SERVLET for solving
Quadratic Equation accept necessary parameters from HTML
form.

Index.jsp
<html>
<body>
<font color="gray" size="5">
Program For Quadratic Equation.
</font>
<form action="quad.jsp" method="GET">
<table><tr><td> Enter coefficients a : </td><td><input type="text"
name="a"><br><br></td></tr>
<tr><td> Enter coefficients b : </td><td><input type="text"
name="b"><br><br></td></tr>
<tr><td> Enter coefficients c : </td><td><input type="text"
name="c"><br><br></td></tr>
<br />
<tr><td><input type="submit" value="Submit" /></td></tr>
</table>
</form>
</body>
</html>

Quad.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Equation</title>
</head>
<body>
<h1>Quadratic Equation </h1>
<%
double a, b, c, determinant,r1,r2, real, imag;
String f1 = request.getParameter("a");
String f2 = request.getParameter("b");
String f3 = request.getParameter("c");
a = Double.parseDouble(f1);
b = Double.parseDouble(f2);
c = Double.parseDouble(f3);
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+Math.sqrt(determinant))/(2*a);
r2= (-b-Math.sqrt(determinant))/(2*a);
out.println("Roots are : = "+r1+" and "+r2);
}
else if (determinant==0)
{
r1 = r2 = -b/(2*a);
out.println("Roots are : = "+r1+" and "+r2);
}
else
{
real= -b/(2*a);
imag = Math.sqrt(-determinant)/(2*a);
out.println("Roots are : = "+real+" and "+imag);
}
%>
<font color =" gray" size="5">
<%
%>
</font>
</body>
</html>
Experiment 9
Develop JSP program to display the grade of a student by
accepting the marks of five subject.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>

</head>
<body>
<center>
<h1>Student marks</h1>
<form action="marks.jsp" method="get">
Enter Makrs in Java : <input type="text" name="java"> <br><br>
Enter NMA Marks : <input type="text" name="NMA"><br><br>
Enter MCAD Marks :<input type="text" name="MCAD"><br><br>
Enter PPUD Marks :<input type="text" name="PPUD"><br><br>
Enter Project Marks :<input type="text" name="pro"><br><br>
<input type="submit">
</form>
</center>
</body>
</html>

*Marks.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
int java=Integer.parseInt(request.getParameter("java"));
int NMA=Integer.parseInt(request.getParameter("NMA"));
int MCAD=Integer.parseInt(request.getParameter("MCAD"));
int PPUD=Integer.parseInt(request.getParameter("PPUD"));
int Project=Integer.parseInt(request.getParameter("pro"));

int c=java+NMA+MCAD+PPUD+Project;
double avg=c/5;

if(avg > 90 )
{
out.println(" your grade is A");
}else if (avg >= 80) {
out.println("your grade is b");
} else if (avg >= 70) {
out.println("your grade is c");
} else if (avg >= 60) {
out.println("your grade is d");
} else {
out.println("your grade is e");
}
%>
</body>
</html>
Experiment 10
Create tables in the database which contain the details of items
(books in our case like Book name, Price, Quantity, Amount)) of
each category. Modify your catalogue page in such a way that you
should connect to the database and extract data from the tables
and display them in the catalogue page using JDBC.

CREATE DATABASE 'Bookstore';


USE Bookstore;

CREATE TABLE `book` (


`book_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(128) NOT NULL,
`author` varchar(45) NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`book_id`),
UNIQUE KEY `book_id_UNIQUE` (`book_id`),
UNIQUE KEY `title_UNIQUE` (`title`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>

public class Book {


protected int id;
protected String title;
protected String author;
protected float price;

public Book() {
}

public Book(int id) {


this.id = id;
}

public Book(int id, String title, String author, float price) {


this(title, author, price);
this.id = id;
}

public Book(String title, String author, float price) {


this.title = title;
this.author = author;
this.price = price;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}

public float getPrice() {


return price;
}

public void setPrice(float price) {


this.price = price;
}
}

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

private String jdbcURL;


private String jdbcUsername;
private String jdbcPassword;
private Connection jdbcConnection;

public BookDAO(String jdbcURL, String jdbcUsername, String jdbcPassword) {


this.jdbcURL = jdbcURL;
this.jdbcUsername = jdbcUsername;
this.jdbcPassword = jdbcPassword;
}
protected void connect() throws SQLException {
if (jdbcConnection == null || jdbcConnection.isClosed()) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
jdbcConnection = DriverManager.getConnection(
jdbcURL, jdbcUsername, jdbcPassword);
}
}

protected void disconnect() throws SQLException {


if (jdbcConnection != null && !jdbcConnection.isClosed()) {
jdbcConnection.close();
}
}

public boolean insertBook(Book book) throws SQLException {


String sql = "INSERT INTO book (title, author, price) VALUES (?, ?, ?)";
connect();

PreparedStatement statement = jdbcConnection.prepareStatement(sql);


statement.setString(1, book.getTitle());
statement.setString(2, book.getAuthor());
statement.setFloat(3, book.getPrice());

boolean rowInserted = statement.executeUpdate() > 0;


statement.close();
disconnect();
return rowInserted;
}

public List<Book> listAllBooks() throws SQLException {


List<Book> listBook = new ArrayList<>();

String sql = "SELECT * FROM book";

connect();

Statement statement = jdbcConnection.createStatement();


ResultSet resultSet = statement.executeQuery(sql);

while (resultSet.next()) {
int id = resultSet.getInt("book_id");
String title = resultSet.getString("title");
String author = resultSet.getString("author");
float price = resultSet.getFloat("price");

Book book = new Book(id, title, author, price);


listBook.add(book);
}

resultSet.close();
statement.close();

disconnect();

return listBook;
}

public boolean deleteBook(Book book) throws SQLException {


String sql = "DELETE FROM book where book_id = ?";

connect();

PreparedStatement statement = jdbcConnection.prepareStatement(sql);


statement.setInt(1, book.getId());

boolean rowDeleted = statement.executeUpdate() > 0;


statement.close();
disconnect();
return rowDeleted;
}

public boolean updateBook(Book book) throws SQLException {


String sql = "UPDATE book SET title = ?, author = ?, price = ?";
sql += " WHERE book_id = ?";
connect();

PreparedStatement statement = jdbcConnection.prepareStatement(sql);


statement.setString(1, book.getTitle());
statement.setString(2, book.getAuthor());
statement.setFloat(3, book.getPrice());
statement.setInt(4, book.getId());

boolean rowUpdated = statement.executeUpdate() > 0;


statement.close();
disconnect();
return rowUpdated;
}

public Book getBook(int id) throws SQLException {


Book book = null;
String sql = "SELECT * FROM book WHERE book_id = ?";

connect();

PreparedStatement statement = jdbcConnection.prepareStatement(sql);


statement.setInt(1, id);

ResultSet resultSet = statement.executeQuery();

if (resultSet.next()) {
String title = resultSet.getString("title");
String author = resultSet.getString("author");
float price = resultSet.getFloat("price");

book = new Book(id, title, author, price);


}

resultSet.close();
statement.close();

return book;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Books Store Application</title>
</head>
<body>
<center>
<h1>Books Management</h1>
<h2>
<a href="/new">Add New Book</a>
&nbsp;&nbsp;&nbsp;
<a href="/list">List All Books</a>

</h2>
</center>
<div align="center">
<table border="1" cellpadding="5">
<caption><h2>List of Books</h2></caption>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Actions</th>
</tr>
<c:forEach var="book" items="${listBook}">
<tr>
<td><c:out value="${book.id}" /></td>
<td><c:out value="${book.title}" /></td>
<td><c:out value="${book.author}" /></td>
<td><c:out value="${book.price}" /></td>
<td>
<a href="/edit?id=<c:out value='${book.id}' />">Edit</a>
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="/delete?id=<c:out value='${book.id}' />">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Books Store Application</title>
</head>
<body>
<center>
<h1>Books Management</h1>
<h2>
<a href="/new">Add New Book</a>
&nbsp;&nbsp;&nbsp;
<a href="/list">List All Books</a>

</h2>
</center>
<div align="center">
<c:if test="${book != null}">
<form action="update" method="post">
</c:if>
<c:if test="${book == null}">
<form action="insert" method="post">
</c:if>
<table border="1" cellpadding="5">
<caption>
<h2>
<c:if test="${book != null}">
Edit Book
</c:if>
<c:if test="${book == null}">
Add New Book
</c:if>
</h2>
</caption>
<c:if test="${book != null}">
<input type="hidden" name="id" value="<c:out value='${book.id}' />"
/>
</c:if>
<tr>
<th>Title: </th>
<td>
<input type="text" name="title" size="45"
value="<c:out value='${book.title}' />"
/>
</td>
</tr>
<tr>
<th>Author: </th>
<td>
<input type="text" name="author" size="45"
value="<c:out value='${book.author}' />"
/>
</td>
</tr>
<tr>
<th>Price: </th>
<td>
<input type="text" name="price" size="5"
value="<c:out value='${book.price}' />"
/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Save" />
</td>
</tr>
</table>
</form>
</div>
</body>
</html>

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* ControllerServlet.java
* This servlet acts as a page controller for the application, handling all
* requests from the user.
* @author www.codejava.net
*/
public class ControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private BookDAO bookDAO;

public void init() {


String jdbcURL = getServletContext().getInitParameter("jdbcURL");
String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");

bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();

try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertBook(request, response);
break;
case "/delete":
deleteBook(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateBook(request, response);
break;
default:
listBook(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
private void listBook(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
List<Book> listBook = bookDAO.listAllBooks();
request.setAttribute("listBook", listBook);
RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp");
dispatcher.forward(request, response);
}

private void showNewForm(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
dispatcher.forward(request, response);
}

private void showEditForm(HttpServletRequest request, HttpServletResponse


response)
throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Book existingBook = bookDAO.getBook(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
request.setAttribute("book", existingBook);
dispatcher.forward(request, response);

private void insertBook(HttpServletRequest request, HttpServletResponse


response)
throws SQLException, IOException {
String title = request.getParameter("title");
String author = request.getParameter("author");
float price = Float.parseFloat(request.getParameter("price"));

Book newBook = new Book(title, author, price);


bookDAO.insertBook(newBook);
response.sendRedirect("list");
}

private void updateBook(HttpServletRequest request, HttpServletResponse


response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String title = request.getParameter("title");
String author = request.getParameter("author");
float price = Float.parseFloat(request.getParameter("price"));

Book book = new Book(id, title, author, price);


bookDAO.updateBook(book);
response.sendRedirect("list");
}

private void deleteBook(HttpServletRequest request, HttpServletResponse


response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));

Book book = new Book(id);


bookDAO.deleteBook(book);
response.sendRedirect("list");

}
}
public void init() {
String jdbcURL = getServletContext().getInitParameter("jdbcURL");
String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");

bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);

}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();

try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertBook(request, response);
break;
case "/delete":
deleteBook(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateBook(request, response);
break;
default:
listBook(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
private void listBook(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
List<Book> listBook = bookDAO.listAllBooks();
request.setAttribute("listBook", listBook);
RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp");
dispatcher.forward(request, response);
}
This method uses the DAO class to retrieve all books from the database, and then
forward to the BookList.jsp page for displaying the result. Similar logic is
implemented for the rest methods.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Books Management Web Application</display-name>

<context-param>
<param-name>jdbcURL</param-name>
<param-value>jdbc:mysql://localhost:3306/bookstore</param-value>
</context-param>

<context-param>
<param-name>jdbcUsername</param-name>
<param-value>root</param-value>
</context-param>

<context-param>
<param-name>jdbcPassword</param-name>
<param-value>P@ssw0rd</param-value>
</context-param>

<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>net.codejava.javaee.bookstore.ControllerServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

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

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


pageEncoding="UTF-8" isErrorPage="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Error</title>
</head>
<body>
<center>
<h1>Error</h1>
<h2><%=exception.getMessage() %><br/> </h2>
</center>
</body>
</html>

You might also like