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

Java Lab

The document is a lab report submitted by Shubhra Debnath to fulfill the requirements of the 4th semester MCA course at BMS College of Engineering. It contains 27 programs written in Java using concepts like servlets, JSP, database connectivity etc. Each program is briefly described and the code is provided. The lab report is certified by the internal guide and head of the computer applications department.

Uploaded by

Shubhra Debnath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Java Lab

The document is a lab report submitted by Shubhra Debnath to fulfill the requirements of the 4th semester MCA course at BMS College of Engineering. It contains 27 programs written in Java using concepts like servlets, JSP, database connectivity etc. Each program is briefly described and the code is provided. The lab report is certified by the internal guide and head of the computer applications department.

Uploaded by

Shubhra Debnath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 80

B.M.

S COLLEGE OF ENGINEERING
(Autonomous College under VTU)
Bull Temple Road, Bangalore-560019

DEPARTMENT OF COMPUTER APPLICATIONS

Lab report on
Advanced Java Programming(18MCA4PCAJ)

Submitted to fulfill the requirements of


4th Semester MCA

Submitted by:
Shubhra Debnath (1BF19MCA15)

Under the Guidance of

R V Raghavendra Rao
Assistant Professor
1
B.M.S COLLEGE OF ENGINEERING
(Autonomous College under VTU)
Bull Temple Road, Bangalore-560019

DEPARTMENT OF COMPUTER APPLICATIONS

CERTIFICATE
This is to certify that Shubhra Debnath (1BF19MCA15) has satisfactorily
completed the requirements Advanced Java Programming (18MCA4PCAJ)
Laboratory Report prescribed by 4th semester MCA course, BMS College of
Engineering during the year 2020-2021.

Signature of the Internal Guide Signature of HOD

2
TABLE OF CONTENTS
S.NO Page

1. Write a program using the request.getParameter() method to


enter the Name and Password of a user and display the output on
another JSP page.
2. Write a program to include an HTML file in a JSP page using
RequestDispatcher interface method. The included file should
display a login form to the user. In addition, the form should
provide a Submit and Reset button. Display a Welcome message
to the user when the user clicks on Submit button after entering
the details
3. a) Write a servlet application to print the current date and time.
b) Write an application to auto-refresh a page in servlet
4. Write a servlet application to establish communication between
Html and servlet page using a hyperlink
5. Write an application to demonstrate the session tracking in
Servlet.
6. a) Write a Servlet application to count the total number of visits
on your website.
b) Write a program to display the multiples of two using jsp
7. Write a Servlet program that accepts the age and name and
displays if the user is eligible for voting or not.
8. Write a program to adding 2 numbers using Java Servlets

9. Write a program to display a Hello World message in the Web


browser, display the hostname and Session-Id. Write JSP code
using HTML code
10. Write a program using the JSP to enter the Name and Password
of a user and display the output on another JSP page.
11. a) Write a program using JSP to calculate the sum of numbers
from 1 to 25.
b) Write a servlet to accept user name as input and reply with
greeting message.
12. Write a program to display the session ID, creation time, and the
last accessed time of the Webpage. Using session.getID,
session.getCreationTime(), and session.getLastAccessedTime()
13. Write a program to display an error message to the user if an
exception occurs in the JSP page. In the JSP page, consider a
null string and find out the length of the string using
length()method of Java. Create an error handler to handle the
exception thrown by this JSP page.
3
14. Develop a Java Bean to process student marks and print his/her
result. Create a JSP to accept details of Student name, Student
Marks in Three subjects. Using bean class verify the marks with
the following validations Students need to score marks >= 40 to
pass each subject else FAIL
If the Total Marks > = 90, Print Grade S
If the Total Marks > = 75 & < 90, Print Grade A
If the Total Marks > = 60 & < 75, Print Grade B
If the Total Marks > = 50 & < 60, Print Grade C
If the Total Marks > = 40 & < 50, Print Grade D else FAIL
15. create a Java Bean named Temperature that implements a
temperature converter from Celsius to Fahrenheit. Create a JSP
to accept the Celsius / Fahrenheit value from the user. Invoke
Java bean to Complete the Conversion process and print the
Result.
16. Create a User Interface to calculate Incometax based on the data
provided by the user. The UI needs the Name of the Tax Payer,
Income earned in the Year, Address etc. Develop a Java bean
class with the necessary logic to calculate Tax Payable. Standard
Deduction is 1,00,000 ( ie Subtract this amount 1,00,000 before
calculating the taxable amount)
Taxable Amount = Income Earned - Standard Deduction
If the Taxable amount < 1,00,000 - NO TAX
If the Taxable amount > 1,00,000 <= 5,00,000 - 10% Tax on
Taxable Amount
If the Taxable amount > 5,00,000 <=10,00,000 - 20% Tax on
Taxable Amount
If the Taxable amount > 10,00,000 - 30% Tax on Taxable
Amount
17. Write a program to display a login page to the user. The login
page should ask user to enter the account Id and pin number.
The account id and pin number should be compared with the
data in
database, and should be validated. Display appropriate message
to the user after validating the user input to the login form
18. Write a program that uses the response.setHeader()method to
display the date. In addition, set the response header attribute
and utilize the JSP expression tag.
19. Write a program to display the withdrawal status to the user. If
the account number is valid, display the withdrawal screen to the
user. The withdrawal screen should display the balance entered
by the user on the withdrawal status screen and ask the user to
4
enter the amount to be withdrawn. Display the balance to the
user after withdrawing the amount.
20. Choose a table in the database and write an application that and
prints the number of records in the table with complete details –
using prepared statement.
21. Write an application that inserts numerical data into a table. The
application
(i) retrieves the values from the command line and
(ii) Apply ACID operations on the selected / created Table.
22. Write an application that connects to a database through JDBC
and
(i) prints the names of all tables in the database,
(ii) for each table of the database prints its columns
23. Develop a Jdbc program to implement Insert, Delete, Update,
Search and Exit operations, based on user choice (For example
in the created table based on user choice, you need to implement
DML operations)
24. Develop a program to insert data into BLOB and CLOB type
columns in a table using JDBC?
25. Using spring create the Student class with necessary properties.
The properties provide through the xml file.
26. Using spring create the instance of dependent object (contained
object) then pass it as an argument of the main class constructor.
Consider student details scenario is Student HAS-A Address.
The
Address class object will be termed as the dependent object
27. Create a JSP page that lets the user to supply a request parameter
indicating the background color. If no parameter is supplied, a
background color should be selected at random

5
Program 1: Write a program using the request.getParameter()
method to enter the Name and Password of a user and display the
output on another JSP page.
Servlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
PrintWriter out=res.getWriter();
String unam=req.getParameter("uname");
String uaa=req.getParameter("uadd");

out.println("<HTML><BODY>");
out.println("<h1> USER INFORMATION</h1><hr />");
out.println("User name:: "+unam+"<br>");
out.println("Password:: "+uaa+"<br>");
out.println("</BODY></HTML>");
}
}

Serv.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ServletAction</title>
</head>

<body>
<h2> User details</h2>
<form method="post" action="http://localhost:8080/WebApp/Servlet1" >
<hr />
<h3> Enter user name::</h3>
<input type="text" name="uname" /><br /><br />
<h3>Enter Password::</h3>
<input type="password" name="uadd" /><br /><br />
<input type="submit" value="Display" />
<input type="reset" value="Clear" />
</form>
</body>
</html>
6
OUTPUT:

7
Program 2: Write a program to include an HTML file in a JSP page
using RequestDispatcher interface method. The included file should
display a login form to the user. In addition, the form should
provide a Submit and Reset button. Display a Welcome message to
the user when the user clicks on Submit button after entering the
details.
disp.jsp
<%
request.getRequestDispatcher("index.html").include(request, response);
%>
index.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="final.jsp" method="get">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/><br/>
<input type="reset" value="Reset"><br/>
</form>
</body>
</html>
final.jsp
<%
String st=request.getParameter("userName");
String pass=String.valueOf(request.getParameter("userPass"));
if(pass.equals("axel"))
{
out.println("<h1>Success! Welcome</h1>");
}
else{
request.getRequestDispatcher("index.html").include(request, response);
}
%>

OUTPUT:

8
9
Program 3: a) Write a servlet application to print the current date
and time.
b) Write an application to auto-refresh a page in servlet
DateTimeServ.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Date")
public class DateTimeServ extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
java.util.Date date = new java.util.Date();
pw.println("<h2>"+"Current Date & Time: " +date.toString()+"</h2>");
pw.close();
}
}

Output:

10
Refresh.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Refresh")
public class Refresh extends HttpServlet {
private static final long serialVersionUID = 1L;
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{

response.setIntHeader("Refresh", 1);
response.setContentType("text/html");
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";

String CT = hour+":"+ minute +":"+ second +" "+ am_pm;

PrintWriter out = response.getWriter();

out.println("<h1 align='center'>Auto Refresh Page</h1><hr>");


out.println("<h3 align='center'>Current time: "+CT+"</h3>");
}
}

11
Output:

12
4. Write a servlet application to establish communication between
Html and servlet page using a hyperlink
Link.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wishing message</title>
</head>
<body>
<a href = "http://localhost:8080/ServletExc/LinkServ">Hello ! This Is
HyperLink Demo</a>
</body>
</html>

LinkServ.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LinkServ")
public class LinkServ extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{

res.setContentType("text/html");

PrintWriter pw = res.getWriter();
pw.println("Demo Success!");

pw.println("<br><br><a href= '../ServletExc/Link.html'>Home</a>");


//close stream object
pw.close();
}

13
Output:

14
5. Write an application to demonstrate the session tracking in
Servlet.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;

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 javax.servlet.http.HttpSession;
@WebServlet("/SessionDemo")
public class SessionDemo extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession();
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


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

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


if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
}
else
{
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

String docType =
15
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#e5f7c0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#eadf8c\">\n" +
"<th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}

16
6. a) Write a Servlet application to count the total number of visits
on your website.
b) Write a program to display the multiples of two using jsp
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
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 javax.servlet.http.HttpSession;

@WebServlet("/Visit")
public class Visit extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

HttpSession session = request.getSession();


int visitCount =0;
if(!session.isNew())
{
visitCount = (Integer)session.getAttribute("VisitCount");
visitCount = visitCount + 1;
}
session.setAttribute("VisitCount", visitCount);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Total Visit "+visitCount);
}

Output:

17
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="MultOf2.jsp">
<b>Enter the Multiplier Range : </b><input type="number" name="no">
<br/>
<br/>
<input type="submit" value="Submit">
<input type="reset">
</form>
</body>
</html>

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


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int n=Integer.parseInt(request.getParameter("no"));
out.println("Multiples of 2 : ");
for(int i=1;i<=n;i++){
out.println(2*i);
}
%>
</body>
</html>

18
Output:

19
7. Write a Servlet program that accepts the age and name and
displays if the user is eligible for voting
or not.
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

/**
* Servlet implementation class VoterServ
*/
@WebServlet("/VoterServ")
public class VoterServ extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException,ServletException
{
//set response content type
res.setContentType("text/html");
//get printWrite obj
PrintWriter pw = res.getWriter();
//read form data from page as request parameter
String name = req.getParameter("name");
int age = Integer.parseInt(req.getParameter("age"));
if (age>=18)
{
pw.println("<font color='green' size='4'>"+name+" you are eligible to
vote</font>");
}
else
pw.println("<font color='red' size='4'>"+name+" you are not eligible
to vote</font>");
//add hyperlink to dynamic page
pw.println("<br><br><a href= 'Voting.html'>Home</a>");
//close the stream
pw.close();
}

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VoterApp</title>
</head>
<body>
<form action= "VoterServ" method="get">
20
<fieldset style="width:20%; background-color:#80ffcc">
<table>
<tr><td>Name</td><td><input type="text"
name="name"></td></tr>
<tr><td>Age</td><td><input type="text" name="age"></td></tr>
<tr><td></td><td><input type = "submit" value="check voting
eligibility"></td></tr>
</table>
</fieldset>
</form>
</body>
</html>

Output:

21
8. Write a program to adding 2 numbers using Java Servlets
<html>
<body>

<form action="AddServ" method="get">


First Number<input type="text" name="num1"><br>
Second Number<input type="text" name="num2"><br>
<input type="submit" value="Calculate">
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/AddServ")
public class AddServ extends HttpServlet {
public static void getData(int num1,int num2,PrintWriter pw)
{
pw.print("Sum Is "+(num1+num2));
}
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String a;int b;
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String n1=req.getParameter("num1");//will return value
String n2=req.getParameter("num2");
try {
int intValue = Integer.parseInt(n1);
int intValue2=Integer.parseInt(n2);
getData(intValue,intValue2,pw);
} catch (NumberFormatException e)
{
System.out.println("Not an Integer.");
pw.print("Not A Number");
}

pw.close();
}

22
}

Output:

23
9. Write a program to display a Hello World message in the Web
browser, display the hostname and Session-Id. Write JSP code using
HTML code.
<HTML>
<HEAD>
<TITLE>Hello Page</TITLE>
</HEAD>
<BODY>
<H2>Hello World!</H2>
<UL>
<%
response.setHeader("name", 5+"");
%>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
</UL>
</BODY>
</HTML>

24
10. Write a program using the JSP to enter the Name and Password
of a user and display the output on another JSP page.
<%@ 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>Registration Form</title>
</head>
<body>
<h1>Register Form</h1>
<form action="TestLogin" method="post">
<table style="with: 50%">
<tr>
<td>First Name</td>
<td><input type="text" name="first_name" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name" /></td>
</tr>
<tr>
<td>UserName</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
</table>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" /></form>
</body>
</html>

<%@ 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>Success Page</title>
</head>
<body>

25
<a><b>Welcome <% out.println(request.getParameter("first_name")+"
"+request.getParameter("last_name")); %></b></a><br>
<a><b>With UserID <% out.println(request.getParameter("username"));
%></b></a><br/>
<a><b>Password <% out.println(request.getParameter("password"));
%></b></a>

</body>
</html>

import java.io.*;

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

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

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// TODO Auto-generated method stub
String first_name = request.getParameter("first_name");
String last_name = request.getParameter("last_name");
String username = request.getParameter("username");
String password = request.getParameter("password");

if(first_name.isEmpty() || last_name.isEmpty() || username.isEmpty() ||


password.isEmpty() )
{
RequestDispatcher req =
request.getRequestDispatcher("BeforeLogin.jsp");
req.include(request, response);
}
else
{
RequestDispatcher req =
request.getRequestDispatcher("AfterLogin.jsp");
req.forward(request, response);
}
}
}

26
Output:

27
11. a) Write a program using JSP to calculate the sum of numbers
from 1 to 25.
b) Write a servlet to accept user name as input and reply with
greeting message.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Sum Of N Numbers</title>
</head>
<form action="SumofN.jsp" method="get">
<table style="with: 50%">
<tr>
<td>Enter Number</td>
<td><input type="text" name="num" /></td>
</tr>
</table>
<input type="submit" value="Calculate" />
</form>
<center><h1>
<%
try{
int n=Integer.parseInt(request.getParameter( "num"));
int s=0;
for(int i=1;i<=n;i++)
{
s=s+i;
}
out.println("From 1 To "+ n+" Sum Is "+s);
}
catch(Exception e)
{
out.println(e);
}
%></h1></center>
<body>
</body>
</html>

28
Output:

29
<html>
<body>
<form action="Hello">
Name:<input type="text" name="name"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello ";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
String name=request.getParameter("name");
out.println("<h1>" + message +name+ "!, Welcome to the page </h1>");
}

public void destroy() {


// do nothing.
30
}
}

Output:

31
12. Write a program to display the session ID, creation time, and the
last accessed time of the Web page. Using session.getID,
session.getCreationTime(), and session.getLastAccessedTime()

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;

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 javax.servlet.http.HttpSession;
@WebServlet("/SessionDemo")
public class SessionDemo extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


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

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


if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
}
32
else
{
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#e5f7c0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#eadf8c\">\n" +
"<th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
33
}

Output:

34
13. Write a program to display an error message to the user if an
exception occurs in the JSP page. In the JSP page, consider a null
string and find out the length of the string using length()method of
Java. Create an error handler to handle the exception thrown by
this JSP page.
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="Concat"/></form>

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


<%

String nm=request.getParameter("n1");
String nm2=request.getParameter("n2");

if(nm.length()==0)
{
nm=null;
nm.length();
}

if(nm2.length()==0)
{
nm2=null;
nm2.length();
}
String comb=nm+nm2;

out.print("Combination: "+comb);

%>

<%@ page isErrorPage = "true" %>

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

Exception is: <%= exception %>


35
36
14. Develop a Java Bean to process student marks and print his/her
result. Create a JSP to accept details
of Student name, Student Marks in Three subjects.
Using bean class verify the marks with the following validations
Students need to score marks >= 40 to pass each subject else FAIL
If the Total Marks > = 90, Print Grade S
If the Total Marks > = 75 & < 90, Print Grade A
If the Total Marks > = 60 & < 75, Print Grade B
If the Total Marks > = 50 & < 60, Print Grade C
If the Total Marks > = 40 & < 50, Print Grade D else FAIL
<html>
<head>
<title> Check Result</title>
</head>
<body>
<form action="ShowDetalis.jsp">
Name: <input type="text" name="name"/><br>
Subject 1:<input type="text" name="m1"/><br>
Subject 2:<input type="text" name="m2"/><br>
Subject 3: <input type="text" name="m3"/><br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

package axel;

import java.beans.JavaBean;
import java.io.Serializable;
@JavaBean
public class StudentDetails implements Serializable {
private static final long serialVersionUID = 1L;
private String name = null;
private double m1=0;
private double m2=0;
private double m3=0;
private double per=0;
private String res=null;
public void setName(String name){

this.name = name;
}
public void setM1(double m1)
{

37
if(m1<40)
this.res="Fail:Marks In Subject 1 Less Than 40";
this.m1=m1;
}
public void setM2(double m2)
{
if(res==null)
{
if(m2<40)
this.res="Fail:Marks In Subject 2 Less Than 40";
}
else
{

if(m2<40)
this.res=this.res+",Marks In Subject 2 Less Than 40";
}
this.m2=m2;
}
public void setM3(double m3)
{
if(res==null)
{
if(m3<40)
this.res="Fail:Marks In Subject 3 Less Than 40";
}
else
{
if(m3<40)
this.res=this.res+",Marks In Subject 3 Less Than 40";
}
this.m3=m3;
}
public void setPer(double total)
{

this.per=(total/300)*100;
}
public void setRes(String totPer)
{
double t2=Double.parseDouble(totPer);
if(this.res==null)
{
if(t2>=90)
{
System.out.print(t2);
this.res="Pass:With S Grade";
}

else if(t2>=75)
this.res="Pass:With A Grade";
else if(t2>=60)
this.res="Pass:With B Grade";
38
else if(t2>=50)
this.res="Pass:With C Grade";
else if(t2>=40)
this.res="Pass:With D Grade";
else
this.res="Fail:Total Percentage Less Than 40";
}
else
{
if(t2<40)
this.res=this.res+",Total Percentage Less Than 40";

}
}
public String getName(){
return this.name;
}
public double getM1()
{
return this.m1;
}
public double getM2()
{
return this.m2;
}
public double getM3()
{
return this.m3;
}
public double getPer()
{
return this.per;
}
public String getRes()
{
return this.res;
}
}

<html>
<head>
<title> Check Result</title>
</head>
<body>
<%
String name=request.getParameter("name");
double m1=Double.parseDouble(request.getParameter("m1"));
double m2=Double.parseDouble(request.getParameter("m2"));
double m3=Double.parseDouble(request.getParameter("m3"));
String per=String.valueOf(((m1+m2+m3)/300)*100);
%>
<jsp:useBean id = "students" class = "axel.StudentDetails">
<jsp:setProperty name = "students" property = "name" value ="<%=name %>"/>
39
<jsp:setProperty name = "students" property = "m1" value = "<%=m1 %>"/>
<jsp:setProperty name = "students" property = "m2" value = "<%=m2 %>"/>
<jsp:setProperty name = "students" property = "m3" value = "<%=m3 %>"/>
<jsp:setProperty name = "students" property = "per" value = "<
%=m1+m2+m3%>"/>
<jsp:setProperty name = "students" property = "res" value = "<%= per%>"/>
</jsp:useBean>

<p>Student First Name:


<jsp:getProperty name = "students" property = "name"/>
</p>

<p>Subject 1:
<jsp:getProperty name = "students" property = "m1"/>
</p>

<p>Subject 2:
<jsp:getProperty name = "students" property = "m2"/>
</p>
<p>Subject 3:
<jsp:getProperty name = "students" property = "m3"/>
</p>
<p>Percentage:
<jsp:getProperty name = "students" property = "per"/>
</p>
<p>Result:
<jsp:getProperty name = "students" property = "res"/>
</p>

</body>
</html>

Output:

40
41
15. create a Java Bean named Temperature that implements a
temperature converter from Celsius to Fahrenheit. Create a JSP to
accept the Celsius / Fahrenheit value from the user. Invoke Java
bean to Complete the Conversion process and print the Result.
<!DOCTYPE html>
<html>
<body>
<form action="Temp.jsp">
<input type="radio" name="radio1" value="Celsius To Farenheit" checked>Celsius To
Farenheit<br/>
<input type="radio" name="radio1" value="Farenheit To Celsius">Farenheit To
Celsius<br/>
<input type="text" name="temp"><br/>
<input type="submit" value="Convert"/>
</form>
</body>
</html>

package axel;
import java.io.*;
public class TempConv implements Serializable{
private static final long serialVersionUID = 1L;
private String scale;
private double temp;
public TempConv() {

}
public void setScale(String s) {
this.scale=s;
}
public void setTemp(double t) {
this.temp=t;
}
public String getScale() {
return this.scale;
}
public double getTemp() {
if(scale.equals("Celsius To Farenheit"))
temp=((temp/5)*9)+32;
else
temp=((temp-32)/9)*5;
return this.temp;
}
}

42
<!DOCTYPE html>
<html>
<body>
<%
String t=request.getParameter("radio1");
double temp=Double.parseDouble(request.getParameter("temp"));
%>
<jsp:useBean id = "conv" class = "axel.TempConv">
<jsp:setProperty name = "conv" property = "scale" value ="<%=t %>"/>
<jsp:setProperty name = "conv" property = "temp" value = "<%=temp %>"/>
</jsp:useBean>
<%
if(t.equals("Celsius To Farenheit")){%>
<jsp:getProperty name = "conv" property = "scale"/><br/>
<jsp:getProperty name = "conv" property = "temp"/><br/>
<%}else{%>
<jsp:getProperty name = "conv" property = "scale"/><br/>
<jsp:getProperty name = "conv" property = "temp"/><br/>
<%}%>
</body>
</html>
Output:

43
16. Create a User Interface to calculate Incometax based on the data
provided by the user. The UI needs
the Name of the Tax Payer, Income earned in the Year, Address etc.
Develop a Java bean class with the necessary logic to calculate Tax
Payable. Standard Deduction is 1,00,000 ( ie Subtract this amount
1,00,000 before calculating the taxable
amount)
Taxable Amount = Income Earned - Standard Deduction
If the Taxable amount < 1,00,000 - NO TAX
If the Taxable amount > 1,00,000 <= 5,00,000 - 10% Tax on Taxable
Amount
If the Taxable amount > 5,00,000 <=10,00,000 - 20% Tax on Taxable
Amount
If the Taxable amount > 10,00,000 - 30% Tax on Taxable Amount

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


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
</head>
<body>
<center><h1>Enter Income And Other Details</h1></center>
<form action="TaxPay.jsp">
Name :&nbsp;<input type="text" name="name"><br><br>
Address :&nbsp;<input type="text" name="address"><br><br>
Income :&nbsp;<input type="text" name="income"><br><br>
&nbsp;&nbsp;&nbsp;<input type="submit" value="Submit">
</form>
</body>
</html>

package axel;
import java.beans.JavaBean;
import java.io.*;
@JavaBean
public class TaxCalculator implements Serializable {
44
private static final long serialVersionUID = 1L;
private String name;
private double income;
private double tax;
private String addr;
public void setName(String name)
{
this.name=name;
}
public void setIncome(double income)
{
this.income=income;
}

public void setTax(double income)


{
double tax=0;
double taxAmount=0;
taxAmount=income-100000;
if(taxAmount<100000);
else if(taxAmount<500000)
tax=taxAmount*0.1;
else if(taxAmount<1000000)
tax=taxAmount*0.2;
else
tax=taxAmount*0.3;
this.tax=tax;
}
public void setAddr(String addr)
{
this.addr=addr;
}
public String getName()
{
return this.name;
}
public double getIncome()
{
return this.income;
}
public double getTax()
{
return this.tax;
}
public String getAddr()
{
return this.addr;
}
}

<html>
<head>
<title> Income Tax Department</title>
</head>

45
<body>
<center><h1>Income Tax Department</h1></center>
<center><h1>Goverment of India</h1></center>
<%
String name=request.getParameter("name");
double income=Double.parseDouble(request.getParameter("income"));
String addr=request.getParameter("address");
%>
<jsp:useBean id = "taxation" class = "axel.TaxCalculator">
<jsp:setProperty name = "taxation" property = "name" value ="<%=name %>"/>
<jsp:setProperty name = "taxation" property = "income" value = "<%=income
%>"/>
<jsp:setProperty name = "taxation" property = "tax" value = "<%=income %>"/>
<jsp:setProperty name = "taxation" property = "addr" value = "<%=addr %>"/>
</jsp:useBean>

<p> Name:
<jsp:getProperty name = "taxation" property = "name"/>
</p>

<p>Income:
<jsp:getProperty name = "taxation" property = "income"/>
</p>

<p>Tax:
<jsp:getProperty name = "taxation" property = "tax"/>
</p>
<p>Address:
<jsp:getProperty name = "taxation" property = "addr"/>
</p>
</body>
</html>

Output:

46
47
17. Write a program to display a login page to the user. The login
page should ask user to enter the account Id and pin number. The
account id and pin number should be compared with the data in
database, and should be validated. Display appropriate message to
the user after validating the user input to the login form.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Check">
Enter Id:<input type="text" name="id" placeholder="Enter Id"><br><br>
Enter Pin:<input type="password" name="pin" placeholder="Enter Pin"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;

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 java.sql.*;

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

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/login","root","axel");
boolean status=false;

48
Statement stmt=con.createStatement();
String id=request.getParameter("id");
String pin=request.getParameter("pin");
ResultSet rs=stmt.executeQuery("select * from users");
PrintWriter out=response.getWriter();
while (rs.next()) {
if(rs.getString(1).equals(id) && rs.getString(2).equals(pin))
{
out.print("Login Success");
status=true;
break;

}
if(status==false)
out.println("Wrong Credentials");
}
catch (Exception e) {
// TODO: handle exception
}
}

Output:

49
50
18. Write a program that uses the response.setHeader()method to
display the date. In addition, set the response header attribute and
utilize the JSP expression tag.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.net.URL"%>
<%@ page import="java.util.Date" %>
</head>
<!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>JSP Response setHeader</title>
</head>
<body>
<form>
<table>
<tr>
<td>Enter your Name :</td>
<td><input type="text" name="name" />
</td>
</tr>
<tr>
<tr>
<td></td>
<td><input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
<%
String nm = request.getParameter("name");
if (nm != null) {
out.println("The Header <b>" + nm + "</b> has been already set : "
+ response.containsHeader("Author")+"<br>");
response.setHeader("Author", nm);
out.println("Author : " + nm+"<br>");
out.println("The Header <b>" + nm + "</b> has been already set : "
);
}
%>
<%=response.containsHeader("Author") %>
<h3>
<% response.setHeader("Refresh", "6"); %>
51
Current date: <%= new Date() %>.
</h3>
</body>
</html>

Output:

52
19. Write a program to display the withdrawal status to the user. If
the account number is valid, display the withdrawal screen to the
user. The withdrawal screen should display the balance entered by
the user on the withdrawal status screen and ask the user to enter
the amount to be withdrawn. Display the balance to the user after
withdrawing the amount.
<%@ 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>Registration Form</title>
</head>
<body>
<h1>Register Form</h1>
<form action="TestLogin" method="post">
<table style="with: 50%">
<tr>
<td>ID</td>
<td><input type="text" name="id" /></td>
</tr>

</table>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" /></form>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Success Page</title>
</head>
<body>
<%=session.getAttribute("bal") %>
<form action="TestWithdraw">
<input type="text" name="inbal"><br>
<input type="submit" value="Withdraw">
</form>
53
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet("/TestLogin")
public class TestLogin extends HttpServlet {

private static final long serialVersionUID = 1L;

public void service(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=request.getSession();
PrintWriter out=response.getWriter();
String id = request.getParameter("id");

if(id.isEmpty()
)
{
RequestDispatcher req =
request.getRequestDispatcher("BeforeLogin.jsp");
req.include(request, response);
}
else
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/login","root","axel");
Statement stmt=con.createStatement();
ResultSet res=stmt.executeQuery("select accno,balance from
balance where accno='"+id+"'");
out.println(res);
while(res.next())
{
if(res.getString(1).equals(id))
{
session.setAttribute("id", res.getString(1));
session.setAttribute("bal", res.getFloat(2));
RequestDispatcher req =
request.getRequestDispatcher("AfterLogin.jsp");
54
req.forward(request, response);
break;
}
}
out.println("No Record");
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;

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

public void service(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=request.getSession();
PrintWriter out=response.getWriter();
String id = (String)session.getAttribute("id");
float inbal=Float.parseFloat(request.getParameter("inbal"));
float bal=(Float)session.getAttribute("bal");
float upbal=bal-inbal;

if(id.isEmpty())
{
RequestDispatcher req =
request.getRequestDispatcher("BeforeLogin.jsp");
req.include(request, response);
}
else if(inbal<=0 || inbal>bal) {

55
out.println("Insufficient Balance or Invalid Amount");
}
else
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/login","root","axel");
Statement stmt=con.createStatement();
stmt.executeUpdate("update balance set
balance="+upbal+"where accno='"+id+"'");
ResultSet res=stmt.executeQuery("select
accno,balance from balance where accno='"+id+"'");

while(res.next())
{
if(res.getString(1).equals(id))
{
session.setAttribute("id",
res.getString(1));
session.setAttribute("bal",
res.getFloat(2));
RequestDispatcher req =
request.getRequestDispatcher("AfterLogin.jsp");
req.include(request, response);
break;
}
}

} catch (SQLException | ClassNotFoundException e) {


// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}

Output:

56
57
20. Choose a table in the database and write an application that and
prints the number of records in the table with complete details –
using prepared statement.
22. Write an application that connects to a database through JDBC
and
(i) prints the names of all tables in the database,
(ii) for each table of the database prints its columns
23. Develop a Jdbc program to implement Insert, Delete, Update,
Search and Exit operations, based on
user choice (For example in the created table based on user choice,
you need to implement DML
operations).
import java.sql.*;
import java.util.Scanner;
public class DemoJdbc {
public static Connection getConnection(int sel_Db)
{
Connection con = null;

try {
if(sel_Db == 1)
{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/movies_det","root","8955");
}
else
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con
=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Gautam\\Desktop\\Java_Proj
ect\\JdbcExce\\db1.accdb");;
}
}catch (Exception e) {
System.out.println(e);
}
return con;

}
public static void main(String [] args) {
58
System.out.print("Select Databse From Below\n1)MySql\n2)Microsoft Access\n");
Scanner db=new Scanner(System.in);
int op=db.nextInt();
Connection con=getConnection(op);
Statement stmt=null;
try {
stmt = con.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
if(op==1)
{
stmt.execute("create table movies (Name VARCHAR(50), Release_Date
VARCHAR(50), Budget float, Movie_Genre VARCHAR(50));");
System.out.println("New Table Was Created In MySql DB(Note:Earlier No
Table Was There)");
}
else
{
stmt.executeUpdate("create table movies (Name VARCHAR(50), Release_Date
VARCHAR(50), Budget SINGLE, Movie_Genre VARCHAR(50))");
System.out.println("New Table Was Created In Access DB(Note:Earlier No
Table Was There)");
}

Menu.menu(con,stmt);

} catch (Exception e)
{
Menu.menu(con,stmt);
}
db.close();
}
}

import java.io.*;
import java.sql.*;
public class Menu {
public static void menu(Connection con,Statement stmt)
{
try
{
int op=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do
{
System.out.println("Enter The Operation\n1)Show All
Records\n2)Insert A Record\n3)Update\n4)Delete\n5)Search Record\n6)Show Tables Column
& List All Tables\n7)Do Rest And Exit ");
op=Integer.parseInt(br.readLine());
switch(op)

59
{
case 1:
{
Options.showRecords(stmt);
break;
}
case 2:
{
PreparedStatement ps=con.prepareStatement("insert
into movies values(?,?,?,?)");
Options.insertRecord(ps);
break;
}
case 3:
{
PreparedStatement ps=con.prepareStatement("update movies
set Name=?,Release_Date=?,Budget=?,Movie_Genre=? where Name=?");
Options.updateRecord(ps,stmt);
break;
}
case 4:
{
PreparedStatement ps=con.prepareStatement("delete from
movies where Name=?");
Options.deleteRecord(ps,stmt);
break;
}
case 5:
{
Options.searchRecord(stmt);
break;
}
case 6:
{
System.out.println("\n");
DatabaseMetaData metaData = con.getMetaData();
String[] types = {"TABLE"};
ResultSet tables = metaData.getTables(“movies_det”, null,
"%", types);
System.out.println("ColumnName" + " | " + "Datatype" + " |
" + "Columnsize" + " | " + "Decimaldigits" + " | " + "IsNullable" + " | " +
"Is_AutoIncrment");

System.out.println("_________________________________________________________________
___________");
while (tables.next())
{
System.out.println(tables.getString("TABLE_NAME"));
Options.getDetailsOfTable(metaData,
tables.getString("TABLE_NAME"));
System.out.println("");
}
System.out.println("\n");
break;

60
}

case 7:
{
System.out.println("Exiting");
for (int i = 0; i <50; i++)
{
System.out.print("-");
Thread.sleep(100);
}
System.out.println("Success");
stmt.close();
con.close();
System.exit(0);
}

}
while(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

import java.io.*;
import java.sql.*;
import java.util.Scanner;
public class Options {
public static void getDetailsOfTable(DatabaseMetaData metaData,String
tableName)
{

try
{
ResultSet columns = metaData.getColumns(null,null, tableName, null);
while(columns.next())
{
String columnName = columns.getString("COLUMN_NAME");
String datatype = columns.getString("DATA_TYPE");
String columnsize = columns.getString("COLUMN_SIZE");
String decimaldigits = columns.getString("DECIMAL_DIGITS");
String isNullable = columns.getString("IS_NULLABLE");
String is_autoIncrment = columns.getString("IS_AUTOINCREMENT");
System.out.println(columnName + " | " + datatype + " | " +
columnsize + " | " + decimaldigits + " | " + isNullable + " | " + is_autoIncrment);
}

61
}
catch (Exception e) {
e.printStackTrace();
}
}

public static void searchRecord (Statement stmt)


{
try
{
showRecords(stmt);
ResultSet rs;
int i=0;
System.out.println("Enter The Name of Movie You Want To Search");
String nm=new Scanner(System.in).nextLine();
rs=stmt.executeQuery("select * from movies where Name='"+nm+"'");
while(rs.next())
{
System.out.println(rs.getString(1)+" | "+rs.getString(2)+" |
"+rs.getFloat(3)+" | "+rs.getString(4)+"\n");
i++;
}
System.out.println("Total Records Fetched "+ i +"\n");
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void showRecords(Statement stmt)
{
ResultSet rs;
int i=0;
try
{
rs = stmt.executeQuery("select * from movies");
while(rs.next())
{
System.out.println(rs.getString(1)+" | "+rs.getString(2)+" |
"+rs.getFloat(3)+" | "+rs.getString(4)+"\n");
i++;
}
System.out.println("Total Records Fetched "+ i);
}
catch (SQLException e) {

e.printStackTrace();
}
}
public static void insertRecord(PreparedStatement ps)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do{
System.out.println("Enter Movie Name:");
String name=br.readLine();

62
System.out.println("Enter Release Date(Month):");
String rd=br.readLine();
System.out.println("Enter Budget:");
float bug=Float.parseFloat(br.readLine());
System.out.println("Enter Movie Genre:");
String gn=br.readLine();
try
{
ps.setString(1,name);
ps.setString(2,rd);
ps.setFloat(3,bug);
ps.setString(4,gn);
int i=ps.executeUpdate();
System.out.println(i+" Records Enterted");

System.out.println("Do you want to continue: y/n");


String s=br.readLine();
if(s.startsWith("n")){
break;
}
}catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
}while(true);
}
public static void deleteRecord(PreparedStatement ps,Statement stmt)
{
showRecords(stmt);
System.out.println("Enter The Movie Name From Above Records:");
String nm=new Scanner(System.in).nextLine();
try
{
ps.setString(1, nm);
int i=ps.executeUpdate();
System.out.println(i+ " Record Deleted");
}
catch (Exception e) {
e.printStackTrace();
}

}
public static void updateRecord(PreparedStatement ps,Statement stmt)
{
showRecords(stmt);
System.out.print("Enter The Name Of Movie Which You Want To Update:");
String oldName=new Scanner(System.in).nextLine();
System.out.print("Enter New Name");
String nm=new Scanner(System.in).nextLine();
System.out.print("Enter New Release Date");
String rd=new Scanner(System.in).nextLine();
System.out.print("Enter New Budget");
Float bg=new Scanner(System.in).nextFloat();
System.out.print("Enter New Movie Genre");
String gen=new Scanner(System.in).nextLine();

63
try
{
ps.setString(1,nm);
ps.setString(2,rd);
ps.setFloat(3,bg);
ps.setString(4,gen);
ps.setString(5, oldName);
int i=ps.executeUpdate();
System.out.println(i+" records updated");
}
catch (Exception e) {
e.printStackTrace();
}
}
}

64
65
21. Write an application that inserts numerical data into a table.
The application
(i) retrieves the values from the command line and
(ii) Apply ACID operations on the selected / created Table.
import java.sql.*;
import java.io.*;

public class Acid {


public static void main(String args[]){
try{
Connection con=null;

Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/movies_det","root","axel");
con.setAutoCommit(false);

PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


while(true){

int id=Integer.parseInt(args[0]);

System.out.println("enter name");
String name=br.readLine();

int salary=Integer.parseInt(args[1]);

ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();

System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit();
}
if(answer.equals("rollback")){
con.rollback();
}

System.out.println("Want to add more records y/n");

66
String ans=br.readLine();
if(ans.equals("n")){
break;
}

}
con.commit();
System.out.println("record successfully saved");

con.close();//before closing connection commit() is called


}catch(Exception e){System.out.println(e);}

}}

Output:

67
68
24. Develop a program to insert data into BLOB and CLOB type
columns in a table using JDBC.
<!DOCTYPE html>
<html>
<body>

<h1>Show File-select Fields</h1>

<h3>Show a file-select field which allows only one file to be chosen:</h3>


<form action="InsertFileDb" >
<label for="myfile1">Select a Text File 1:</label>
<input type="file" id="myfile1" name="f1" accept="text/plain"><br><br>
<label for="myfile2">Select a Text File 2:</label>
<input type="file" id="myfile2" name="f2" accept="text/plain"><br><br>
<label for="myfile3">Select a Text File 3:</label>
<input type="file" id="myfile3" name="f3" accept="text/plain"><br><br>
<label for="mypic1">Select a Image File 1:</label>
<input type="file" id="mypic1" name="f4" ><br><br>
<label for="mypic2">Select a Image File 2:</label>
<input type="file" id="mypic2" name="f5"><br><br>
<label for="mypic3">Select a Image File 3:</label>
<input type="file" id="mypic3" name="f6"><br><br>
<input type="submit">
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;

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

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

protected void service(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
String f1=request.getParameter("f1").toString();
String f2=request.getParameter("f2").toString();
String f3=request.getParameter("f3").toString();
String f4=request.getParameter("f4").toString();
69
String f5=request.getParameter("f5").toString();
String f6=request.getParameter("f6").toString();
PrintWriter out=response.getWriter();
try {
String success=BlobClob.insert(f1, f2, f3, f4, f5, f6);
if(success.equalsIgnoreCase("Done"))
{
out.println("Record Inserted");
out.println("<img src=\""+f4+"\" alt=\"Girl in a jacket\"
width=\"100\" height=\"50\">");
out.println("<img src=\""+f5+"\" alt=\"Girl in a jacket\"
width=\"100\" height=\"50\">");
out.println("<img src=\""+f6+"\" alt=\"Girl in a jacket\"
width=\"100\" height=\"50\">");
}
else
out.println("Record Insertion Error");

} catch (Exception e) {
// TODO Auto-generated catch block

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class BlobClob {
public static String insert(String f1,String f2,String f3,String f4,String
f5,String f6) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/blobclob";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "8955");
System.out.println("Connection established......");
//Inserting values
String query = "INSERT INTO articles_data(Name, Article, Logo) VALUES
(?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "First");

70
FileReader fileReader = new FileReader(f1);
pstmt.setClob(2, fileReader);
InputStream inputStream = new FileInputStream(f4);
pstmt.setBlob(3, inputStream);
pstmt.execute();
pstmt.setString(1, "Second");
fileReader = new FileReader(f2);
pstmt.setClob(2, fileReader);
inputStream = new FileInputStream(f5);
pstmt.setBlob(3, inputStream);
pstmt.execute();
pstmt.setString(1, "Third");
fileReader = new FileReader(f3);
pstmt.setClob(2, fileReader);
inputStream = new FileInputStream(f6);
pstmt.setBlob(3, inputStream);
pstmt.execute();
return "Done";

}
}

Output:

71
72
25. Using spring create the Student class with necessary properties.
The properties provide through the xml file.
package com.axel;
public class Student {
private String name;
private String usn;
public void setName(String name){
this.name = name;
}
public void getName(){
System.out.println("Your Name : " + this.name);
}
public void setOccupation(String usn)
{
this.usn=usn;
}
public void getOccupation()
{
System.out.println("Your USN: "+this.usn);
}
}

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


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id = "info" class = "com.axel.Student">


<property name = "name" value = "Ravi"/>
<property name = "usn" value = "1BM19MCA16"/>
</bean>

</beans>

package com.grk;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class PrintInfo {


public static void main(String[] args) {
ApplicationContext context = new

73
ClassPathXmlApplicationContext("Beans.xml");
Student obj = (Student) context.getBean("info");
obj.getName();
obj.getOccupation();
}
}

74
26. Using spring create the instance of dependent object (contained
object) then pass it as an argument of the main class constructor.
Consider student details scenario is Student HAS-A Address. The
Address class object will be termed as the dependent object
package com.axel;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
Students obj = (Students) context.getBean("e");
obj.show();

}
}

package com.axel;

public class Address {

private int roll;


private String age;
private String cgpa;

public Address(int roll, String age, String cgpa) {


super();
this.roll = roll;
this.age = age;
this.cgpa = cgpa;
}

public String toString(){


return "Roll No:"+roll+" "+"Age:"+age+" "+"CGPA:"+cgpa;
}
}

package com.axel;

public class Students {


75
private String usn;
private String name;
private Address address;

public Students() {System.out.println("def cons");}

public Students(String usn, String name, Address address) {


super();
this.usn = usn;
this.name = name;
this.address = address;
}

void show(){
System.out.println("USN:"+usn+" "+"Name:"+name);
System.out.println(address.toString());
}
}

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


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="a1" class="com.axel.Address">


<constructor-arg value="16" type="int"></constructor-arg>
<constructor-arg value="23"></constructor-arg>
<constructor-arg value="7.83"></constructor-arg>
</bean>

<bean id="e" class="com.axel.Students">


<constructor-arg value="1BM19MCA16" ></constructor-arg>
<constructor-arg value="Gautam Raj Kumawat"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>

</beans>

76
27. Create a JSP page that lets the user to supply a request
parameter indicating the background color. If no parameter is
supplied, a background color should be selected at random.

<%@page import="java.awt.Color"%>
<%@page import="java.util.Random"%>
<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>

<%
Random rand=new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
String myColor = request.getParameter("color");
if(myColor == null || myColor.equals("")){
myColor=Integer.toString(randomColor.getRGB());
}
else if(myColor.matches(".*\\d.*")){
RequestDispatcher rd =request.getRequestDispatcher("ColorError.jsp");
rd.forward(request, response);
}
%>

<BODY BGCOLOR="<%= myColor %>">

<H2 ALIGN="CENTER">Color Testing</H2>

<form>
<input type="text" name="color" size="25">
<p></p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>

</BODY>
</HTML>

77
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<b>Invalid Input!</b>
<a href="Color.jsp">Click Here To Go Back</a>
</body>
</html>

Output:

78
79
80

You might also like