Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views30 pages

Java FS

The document contains Java code examples demonstrating serialization, collection framework usage, JDBC operations, and JSP with database interactions. It includes classes for student management, sorting by different criteria, database CRUD operations, and web forms for data input and retrieval. The examples illustrate how to connect to a MySQL database, perform operations, and display results using JSP and servlets.

Uploaded by

karshuhana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views30 pages

Java FS

The document contains Java code examples demonstrating serialization, collection framework usage, JDBC operations, and JSP with database interactions. It includes classes for student management, sorting by different criteria, database CRUD operations, and web forms for data input and retrieval. The examples illustrate how to connect to a MySQL database, perform operations, and display results using JSP and servlets.

Uploaded by

karshuhana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Serialization

Student.java

import java.io.Serializable;

public class Student implements Serializable{

int id;

String name;

public Student(int id, String name) {

this.id = id;

this.name = name;

Persist.java

import java.io.*;

class Persist{

public static void main(String args[]){

try{

//Creating the object

Student s1 =new Student(211,"ravi");

//Creating stream and writing the object

FileOutputStream fout=new FileOutputStream("d:\\f.txt");

ObjectOutputStream out=new ObjectOutputStream(fout);

out.writeObject(s1);

out.flush();

//closing the stream

out.close();

System.out.println("success");

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

}
Depersist.java

import java.io.*;

class Depersist{

public static void main(String args[]){

try{

//Creating stream to read the object

FileInputStream fin = new FileInputStream("d:\\f.txt")

ObjectInputStream in=new ObjectInputStream(fin);

Student s=(Student)in.readObject();

//printing the data of the serialized object

System.out.println(s.id+" "+s.name);

//closing the stream

in.close();

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

collection framework

import java.io.*;

import java.util.*;
class Student {

int rollno;

String name;

float fees;

String branch;

int year;

int sem;

int age;

static String clg;

public Student(int rollno,String name,float fees,String branch,int year,int sem,int age) {

this.rollno = rollno;

this.name = name;

this.fees = fees;

this.branch = branch;

this.year = year;

this.sem = sem;

this.age = age;

clg="PU";

@Override

public String toString() {

return rollno + " "+ name + " " + fees + " " + branch + " " + year + sem + " " + age + " " + clg + "\n";

class AgeComparator implements Comparator {

public int compare(Object o1, Object o2) {

Student s1=(Student)o1;

Student s2=(Student)o2;

if(s1.age==s2.age)
return 0;

else if(s1.age>s2.age)

return 1;

else

return -1;

class NameComparator implements Comparator{

public int compare(Object o1, Object o2) {

Student s1=(Student)o1;

Student s2=(Student)o2;

return s1.name.compareTo(s2.name);

class FeesComparator implements Comparator {

public int compare(Object o1,Object o2) {

Student s1=(Student)o1;

Student s2=(Student)o2;

if(s1.fees==s2.fees)

return 0;

else if(s1.fees>s2.fees)

return 1;

else

return -1;

public class Temp1 {

public static void main(String[] args) {


// TODO Auto-generated method stub

ArrayList sl=new ArrayList();

sl.add(new Student(1,"Shiva",10000.00f,"cse",1,1,18));

sl.add(new Student(2,"Venky",15000.00f,"ise",1,2,20));

sl.add(new Student(3,"Jesus",17000.00f,"ece",1,1,19));

sl.add(new Student(3,"Alla",12000.00f,"eee",1,1,19));

sl.add(new Student(3,"Budha",11000.00f,"mech",1,1,21));

System.out.println("Sorting by Name");

System.out.println("_______________");

Collections.sort(sl,new NameComparator());

Iterator itr=sl.iterator();

while(itr.hasNext()){

Student st=(Student)itr.next();

System.out.println(st.rollno+" "+st.name+" "+ st.fees+ " " + st.branch+ " " + st.year + " " + st.sem + " "
+ st.age + " " + Student.clg);

System.out.println("Sorting by age");

System.out.println("______________");

Collections.sort(sl,new AgeComparator());

Iterator itr2=sl.iterator();

while(itr2.hasNext()){

Student st=(Student)itr2.next();

System.out.println(st.rollno+" "+st.name+" "+ st.fees+ " " + st.branch+ " " + st.year + " " + st.sem + " "
+ st.age + " " + Student.clg);

System.out.println("Sorting by fees");

System.out.println("______________");

Collections.sort(sl,new FeesComparator());

Iterator itr1=sl.iterator();

while(itr1.hasNext()){

Student st=(Student)itr1.next();
System.out.println(st.rollno+" "+st.name+" "+ st.fees+ " " + st.branch+ " " + st.year + " " + st.sem + " "
+ st.age + " " + Student.clg);

jdbc

import java.sql.*;

import java.util.*;

public class Temp2 {

public static void main(String[] args) {

// TODO Auto-generated method stub

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/god?
characterEncoding=latin1","root","admin123");

Statement stmt=con.createStatement();

int ans=1;

do {

System.out.println("1. Insert a record ");

System.out.println("2. Delete a record ");

System.out.println("3. Modify/Edit a record ");

System.out.println("4. Display list of records ");


Scanner sc = new Scanner(System.in);

System.out.println("Enter your choice:");

int ch = sc.nextInt();

String ename;

int eno,age;

String query="";

switch(ch) {

case 1:

System.out.println("Enter employee number:");

eno = sc.nextInt();

System.out.println("Enter employee name:");

ename = sc.next();

System.out.println("Enter employee age:");

age = sc.nextInt();

query = "INSERT INTO emp " + "VALUES (" + eno+ ",'" + ename+"',"+ age+")";

stmt.executeUpdate(query);

break;

case 2:

System.out.println("Enter employee number:");

eno = sc.nextInt();

query = "delete from emp where eno='"+eno+"'";

stmt.executeUpdate(query);

System.out.println("Record is deleted from the table successfully..................");

break;

case 3:

PreparedStatement ps = null;

query = "update emp set name=? where eno=? ";

ps = con.prepareStatement(query);

System.out.println("Enter employee number:");

eno = sc.nextInt();

System.out.println("Enter employee name:");


ename = sc.next();

ps.setString(1, ename);

ps.setInt(2, eno);

ps.executeUpdate();

System.out.println("Record is updated successfully......");

break;

case 4:

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));

System.out.println("Enter another(1/0)");

ans = sc.nextInt();

}while(ans==1);

con.close();

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

Servlet with database

<!DOCTYPE html>

<html>

<head>

<title>Insert title here</title>


</head>

<body>

<form action="./InsertData" method="post">

<table>

<tr><td>Enter Roll No:</td>

<td><input type="text" name="rollno"/></td>

</tr>

<tr><td>Enter Name:</td>

<td><input type="text" name="name"/></td>

</tr>

<tr><td>Enter Section:</td>

<td><select name="section">

<option>A</option>

<option>B</option>

<option>C</option>

<option>D</option>

</select>

</td>

</tr>

<tr><td>Enter Subjet1 Mark:</td>

<td><input type="text" name="sub1"/></td>

</tr>

<tr><td>Enter Subject2 Mark:</td>

<td><input type="text" name="sub2"/></td>

</tr>

<tr><td>Enter Subjet3 Mark:</td>

<td><input type="text" name="sub3"/></td>

</tr>

<tr><td>Enter Subject4 Mark:</td>

<td><input type="text" name="sub4"/></td>

</tr>
<tr><td>Enter Subject5 Mark:</td>

<td><input type="text" name="sub5"/></td>

</tr>

<tr><td>Enter Subject6 Mark:</td>

<td><input type="text" name="sub6"/></td>

</tr>

<tr><td>Enter Lab1 Mark:</td>

<td><input type="text" name="lab1"/></td>

</tr>

<tr><td>Enter Lab2 Mark:</td>

<td><input type="text" name="lab2"/></td>

</tr>

<tr><td><input type="submit"/></td></tr>

</table>

</form>

</body>

</html>

InsertData.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// TODO Auto-generated method stub

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/god?
characterEncoding=latin1","root","admin123");

PreparedStatement st = con.prepareStatement("insert into mark values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

st.setInt(1, Integer.valueOf(request.getParameter("rollno")));

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

st.setString(3, request.getParameter("section"));

st.setInt(4, Integer.valueOf(request.getParameter("sub1")));
st.setInt(5, Integer.valueOf(request.getParameter("sub2")));

st.setInt(6, Integer.valueOf(request.getParameter("sub3")));

st.setInt(7, Integer.valueOf(request.getParameter("sub4")));

st.setInt(8, Integer.valueOf(request.getParameter("sub5")));

st.setInt(9, Integer.valueOf(request.getParameter("sub6")));

st.setInt(10, Integer.valueOf(request.getParameter("lab1")));

st.setInt(11, Integer.valueOf(request.getParameter("lab2")));

st.executeUpdate();

st.close();

con.close();

PrintWriter out = response.getWriter();

out.println("<html><body><b>Successfully Inserted"

+ "</b></body></html>");

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

Search.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<form action="./DispData">

Enter your Roll No:<input type="text" name="rollno"/><br/>

<input type="submit" value="search"/>

</form>

</body>
</html>

DispData.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// TODO Auto-generated method stub

response.setContentType("text/html");

PrintWriter out = response.getWriter();

try{

String rno=request.getParameter("rollno");

int rn=Integer.valueOf(rno);

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/god?
characterEncoding=latin1","root","admin123");

PreparedStatement ps=con.prepareStatement("select * from mark where rollno=?");

ps.setInt(1,rn);

out.print("<table width=50% border=1>");

out.print("<caption>Result:</caption>");

ResultSet rs=ps.executeQuery();

/* Printing column names */

ResultSetMetaData rsmd=rs.getMetaData();

int total=rsmd.getColumnCount();

out.print("<tr>");

for(int i=1;i<=total;i++)

out.print("<th>"+rsmd.getColumnName(i)+"</th>");

out.print("<th>Status</th></tr>");

/* Printing result */

while(rs.next())

{
out.print("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+ "</td><td>"+rs.getString(3)+
rs.getInt(4)+"</td><td>" + rs.getInt(5)+"</td><td>" + rs.getInt(6)+"</td><td>"+
rs.getInt(7)+"</td><td>" + rs.getInt(8)+"</td><td>"+ rs.getInt(9)+"</td><td>"+
rs.getInt(10)+"</td><td>"+rs.getInt(11)+"</td><td>");

if(rs.getInt(4)>=40 && rs.getInt(5)>=40 && rs.getInt(6)>=40 && rs.getInt(7)>=40 && rs.getInt(8)>=40


&& rs.getInt(9)>=40 && rs.getInt(10)>=40 && rs.getInt(11)>=40)

out.print("<td>Pass</td>"+"</td></tr>");

else

out.print("<td>Fail</td>"+"</td></tr>");

out.print("</table>");

}catch (Exception e2) {e2.printStackTrace();}

finally{out.close();}

jsp with database

Create table employees(eno int,name varchar(30),gender varchar(1),dept varchar(10),salary


float(10,2));

Insert.jsp

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


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

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<body bgcolor="#ffffcc">

<font size="+3" color="green"><br>Welcome to Presidency University !</font>

<FORM action="Insert.jsp" method="get">

<TABLE style="background-color: #ECE5B6;" WIDTH="30%" >

<TR>

<TH width="50%">Employee No:</TH>

<TD width="50%"><INPUT TYPE="text" NAME="eno"></TD>

</tr>

<TR>

<TH width="50%">Employee Name</TH>

<TD width="50%"><INPUT TYPE="text" NAME="name"></TD>

</tr>

<tr>

<TH width="50%">Employee Gender</TH>

<TD width="50%"><INPUT TYPE="text" NAME="gender"></TD>

</tr>

<tr>

<TH width="50%">Employee Department</TH>


<TD width="50%"><INPUT TYPE="text" NAME="dept"></TD>

</tr>

<tr>

<TH width="50%">Employee Salary</TH>

<TD width="50%"><INPUT TYPE="text" NAME="salary"></TD>

</tr>

<TR>

<TH></TH>

<TD width="50%"><INPUT TYPE="submit" VALUE="submit"></TD>

</tr>

</TABLE>

<%

int uq=0;

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/god?
characterEncoding=latin1","root","Nikhil@123");

PreparedStatement pstatement = con.prepareStatement("INSERT INTO EMPLOYEES


VALUES(?, ?, ?, ?, ?)");

pstatement.setInt(1, Integer.valueOf(request.getParameter("eno")));

pstatement.setString(2, request.getParameter("name"));

pstatement.setString(3, request.getParameter("gender"));

pstatement.setString(4, request.getParameter("dept"));

pstatement.setFloat(5, Integer.valueOf(request.getParameter("salary")));

uq=pstatement.executeUpdate();

pstatement.close();

con.close();

catch(Exception ex) {

System.out.println("Unable to connect to database.");

if (uq != 0) {
%>

<br>

<TABLE style="background-color: #E3E4FA;"

WIDTH="30%" border="1">

<tr><th>Data is inserted successfully in database.</th></tr>

</table>

<%

} %>

</form>

</body>

</html>

disp.jsp

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

pageEncoding="UTF-8"%>

<!DOCTYPE html>

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

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

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>
<h2>Employee Details</h2>

<%

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/god?
characterEncoding=latin1","root","Nikhil@123");

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("select * from employees");

%>

<TABLE cellpadding="15" border="1" style="background-color: #ffffcc;">

<tr><th>E.No</th><th>Name</th><th>Gender</th><th>Department</th><th>Salary</th><tr>

<%

while (rs.next()) {

%>

<TR>

<TD><%=rs.getInt(1)%></TD>

<TD><%=rs.getString(2)%></TD>

<TD><%=rs.getString(3)%></TD>

<TD><%=rs.getString(4)%></TD>

<TD><%=rs.getFloat(5)%></TD>

</TR>

<% } %>

<%

// close all the connections.

rs.close();

st.close();

con.close();

} catch (Exception ex) {

%>

<font size="+3" color="red"></b>


<%

out.println("Unable to connect to database.");

%>

</TABLE><TABLE>

<TR>

<TD><FORM ACTION="Disp.jsp" method="get" >

<button type="submit"><-- back</button></TD>

</TR>

</TABLE>

</font>

</body>

</html>

mvc

index.jsp

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

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>
<body>

<form action="ControllerServlet" method="post">

Name:<input type="text" name="name"><br>

Password:<input type="password" name="password"><br>

<input type="submit" value="login">

</form>

</body>

</html>

login-success.jsp

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

pageEncoding="UTF-8" import="mvcc.LoginBean"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<p>You are successfully logged in!</p>

<%

LoginBean bean=(LoginBean)request.getAttribute("bean");

out.print("Welcome, "+bean.getName());
%>

</body>

</html>

login-error.jsp

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

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<p>Sorry! username or password error</p>

<%@ include file="index.jsp" %>

</body>

</html>

ControllerServlet.java
import jakarta.servlet.RequestDispatcher;

import jakarta.servlet.ServletException;

import jakarta.servlet.annotation.WebServlet;

import jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;

import mvcc.LoginBean;

import java.io.IOException;

import java.io.PrintWriter;

/**

* Servlet implementation class ControllerServlet

*/

public class ControllerServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public ControllerServlet() {

super();

// TODO Auto-generated constructor stub

}
/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();

String name=request.getParameter("name");

String password=request.getParameter("password");

LoginBean bean=new LoginBean();

bean.setName(name);

bean.setPassword(password);

request.setAttribute("bean",bean);

boolean status=bean.validate();

if(status){

RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");

rd.forward(request,response);

else{

RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");

rd.forward(request,response);

}
}

LoginBean.java

package mvcc;

import java.lang.*;

public class LoginBean {

private String name,password;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

public boolean validate(){


if(password.equals("admin")){

return true;

else{

return false;

mvc pattern with db

Employee.java

package com.pu;

import java.io.Serializable;

public class Employee implements Serializable{

private static final long serialVersionUID = 1L;

private int id;

private String firstName;

private String lastName;


private String username;

private String password;

private String address;

private String contact;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

public String getUsername() {

return username;

public void setUsername(String username) {

this.username = username;

public String getPassword() {

return password;

}
public void setPassword(String password) {

this.password = password;

public String getAddress() {

return address;

public void setAddress(String address) {

this.address = address;

public String getContact() {

return contact;

public void setContact(String contact) {

this.contact = contact;

EmployeeDao.java

package com.pu;

import java.sql.*;

public class EmployeeDao {

public int registerEmployee(Employee employee) throws Exception {

String query = "INSERT INTO employee1" +

" (id, first_name, last_name, username, password, address, contact) VALUES " +

" (?, ?, ?, ?, ?,?,?);";


int result = 0;

Class.forName("com.mysql.jdbc.Driver");

try (Connection connection = DriverManager

.getConnection("jdbc:mysql://localhost:3306/god?characterEncoding=latin1","root","admin123");

// Step 2:Create a statement using connection object

PreparedStatement preparedStatement = connection.prepareStatement(query)) {

preparedStatement.setInt(1, employee.getId());

preparedStatement.setString(2, employee.getFirstName());

preparedStatement.setString(3, employee.getLastName());

preparedStatement.setString(4, employee.getUsername());

preparedStatement.setString(5, employee.getPassword());

preparedStatement.setString(6, employee.getAddress());

preparedStatement.setString(7, employee.getContact());

System.out.println(preparedStatement);

// Step 3: Execute the query or update query

result = preparedStatement.executeUpdate();

} catch (SQLException e) {

// process sql exception

System.err.println(e);

return result;

}
}

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

<h1>Employee Register Form</h1>

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

<table style="with: 50%">

<tr>

<td>Registration Id</td>

<td><input type="text" name="id" /></td>

</tr>

<tr>

<td>First Name</td>

<td><input type="text" name="firstName" /></td>

</tr>

<tr>

<td>Last Name</td>

<td><input type="text" name="lastName" /></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>

<tr>

<td>Address</td>

<td><input type="text" name="address" /></td>

</tr>

<tr>

<td>Contact No</td>

<td><input type="text" name="contact" /></td>

</tr>

</table>

<input type="submit" value="Submit" /></form>

</body>

</html>

employeedetail.jsp

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

pageEncoding="ISO-8859-1"%>

<%@page import="com.pu.*"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>
<body>

<jsp:useBean id="employee" class="com.pu.Employee" />

<jsp:setProperty property="*" name="employee" />

<%

EmployeeDao employeeDao = new EmployeeDao();

int status = employeeDao.registerEmployee(employee);

if (status > 0) {

out.print("You are successfully registered");

%>

</body>

</html>

You might also like