Advance Java Lab File
Advance Java Lab File
1
MAHILA ENGINEERING COLLEGE, AJMER
Department: Computer Engineering
Program: Computer Science & Engineering
To facilitate and provide state-of-the-art facilities to women technocrats and faculty- to create an environment
where novel ideas blossom, research flourishes and becomes the knowledge house of tomorrow's leaders and
innovators.
Mission of Department:
To transfer fundamental knowledge on various subject areas and develop capability to analyze and solve
new problems.
To provide state of the art laboratory facilities and exposure to practical aspects of various computer
engineering principles and inculcate ability to analyze, design, test and implement solutions to various
problems in the field of computer engineering.
To provide opportunities to the students for improving interpersonal skills and holistic development, so
they become professionally competitive and responsible citizen.
2
To provide ample opportunities for training and placement
TABLE OF CONTENTS
3
7. WAP in JAVA to Design JSP. 21
Program No – 1
import java.awt.*;
import java.applet.*;
public class apletdemo2 extends Applet {
String msg;
// set the foreground and background colors. public void init()
{setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed. public void start()
{
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g)
{
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}
4
HTML Program to Show Applet Class
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "apletdemo2.class" width = "320" height = "120"></applet>
<hr>
</html>
OUTPUT:
5
Program No – 2
import java.awt.*;
import javax.swing.*;
public class marksheet
{
public static void main(String[] args)
{
JFramejf =new JFrame("Marks Sheet");
//Title Student Marks
JLabel jltitle1 = new JLabel();
jltitle1.setBounds(150,10,200,20); //L-250,T-50,W-250,H-30
jltitle1.setText("Student Marks");
//Name
JLabeljlname = new JLabel();
jlname.setBounds(50,40,250,20); //L-50,T-150,W-250,H-30
jlname.setText("Name");
JTextFieldjtname = new JTextField();
jtname.setBounds(250,40,250,20); //L-250,T-150,W-250,H-30
//Age
JLabeljlage = new JLabel();
jlage.setBounds(50,70,250,20); //L-50,T-200,W-250,H-30
jlage.setText("Age");
JTextFieldjtage = new JTextField();
6
jtage.setBounds(250,70,100,20); //L-250,T-200,W-100,H-30
//Title Marks
JLabel jltitle2 = new JLabel();
jltitle2.setBounds(150,100,250,20); //L-320,T-250,W-250,H30
jltitle2.setText("Marks Obtained");
//Hindi
JLabel jlm1 = new JLabel();
jlm1.setBounds(50,130,200,20); //L-50,T-250,W-250,H-30
jlm1.setText("Hindi");
JTextField jtm1 = new JTextField();
jtm1.setBounds(250,130,100,20); //L-250,T-250,W-100,H-30
//English
JLabel jlm2 = new JLabel();
jlm2.setBounds(50,160,200,20); //L-50,T-350,W-200,H-30
jlm2.setText("English");
JTextField jtm2 = new JTextField();
jtm2.setBounds(250,160,100,20); //L-250,T-350,W-100,H-30
//Maths
JLabel jlm3 = new JLabel();
jlm3.setBounds(50,190,200,20); //L-50,T-250,W-200,H-30
jlm3.setText("Maths");
JTextField jtm3 = new JTextField();
jtm3.setBounds(250,190,100,20); //L-250,T-250,W-100,H-30
//Calculate Button
JButtonjbcalc = new JButton();
jbcalc.setBounds(150,220,100,20); //L-250,T-450,W-150,H-30
jbcalc.setText("Calculate");
jbcalc.setBackground(Color.RED);
//Title Result
JLabel jltitle3 = new JLabel();
7
jltitle3.setBounds(170,250,200,20); //L-320,T-500,W-200,H30
jltitle3.setText("Result");
JLabeljltotal = new JLabel();
jltotal.setBounds(50,280,200,20); //L-50,T-550,W-200,H-30
jltotal.setText("Total");
JTextFieldjttotal = new JTextField();
jttotal.setBounds(250,280,100,20); //L-320,T-550,W-100,H-30
jttotal.setEnabled(false);
JLabeljlper = new JLabel();
jlper.setBounds(50,310,200,20); //L-50,T-600,W-200,H-30
jlper.setText("Percentage");
JTextFieldjtper = new JTextField();
jtper.setBounds(250,310,100,20); //L-250,T-600,W-100,H-30
jtper.setEnabled(false);
JLabeljlres = new JLabel();
jlres.setBounds(50,340,200,20); //L-50,T-750,W-250,H-30
jlres.setText("Result");
JTextFieldjtres = new JTextField();
jtres.setBounds(250,340,100,20); //L-250,T-650,W-100,H-30
jtres.setEnabled(false);
jf.add(jltitle1);
jf.add(jltitle2);
jf.add(jltitle3);
jf.add(jlname);
jf.add(jlage);
jf.add(jtname);
jf.add(jtage);
jf.add(jlm1);
jf.add(jlm2);
jf.add(jlm3);
8
jf.add(jtm1);
jf.add(jtm2);
jf.add(jtm3);
jf.add(jbcalc);
jf.add(jltotal);
jf.add(jlper);
jf.add(jlres);
jf.add(jltitle3);
jf.add(jttotal);
jf.add(jtper);
jf.add(jtres);
jf.setBounds(300,200,550,450);
jf.setLayout(null);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT:
9
Program No – 3
10
Program No – 4
import java.sql.*;
class mysqlcon
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/stdmarks",
"root", "root");
PreparedStatementps = con.prepareStatement("select * from
stddata where perc > 60");
ResultSetrs = ps.executeQuery(); //execute
System.out.println("Students having marks > 60 are:");
while(rs.next())
System.out.println(rs.getString(1));
con.close();
}
catch(Exception e)
{
System.out.println("Error" + e.toString());
11
}
}
}
OUTPUT:
12
Program No- 5
MyJDBC.java
import java.sql.*;
import java.util.Scanner;
public class MyJDBC {
private static Scanner scanner;
public static void main(String[] args) throws SQLException, ClassNotFoundException
//throws SQLException and ClassNotFoundException due to connectivity of SQL(JDBC)
{
student s = new student();//object of type student with name as "s".
int Choice=0;
do {
System.out.println("Select an option\n1-Registration\n2-Update\n3-delete\n4-Search\n5-
Exit");
scanner = new Scanner(System.in);
Choice = scanner.nextInt();
switch (Choice) {
case 1:
s.get_student_details();//calls the method get_student_details from the student class
s.insert_details();//calls the method insert_details from the student class
break;
case 2:
s.update_student_name();//calls the method update_student_name from the student
13
class
break;
case 3:
s.delete_student_record();//calls the method delete_student_record from the student
class
break;
case 4:
s.search_details();//calls the method search_details from the student class
break;
case 5:
System.out.println("Exiting the Application");//exits the application
break;
default:
System.out.println("Choose a valid option");//in case of an invalid input(other than
1,2,3,4 and 5)
}
}while(Choice!=5);
}
}
student.java
import java.sql.*;
import java.util.Scanner;
public class student {
String name;
int id;
private Scanner input;
private Scanner input2;
private Scanner input3;
private Scanner input4;
public void get_student_details()//gets the student details such as name and ID
14
{
input = new Scanner(System.in);
System.out.println("Enter your name:");
name=input.nextLine();//gets ur name
System.out.println("Enter your id:");
id=input.nextInt();//gets user ID
}
public void insert_details() throws SQLException, ClassNotFoundException//method to insert
the details of student
{
dbconnection connection=new
dbconnection("jdbc:mysql://localhost:3306/jdbc","shikha","password");//creates an object of
type dbconnection class with name connection.name of the database id jdbc-1,user id is root and
password is basketball30.
Connection con=connection.getConnection();//establish the connection with the database
"jdbc-1"
String sql="insert into people values(?,?);";//sql statement for inserting the values given by
the user in the table people.
PreparedStatementstmt=con.prepareStatement(sql);
stmt.setInt(1,id);//map the first ? from the sql statement to the id
stmt.setString(2,name);//map the first ? from the sql statement to the name
stmt.execute();//execute the SQL statement
System.out.println("Record inserted Successfully");
connection.closeConnection(con,stmt);//close the dbconnection with the method
closeConnection in the dbconnection class
}
public void update_student_name() throws SQLException,ClassNotFoundException//method
to update the details of student
{
dbconnection connection=new
15
dbconnection("jdbc:mysql://localhost:3306/jdbc","shikha","password");//refer line 16
Connection con=connection.getConnection();//refer line 17
input2 = new Scanner(System.in);
System.out.println("Enter your id");
id=input2.nextInt();//gets student ID from the user
System.out.println("Enter your corrected name");
String cname=input2.next();//gets Student name from the user
String sql="update people set first_name=? where id=?;";//sql statement to update the
values in the table people.
PreparedStatementstmt=con.prepareStatement(sql);
stmt.setString(1,cname);//refer to line 21
stmt.setInt(2,id);//refer to line 20
int i = stmt.executeUpdate();
if(i>0)//if valid record
System.out.println("Record updated successfully");
else//invalid record or record not found
System.out.println("No such Record found");
connection.closeConnection(con,stmt);//refer line 24
}
public void delete_student_record() throws SQLException, ClassNotFoundException//
method to delete the data record of the particular student
{
dbconnection connection=new
dbconnection("jdbc:mysql://localhost:3306/jdbc","shikha","password");//refer line 16
Connection con=connection.getConnection();//refer line 17
input4 = new Scanner(System.in);
System.out.println("Enter your id:");
id=input4.nextInt();//gets StudentID from the user
String sql="delete from people where id=?;";//sql statement for deleting the record in people
where id=ID given by user in line above.
16
PreparedStatementstmt=con.prepareStatement(sql);
stmt.setInt(1,id);//refer line 20
int i=stmt.executeUpdate();
if(i>0)//if valid record
{
System.out.println("Record deleted Successfully");
}//if invalid record
else
System.out.println("Record not found");
connection.closeConnection(con,stmt);//refer line 24
}
public void search_details() throws SQLException, ClassNotFoundException //method to
search the details of the particular student
{
dbconnection connection=new
dbconnection("jdbc:mysql://localhost:3306/jdbc","shikha","password");//refer line 16
Connection con=connection.getConnection();//refer line 17
input3 = new Scanner(System.in);
System.out.println("Enter the id:");
id=input3.nextInt();//gets StudentID from the user
String sql="select * from people where id=?;";//sql Statement for selecting the data where
id=StudentID given by user in line above.
PreparedStatement
stmt=con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCU
R
_UPDATABLE);
stmt.setInt(1,id);//refer line 20
ResultSetrs=stmt.executeQuery();
if(rs.next()==false)//if no record is there
System.out.println("There is no such record");
else//if a valid record exist
17
{
rs.previous();
while (rs.next())
{
System.out.println(rs.getInt(1) + rs.getString(2));//prints the record of the StudentID
entered
}
}
connection.closeConnection(con,stmt);//refer line 24
}
}
dbconnection.java
import java.sql.*;
public class dbconnection {
String url;//url of the database in the local computer or localhost which is present in MySQL
with
name as jdbc-1
String user;//user ID of MySQL in the local computer
String password;//password of MySQL
dbconnection(String url,Stringuser,String password)//constructor of dbconnection
{
this.url=url;
this.user=user;
this.password=password;
}
public Connection getConnection() throws ClassNotFoundException, SQLException//method
to establish connection with the database. Would return Connection which could be used in the
class Student while creating the object of dbconnection to establish conneection
{
Connection con=null;
Class.forName("com.mysql.cj.jdbc.Driver");//name of the Driver
18
con=DriverManager.getConnection(url,user,password);//creating the connection with the
mentioned url,user,password
System.out.println("Connection established");
return con;//would return the connection
public void closeConnection(Connection con,PreparedStatementstmt) throws
SQLException//method to close the connection
{
stmt.close();//closes the SQL statement
con.close();//closes dbconnection
System.out.println("Connection is closed");}
}
Output:
19
Program No – 6
Client-side program:
import java.net.*;
import java.io.*;
public class TCPclient
{
public static void main(String[] args) throws IOException
{
Socket s = new Socket("localhost",4999);
PrintWriter pr = new PrintWriter(s.getOutputStream());
pr.println("Greetings from client");
pr.flush();
InputStreamReader in = new InputStreamReader(s.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
System.out.println("Server: " + str);
}
}
Server-side program:
import java.net.*;
import java.io.*;
public class TCPserver
{
20
public static void main(String[] args) throws IOException
{
ServerSocket ss = new ServerSocket(4999);
Socket s = ss.accept();
System.out.println("client connected");
InputStreamReader in = new InputStreamReader(s.getInputStream());
BufferedReader bf = new BufferedReader(in);
String str = bf.readLine();
System.out.println("client : " + str);
PrintWriter pr = new PrintWriter(s.getOutputStream());
pr.println("Greetings from Server");
pr.flush();
}
}
OUTPUT:
2)Write a client server program in java to input a string on the client side and show on
theserver side.
21
Client-side program:
import java.net.Socket;
import java.io.*;
public class EchoClient {
public static void main(String[] args) {
//TODO Auto-generated mehod stub
try
{
System.out.println("Client started");
Socket soc = new Socket("localhost", 9806);
BufferedReaderuserInput = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a string");
String str = userInput.readLine();
PrintWriter out = new PrintWriter(soc.getOutputStream() , true);
out.println(str);
BufferedReader in = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
System.out.println(in.readLine());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Server-side program:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
22
public class EchoServer {
public static void main(String[] args) {
//TODO Auto-generated method stub
try
{
System.out.println("Waiting for client ......");
ServerSocket ss = new ServerSocket(9806);
Socket soc =ss.accept();
System.out.println("connection established");
BufferedReader in = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
String str = in.readLine();
PrintWriter out = new PrintWriter(soc.getOutputStream() , true);
out.println("Server says: " +str);
}
catch(Exception e)
{
e.printStackTrace();
}}}
Output:
23
Program No – 7
File: reg.jsp
<%@ 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>
<input type="hidden" id="status" value="<%= request.getAttribute("status") %>">
<form action="reg" method="post">
<label for="name">Name</label><br>
<input type="text" name="uname" placeholder="Enter the Name"
required="required"><br><br>
<label for="email">Email</label><br>
<input type="email" name="uemail" placeholder="Enter the Email"
required="required"><br><br>
<label for="password">Password</label><br>
<input type="password" name="upass" placeholder="Enter the password"
required="required"><br><br>
<label for="contact">Contact</label><br>
24
<input type="tel" name="umobile" placeholder="Enter the contact" pattern="[0-9]{3}[0-
9]{3}[0-9]{4}" required="required"><br><br>
<input type="submit" value="Sign Up">
<a href="log.jsp">Already an member</a>
</form>
<script src="https://unpkg.com/sweetalert/dist//sweetalert.min.js"></script>
<script type="text/javascript">
var status=document.getElementById("status").value;
if(status=="success"){
swal("Congrats","Account Created Successfully","success");
}
if(status=="failed"){
swal("This email id is already registered","error");
}
</script>
</body>
</html>
File: log.jsp
<%@ 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>
<input type="hidden" id="status" value="<%= request.getAttribute("status") %>">
<form action="log" method="post">
25
<label for="Email">Email</label><br>
<input type="email" name="uemail" placeholder="Enter your Email"
required="required"><br><br>
<label for="Password">Password</label><br>
<input type="password" name="upassword" placeholder="Enter your Password"
required="required"><br><br>
<input type="submit" value="Login">
<a href="reg.jsp">Create an account</a>
</form>
<script src="https://unpkg.com/sweetalert/dist//sweetalert.min.js"></script>
<script type="text/javascript">
var status=document.getElementById("status").value;
if(status=="success"){
swal("Congrats","loginSuccessfully","success");
}
if(status=="failed"){
swal("Sorry","Wrong Username or Password","error");
}
</script>
</body>
</html>
File: index.jsp
<%
if(session.getAttribute("name")==null){
response.sendRedirect("log.jsp");
}
%>
<!DOCTYPE html>
<html>
<head>
26
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>HELLo EVERYONE!!</h1>
</body>
</html>
File: reg.java
package aa;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 reg
*/
@WebServlet("/reg")
public class reg extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
String uname=request.getParameter("uname");
27
String uemail=request.getParameter("uemail");
String upwd=request.getParameter("upass");
String umobile=request.getParameter("umobile");
RequestDispatcher dispatcher=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/company?
useSSL=false","root","root");
PreparedStatementps=con.prepareStatement("select * from users where
uemail=?");
ps.setString(1,uemail);
ResultSetrs=ps.executeQuery();
if(rs.next()) {
request.setAttribute("status","failed");
request.getRequestDispatcher("reg.jsp").forward(request, response);
}
else {
PreparedStatementpst=con.prepareStatement("insert into
users(uname,upwd,uemail,umobile) values(?,?,?,?)");
pst.setString(1,uname);
pst.setString(2,upwd);
pst.setString(3,uemail);
pst.setString(4,umobile);
int rowcount=pst.executeUpdate();
if(rowcount>0) {
request.setAttribute("status","success");
dispatcher=request.getRequestDispatcher("log.jsp");
}
else {
request.setAttribute("status","failed");
28
dispatcher=request.getRequestDispatcher("reg.jsp");
}}
dispatcher.forward(request, response);
}catch(Exception e) {
e.printStackTrace();
}}}
File: log.java
package aa;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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("/log")
public class log extends HttpServlet {
private static final long serialVersionUID = 1L;
29
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/company?useSSL=false","root
","root");
PreparedStatementpst=con.prepareStatement("select * from users where
uemail = ? and upwd = ? ");
pst.setString(1,uemail);
pst.setString(2,upwd);
ResultSetrs=pst.executeQuery();
if(rs.next()) {
session.setAttribute("name",rs.getString("uname"));
request.setAttribute("status","success");
dispatcher=request.getRequestDispatcher("index.jsp");
}
else {
request.setAttribute("status","failed");
dispatcher=request.getRequestDispatcher("log.jsp");
}
dispatcher.forward(request, response);
}catch(Exception e) {
e.printStackTrace();
}}}
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/webapp_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Aa</display-name>
<welcome-file-list>
30
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
OUTPUT:
31