Advance Java Lab - Pct/Co/31: Women'S Christian College, Chennai
Advance Java Lab - Pct/Co/31: Women'S Christian College, Chennai
Bonafide Certificate
This is to certify that this is the Bonafide record work done by Swaathira Ramachandran
(18PCT25) IV M.Sc. Computer Science and Technology for the Course ADVANCE JAVA
LAB (PCT/CO/31) during the academic year February 2022- June 2022, Semester VIII
INDEX
AIM:
To create a registration form.
ALGORITHM:
STEP1: Create a dynamic web project by clicking on file –> new -->Dynamic web project
STEP 2: Design an user interface for a registration form using html. (web content-> new -
>html) .
STEP 3: Create a servlet (Java resources->src->new->servlet) and assign the values
STEP 4: Using if statement check whether all the fields are filled
STEP 5: If the fields are not fill it will throw an errorstatement
STEP 6: If the fields are filled then print the result .
PROGRAM:
HTML:
<!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 bgcolor="#AABB76">
<form method="post" action="ex03_cls">
<h1><center><b>WEBINAR REGISTRATION</b></center></h1><br><br>
<hr>
<label>NAME:</label>
<input type="text" name="name" id="name"/><br>
<label>Reg No:</label>
<input type="text" name="reg" id="reg"/><br>
<label>DEPARTMENT:</label><br>
<input type="radio" name="r" id="r">CST</input><br>
<input type="radio" name="r" id="r">IT</input><br>
<input type="radio" name="r" id="r">BCA</input><br>
<input type="radio" name="r" id="r">BCom</input><br>
5
<label>Email id:</label>
<input type="text" name="mail" id="mail"/><br>
<label>Phone no:</label>
<input type="number" name="num" id="num"/><br><br>
<button>SUBMIT</button>
</form>
<style>
if(uname.isEmpty()||reg1.isEmpty()||dep.isEmpty()||email.isEmpty()||number.isEmpty
())
{
out.println("<html><body><b>FILL ALL THE
FIELDS</b><br></body><style> b{font-size:20px; color:red;} body{background-
color:#ccdd77;} </style></html>");
}
else
{
out.println("<html><body><b>REGISTRATION
SUCCESSFUL</b><br><b><var>Name</var>"+uname+"<br><var>Reg
No:</var>"+reg1+"<br><var>Department:</var>"+dep+"<br><var>Email:</var>"+email+"
<br><var>Phone no:</var>"+number+"</b></body><style> b{font-size:20px; color:red;}
body{background-color:#ccdd77;} </style></html>");
}
}
6
OUTPUT:
RESULT:
The output has been obtained successfully.
7
AIM:
To create a dynamic web application using J2EE to calculate the travel ticket price using
bean class.
ALGORITHM:
STEP 1: Create a new dynamic web project by clicking on file – >new->Dynamic web
project
STEP 2: Right click on WebContent to create new html file.
STEP 3: Design an user interface for a login form using html to get the users detail.
STEP 4: Create a servlet, assign the values to each variable and set the values in bean
STEP 5: The calculation is done in the bean class(java resource->src->new->class ).
STEP6: Then based on the mode of travel and number of passengers, send the control to the
next servlet page using RequestDispatcher.
STEP7: In the next servlet we display the price of the ticket based on user selection.
STEP8: Print the result .
PROGRAM:
HTML:
<!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 bgcolor="lavender">
<form method="post" action="ex08_cls"><center>
<h1>Travel Booking</h1><br>
<hr>
Name:<input type="text" name="name"><br><br>
Address:<input type="text" name="add"><br><br>
Phone.No:<input type="text" name="ph"><br><br>
8
Mode Of Travel:<br>
<input type="radio" name="r" value="bus">Bus</input><br><br>
<input type="radio" name="r" value="train">Train</input><br><br>
No. of passengers:<input type="number" name="pass"><br><br>
<button>Submit</button>
</form></center>
</body>
<style>
</style>
</html>
SERVLET1:
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name=request.getParameter("name");
String adr=request.getParameter("add");
String mob=request.getParameter("ph");
String mode=request.getParameter("r");
int num=Integer.parseInt(request.getParameter("pass"));
fourb f=new fourb();
f.getNum(num);
f.getOp(mode);
request.setAttribute("f-object",f);
if(mode.equals("bus"))
{
RequestDispatcher rd=request.getRequestDispatcher("buses");
rd.forward(request, response);
}
else
{
RequestDispatcher rd=request.getRequestDispatcher("trains");
rd.forward(request, response);
}
}
Servlet2: (bus)
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
fourb f=((fourb)request.getAttribute("f-object"));
int r=(int)f.calculate();
PrintWriter out=response.getWriter();
out.println("<html><body><b>Amount:</b>"+r+"</body><style>body{background-
color:cyan;} </style></html>");
}
9
Servlet3:
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
fourb f=((fourb)request.getAttribute("f-object"));
int r=(int)f.calculate();
PrintWriter out=response.getWriter();
out.println("<html><body><b>Amount:</b>"+r+"</body><style>body{background-
color:cyan;} </style></html>");
}
Javabean:
package fourbean;
publicclass fourb {
privateint num;
private String op;
privateint r;
public fourb()
{
num=0;
op="";
r=0;
}
publicvoid getNum(int num)
{
this.num=num;
}
publicint setNum()
{
return num;
}
publicvoid getOp(String op)
{
this.op=op;
}
public String setOp()
{
return op;
}
publicint calculate()
{
if(this.op.equals("bus")){
r=465*num;
return(r);
10
}
else
{
r=788*num;
return(r);
}
}
OUTPUT:
11
RESULT:
The output has been obtained successfully.
12
AIM:
To create a dynamic web application to check voter’s eligibility using cookies
ALGORITHM:
STEP 1: Create a new dynamic web project by clicking on file – >new->Dynamic web
project
STEP 2: Right click on WebContent to create new html file.
STEP 3: Design an user interface for a login form using html to get the users detail.
STEP 4: Get the username and age from the user
STEP 5: Create a bean class
STEP 6: Calculate the voter’s eligibility in the bean class
STEP 7: Create a servlet page using cookies
STEP 8: Print the result
PROGRAM:
HTML:
<!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 bgcolor="orange">
</body>
</html>
13
Servlet1:
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String n=request.getParameter("name");
String a=request.getParameter("age");
fourb f=new fourb();
f.getAge(a);
request.setAttribute("f-object",f);
Cookie ck1=newCookie("Username",n);
Cookie ck2=newCookie("Age",a);
response.addCookie(ck1);
response.addCookie(ck2);
RequestDispatcher rd=request.getRequestDispatcher("serv2");
rd.forward(request, response);
}
Servlet2:
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String s1,s2;
PrintWriter out=response.getWriter();
Cookie[] cks=request.getCookies();
if(cks!=null)
{
for(Cookie c:cks)
{
s1=c.getName();
s2=c.getValue();
out.println("<html><body><b>"+s1+"<br>"+s2+"</b></body><style>body{background-
color:pink;}</style><html>");
RequestDispatcher rd=request.getRequestDispatcher("serv3");
rd.include(request, response);
}
}
}
Servlet3:
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
fourb f=((fourb)request.getAttribute("f-object"));
String r=f.calcage();
PrintWriter out=response.getWriter();
14
out.println("<html><body><b>"+r+"</b></body><style>body{background-
color:pink;}</style><html>");
}
Java bean:
package fourbean;
publicclass fourb {
privateint age;
private String r;
public fourb(){
age=0;
r="";
}
publicvoid getAge(String age)
{
this.age=Integer.parseInt(age);
}
publicint setAge()
{
return(age);
}
public String calcage()
{
if(age >=18)
{
r="YOU ARE ELIGIBLE TO VOTE";
return r;
}
else
{
r="YOU ARE NOT ELIGIBLE TO VOTE";
return r;
}
}
}
15
OUTPUT:
RESULT:
The program has been obtained successfully
16
AIM:
To create a dynamic web application to display an user login page using session tracking and
error page
ALGORITHM:
STEP1: Create a new dynamic web project by clicking on file – >new->Dynamic web project
and generate the web.xml file by selecting deployment descriptor while creating dynamic
web project.
STEP 2: Design an user interface for a login form using html.
STEP 3: Right click on source file and click new – servlet to create a new servlet.
STEP 4: In Web.xml file initialize the parameters using <context param> tag. Mention the
<servlet name> and <servlet class>.
STEP 5:In the servlet compare the username and password given by the user and the
username and password initialized in the web.xml file. if they match
• then set the username as the session attribute and forward it to the other servlet
• else redirect response to a html file to print the error message
STEP 6: In the next servlet, get the session attribute and print the username using session
tracking
17
PROGRAM:
main.html:
<!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 bgcolor="lightpink">
<div class="main">
<center><h1>REGISTRATION FORM</h1></center>
</div>
<form method="post" action="serv">
<b>
USERNAME : <input type="text" name="use"><br><br>
PASSWORD : <input type="text" name="pass"><br><br>
<input type="submit" value="Login">
</b>
</form>
</body>
<style>
.main{
background-color:gray;
color:white;
margin-top:10px;
margin-bottom:10px;
padding-top:25px;
padding-bottom:25px;
}
input[type=submit]{
background-color: green;
color: white;
padding: 16px 40px;
margin: 10px 550px;
cursor: pointer;
}
</html>
web.xml:
18
serv.java:
package sess;
import java.io.IOException;
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;
/**
* Servlet implementation class serv
*/
@WebServlet("/serv")
publicclass serv extends HttpServlet {
privatestaticfinallongserialVersionUID = 1L;
19
/**
* @see HttpServlet#HttpServlet()
*/
public serv() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession sess=request.getSession();
String user=request.getParameter("use");
String pwd=request.getParameter("pass");
String u=getServletContext().getInitParameter("u1");
String p=getServletContext().getInitParameter("p1");
if(u.equals(user) && p.equals(pwd))
{
sess.setAttribute("tmp", user);
RequestDispatcher rd=request.getRequestDispatcher("login");
rd.forward(request,response);
}
else
response.sendRedirect("error.html");
login.java:
package sess;
import java.io.IOException;
import java.io.PrintWriter;
20
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;
/**
* Servlet implementation class login
*/
@WebServlet("/login")
publicclass login extends HttpServlet {
privatestaticfinallongserialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public login() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession sess=request.getSession();
PrintWriter out=response.getWriter();
out.println("<h1>Welcome "+sess.getAttribute("tmp")+"</h1>");
}
error.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
21
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<H1><center>ERROR : 404</center></H1>
</body>
</html>
OUTPUT:
22
23
RESULT:
The output has been obtained successfully.
24
AIM:
To create a dynamic web application using filters to perform currency conversion.
ALGORITHM:
STEP1: Create a new dynamic web project by clicking on file – >new->Dynamic web
project.
STEP 2: Design an user interface for a login form using html.
STEP 3: Right click on source file and click new- >filter, to create a filter class.
Use filter class to filter the user as ‘admin’.
STEP 4: While creating a new project click on the checkbox to create web.xml file. In
Web.xml file initialize the parameters using init param tag. Include the tags <filter name>,
<filter class>, <servlet name> and<servlet class>or<servlet mapping>.
STEP 5: To create a new servlet right click on source file and click new - >servlet.
STEP 6: Design an user interface to perform currency conversion using html and forward to
the next servlet.
STEP 7: In the next servlet perform currency conversions.
STEP 8: Print the result.
PROGRAM:
HTML:
<!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 bgcolor="#ffb3b3">
<center>
<font size="6" face="Fantasy" color="#003333">
<h2> *USERLOGIN* </h2>
</font>
<hr>
<font size="5" face="Monaco" color="#003333">
25
SERVLET 1:
package filt;
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;
/**
* Servlet implementation class ex13_cls
*/
@WebServlet("/ex13_cls")
public class ex13_cls extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ex13_cls() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
26
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
out.println(request.getAttribute("message"));
out.println("<html><body><center><form method='post'
action='serv2'><br><h1>CURRENCY CHANGER</h1><hr>Enter amount in Rs.<input
type='text' name='rs'><br><label>currencies</label><br><input type='radio' name='r'
value='dollar'>Dollar</input><br><input type='radio' name='r'
value='euro'>Euro</input><br><input type='radio' name='r'
value='dinar'>Dinar</input><br><input
type='submit'></form></center></body><style>body{background-
color:#ffaa80}</style></html> ");
SERVLET 2:
package filt;
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;
/**
* Servlet implementation class serv2
*/
@WebServlet("/serv2")
public class serv2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public serv2() {
super();
// TODO Auto-generated constructor stub
27
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
int a=Integer.parseInt(request.getParameter("rs"));
PrintWriter out=response.getWriter();
String op=request.getParameter("r");
int res=0;
if(op.equals("dollar"))
{
res=a*165;
out.println("<html><body><center><hr><h1>Dollar:"+res+"</h1></center></body>
<style>body{background-color:#ffffcc;}</style></html>");
}
else if(op.equals("euro"))
{
res=a*95;
out.println("<html><body><center><hr><h1>Euro:"+res+"</h1></center></body><
style>body{background-color:#ffffcc;}</style></html>");
}
else
{
res=a*225;
out.println("<html><body><center><hr><h1>Dinar:"+res+"</h1></center></body><
style>body{background-color:#ffffcc;}</style></html>");
}
}
FILTER:
28
package filt;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
/**
* Servlet Filter implementation class newfill
*/
@WebFilter("/newfill")
public class newfill implements Filter {
private FilterConfig filterconfig=null;
/**
* Default constructor.
*/
public newfill() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain
chain) throws IOException, ServletException {
String n=((HttpServletRequest)request).getParameter("name");
String msg=filterconfig.getInitParameter("message");
if(n.equals("admin"))
{
request.setAttribute("message",msg);
chain.doFilter(request, response);
}
else
{
System.out.println("Unauthorized user");
}
29
}
// TODO Auto-generated method stub
// place your code here
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterconfig=fConfig;
}
WEB.XML:
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>zzfilter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>f</filter-name>
<filter-class>filt.newfill</filter-class>
<init-param>
<param-name>message</param-name>
<param-value>Welcome!</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>f</filter-name>
<servlet-name>filt.ex13_cls</servlet-name>
</filter-mapping>
</web-app>
30
OUTPUT:
31
RESULT:
The output has been obtained successfully.
32
AIM:
To create a dynamic web application for temperature conversion using jsp.
ALGORITHM:
STEP 1: Create a new dynamic web project by clicking on file – >new->Dynamic web
project.
STEP 2: Right click on WebContent to create new html file.
STEP 3: Design an user interface for a login form using html.
STEP 4: Right click on source file and click JSP to create a JSP page.
STEP 5: Using the formula F=(C × 9/5) + 32 in JSP calculate the temperature.
STEP 6: Design an user interface to perform Temperature conversion using html and
forward to JSP.
STEP 7: Print the result.
PROGRAM:
Tc.html
<!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 bgcolor="skyblue">
<center>
<form action="temp.jsp">
<h1>TEMPERATURE CONVERTER</h1>
Value:<input type="text" name="cel"><br>
<input type="radio" name="r" value="cel">Celcius</input>
<input type="radio" name="r" value="far">Farenheit</input>
<button>convert</button>
</form>
</center>
33
</body>
</html>
temp.jsp:
<%@ 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>Insert title here</title>
</head>
<body bgcolor="skyblue">
<%
String c=request.getParameter("cel");
String op=request.getParameter("r");
if(op.equals("far")){
float t=Float.parseFloat(c);
float f=32+9*t/5;
out.println("Farenheit:"+f);
}
else{
float t=Float.parseFloat(c);
float f=(t-32)*5/9;
out.println("Celcius:"+f);
}%>
</body>
</html>
34
OUTPUT:
35
RESULT:
The output has been obtained successfully.
36
AIM:
To create a dynamic web application for user login using JSP and Java Bean.
ALGORITHM:
STEP 1: Create a new project by clicking on File -> New -> Dynamic Project.
STEP 2: Click on the Java Resource -> Right click on src -> New -> JSP.
STEP 3: Enter the code for the login page.
STEP 4: Now right click on the src -> New -> Class.
STEP 5: Enter the code for bean class. Initialize the parameters and set the password in
web.xml.
STEP 6: If the user password matches with the admin password login gets successful. Else it
shows a Login Unsuccessful Message.
PROGRAM:
Main.jsp
s.jsp:
bbb.java:
38
package abc;
}
else
{
res=1;
return res;
}
}
}
39
OUTPUT:
40
41
RESULT:
The required output has been obtained successfully.
42
AIM:
To develop a dynamic web application for maintaining bank details using JDBC.
ALGORITHM:
Database creation in SQL Server Management: Note the server name while opening the
SQL server
1. Right click on the folder Database -> New database -> Finish.
2. Right click on table folder ->New table. Insert the column names and its data types in
the table shown.
3. Right click on the created table -> Open table -> Enter data and save it.
JSP File:
6. Go to Java Resource -> Right click on Src -> JSP.
43
7. Enter the JSP code to design the User Interface Page to perform various Bank
Operations.
PROCEDURE:
STEP 1: Start the program by creating the HTML and JSP File for the Bank application.
STEP 2: Create a database table with required fields in sql server management.
STEP 3: Create a servlet class to perform Creating a New Bank Account, Withdrawal
and Deposit the amount and it's transactions in the database, and to view and delete the
records in the database.
STEP 4:Give the mapping to the pages correctly. Now save the Web Project and execute
it.
PROGRAM:
First.html:
</html>
Conn_cls.java:
package conn_pkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.lang.String;
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 conn_cls
*/
@WebServlet("/conn_cls")
public class conn_cls extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public conn_cls() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
try{
java.sql.Connection con;
45
try{
Class.forName("sun.jdbc.odbc.jdbcOdbcDriver");
}
catch(Exception e){}
con=DriverManager.getConnection("jdbc:odbc:eclipse-cst");
Statement st=con.createStatement();
String acc=request.getParameter("acc");
String na=request.getParameter("na");
String gen=request.getParameter("gen");
String dt=request.getParameter("dt");
String em=request.getParameter("em");
String phn=request.getParameter("phn");
String add=request.getParameter("add");
String cty=request.getParameter("cty");
int pin=Integer.parseInt(request.getParameter("pin"));
int bal=Integer.parseInt(request.getParameter("bal"));
String str="insert into accnt
(accno,name,gender,dob,email,phno,addr,city,pin,bal) values (" + acc + ",'" + na
+"','"+gen+"','"+dt+"','"+em+"','"+phn+"','"+add+"','"+cty+"',"+pin+","+bal+")";
st.executeUpdate(str);
out.println("Account Created");
out.println("<br><a href=\"options.jsp\" >TRANSACTIONS</a>");
}
catch(SQLException e)
{
out.println("Caught"+e);
}
}
}
Options.jsp:
</html>
Withdrw.jsp:
Wdrw_cls.java:
package wdrw_pkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 wdrw_cls
*/
@WebServlet("/wdrw_cls")
public class wdrw_cls extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
47
public wdrw_cls() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
String acc=request.getParameter("acc");
int pi=Integer.parseInt(request.getParameter("pi"));
int amt=Integer.parseInt(request.getParameter("amt"));
try{
java.sql.Connection con;
try{
Class.forName("sun.jdbc.odbc.jdbcOdbcDriver");
}
catch(Exception e){}
con=DriverManager.getConnection("jdbc:odbc:eclipse-cst");
Statement st=con.createStatement();
String str="select * from accnt where accno="+acc+"";
ResultSet rs=st.executeQuery(str);
while(rs.next())
{
String p=rs.getString(9);
String q=rs.getString(10);
int b=Integer.parseInt(q);
int pt=Integer.parseInt(p);
if(pi==pt)
{
if(amt<b)
{
int bn=b-amt;
str="update accnt set bal="+bn+" where
accno="+acc+"";
st.executeUpdate(str);
48
out.println("REMAINING
BALANCE"+bn);
}
else
out.println("NOT ENOUGH
BALANCE");
}
else
out.println("INCORRECT PIN");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
out.println("<br><a href=\"options.jsp\" >TRANSACTIONS</a>");
}
}
Deposit.jsp:
Dep_cls.java:
package dep_pkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
49
import java.sql.SQLException;
import java.sql.Statement;
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 dep_cls
*/
@WebServlet("/dep_cls")
publicclass dep_cls extends HttpServlet {
privatestaticfinallongserialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public dep_cls() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
String acc=request.getParameter("acc");
int pi=Integer.parseInt(request.getParameter("pi"));
int amt=Integer.parseInt(request.getParameter("amt"));
try{
java.sql.Connection con;
try{
Class.forName("sun.jdbc.odbc.jdbcOdbcDriver");
}
catch(Exception e){}
con=DriverManager.getConnection("jdbc:odbc:eclipse-cst");
50
Statement st=con.createStatement();
String str="select * from accnt where accno="+acc+"";
ResultSet rs=st.executeQuery(str);
while(rs.next())
{
String p=rs.getString(9);
String q=rs.getString(10);
int b=Integer.parseInt(q);
int pt=Integer.parseInt(p);
if(pi==pt)
{
int bn=b+amt;
str="update accnt set bal="+bn+" where
accno="+acc+"";
st.executeUpdate(str);
out.println("REMAINING
BALANCE"+bn);
}
else
out.println("INCORRECT PIN");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
out.println("<br><a href=\"options.jsp\" >TRANSACTIONS</a>");
}
View.jsp:
Vw_cls.java:
package vw_pkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 vw_cls
*/
@WebServlet("/vw_cls")
public class vw_cls extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public vw_cls() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
52
while(rs.next())
{
String acn=rs.getString(1);
String na=rs.getString(2);
String gen=rs.getString(3);
String dob=rs.getString(4);
String em=rs.getString(5);
String ph=rs.getString(6);
String add=rs.getString(7);
String cty=rs.getString(8);
String p=rs.getString(9);
String bal=rs.getString(10);
int pt=Integer.parseInt(p);
if(pi==pt)
{
out.println("ACCOUNT DETAILS <br><br>
Account Number : "+acn+"<br>Name : "+na+"<br>Gender : "+gen+
"<br>DOB : "+dob+"<br>Email :
"+em+"<br>Phone Number : "+ph+"<br>Address : "+add+
"<br>City : "+cty+"<br>Balance:
"+bal);
}
else
out.println("INCORRECT PIN");
}
out.println("<br><a href=\"options.jsp\"
>TRANSACTIONS</a>");
}
catch(SQLException e)
{
e.printStackTrace();
53
}
}
}
Del.jsp:
Del_cls.java:
package del_pkg;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 del_cls
*/
@WebServlet("/del_cls")
public class del_cls extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
54
*/
public del_cls() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
String acc=request.getParameter("acc");
int pi=Integer.parseInt(request.getParameter("pi"));
try{
java.sql.Connection con;
try{
Class.forName("sun.jdbc.odbc.jdbcOdbcDriver");
}
catch(Exception e){}
con=DriverManager.getConnection("jdbc:odbc:eclipse-cst");
Statement st=con.createStatement();
String str="select * from accnt where accno="+acc+"";
ResultSet rs=st.executeQuery(str);
while(rs.next())
{
String p=rs.getString(9);
int pt=Integer.parseInt(p);
if(pi==pt)
{
str="delete from accnt where
accno="+acc+"";
st.executeUpdate(str);
out.println("ACCOUNT DELETED");
}
else
55
out.println("INCORRECT PIN");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
out.println("<br><a href=\"options.jsp\" >TRANSACTIONS</a>");
}
}
OUTPUT:
56
57
58
59
RESULT:
AIM:
To develop a dynamic web application for User login using Struts
ALGORITHM:
Step 1: Create a dynamic web project
Step 2 : Copy the jar files and paste it in the WEB_INF >lib
asm-3.3.jar
asm-common-3.3.jar
asm-tree-3.3.jar
commons-fileupload-1.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
commons-logging-api-1.0.5.jar
freemaker-2.3.19.jar
javaassist-3.11.0.GA.jar
log4j-1.2.17.jar
ognl-3.0.6.jar
struts-core-2.3.15.1.jar
xwork-core-2.3.15.1.jar
Step 3 : Create a JSP file named Index.jsp to get the name from the user.
Step 4 : Create a JSP file to print the message and along with the user name.
Step 5 : Create an action class with execute() method.
Step 6 : In web.xml include the filter code for configuration.
Step 7 : Create a folder named classes in WEB-INF.
Step 8 : Create struts.xml in classes and declare an action tag within it.
Step 9 : Declare a result tag if the result is success then displayed hello.jsp page with the
entered name.
Step 10 : Execute the index.jsp to view the result.
61
PROGRAM:
Struts_cls.java:
package struts_pkg;
public class struts_cls {
private String name;
public String execute() throws Exception{
return "success";
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
Index.jsp:
<%@ 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>Insert title here</title>
</head>
<body>
<form action="hello">
<label for="name">Enter your name</label><br>
<input type="text" name="name"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Hello.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>
62
Web.xml:
<?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/w
eb-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>struts</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-
class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Struts.xml:
OUTPUT:
RESULT:
The output has been executed successfully.
64
AIM:
To develop a dynamic web application to connect database using hibernate.
ALGORITHM:
Instruction for creating Odbc connection:
1. Server: CST-14 -> Connect -> Right click on the folder database ->
New database ->swaathi -> finish.
2. In database swaathi, Right click on table folder -> New table -> login -> the table
columns names are asked -> give the names and save.
3. Close the table and right click on the created table(dbo.login) -> open table ->
enter few values on the table and save it.
1. Copy the JAR Files from the folder -> web content -> WEB-INF ->lib->paste.
Creating files in the Eclipse platform:
Hibcls.java:
65
Java resource -> src -> New -> class ->(package: hib, class: hibcls).
First.java [servlet]:
Java resource -> src -> New ->Servlet -> (package:hib, servlet:first).
PROCEDURE:
STEP 1: Create a new project by clicking on file – >new->Dynamic web project
STEP 2: Import the required hibernate JAR files to WEB-INF/lib folder.
STEP 3: Create a database table with required fields in sql server management.
STEP 4: Create a persistent class and the configuration file to perform hibernate
functions.
STEP 5: Create a servlet to insert, update and delete the records in the database, and
retrieve the records to view the records in the database.
STEP 6: Stop the program.
PROGRAM:
html:
hibcls.hb.xml:
66
<hibernate-mapping>
<class name="hib.hibcls" table="login">
<id name="phnum" column="phnum" type="int"></id>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:odbc:demo</property>
<property name="connection.username">CST-14</property>
<property name="connection.password"></property>
Bean class:
package hib;
phnum=0;
password="";
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setPassword(String password)
{
this.password=password;
}
public String getPassword()
{
return password;
}
public void setPhnum(int phnum)
{
this.phnum=phnum;
}
public int getPhnum()
{
return phnum;
}
servlet:
package hib;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
68
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* Servlet implementation class first
*/
@WebServlet("/first")
public class first extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public first() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
int num=Integer.parseInt(request.getParameter("num"));
PrintWriter out=response.getWriter();
String op=request.getParameter("r");
if(op.equals("insert")){
HttpSession sess=request.getSession(true);
try{
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.getCurrentSession();
Transaction tx = session.beginTransaction();
hibcls hc = new hibcls();
hc.setName(name);
hc.setPassword(pwd);
hc.setPhnum(num);
session.save(hc);
System.out.println("connection success");
69
tx.commit();
out.println("connection success");
/*Configuration conf=new Configuration().configure();
SessionFactory sf=conf.buildSessionFactory();
Session ses=null;
ses=sf.openSession();
Transaction trans=null;
trans=ses.beginTransaction();
hibcls h=new hibcls();
System.out.println("connection success");
h.setName(name);
h.setPwd(pwd);
h.setNum(num);
ses.save(h);
System.out.println("connection success");
ses.getTransaction().commit();
//trans.commit();
System.out.println("connection success");*/
System.out.println("\n Details added");
} catch(HibernateException e){
System.out.println(e.getMessage());
System.out.println("error");
}
//out.println("success");
//response.sendRedirect("ins.jsp");
}
if(op.equals("view")){
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s1 = sf.openSession();
String SQL_QUERY = "from hibcls";
List<hibcls> l = s1.createQuery(SQL_QUERY).list();
for(int i =0;i<l.size();i++) {
hibcls hc = (hibcls) l.get(i);
out.println("Name :"+hc.getName());
System.out.print("Password :"+hc.getPassword());
System.out.println("Ph-num :"+hc.getPhnum());
}
s1.close();
//response.sendRedirect("nview.jsp?pnum="+num);
}
if(op.equals("delete"))
{
}
catch(Exception e){
System.out.print("error");
}
}
if(op.equals("modify"))
{
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s1 = sf.openSession();
Transaction tx = s1.beginTransaction();
OUTPUT:
HTML INSERT:
71
SQL INSERTED:
72
DELETE:
RESULT:
The output has been executed successfully.
73
74
75
76