Add-Edit-Delete in a Single JSP Page(Using query String)

1) if you write in browser                                     http://localhost:8080/BankProject/add_edit_delete_search/NewFile.jsp?fn=ShowList

It will show you the List of all book details

2) If you write              http://localhost:8080/BankProject/add_edit_delete_search/NewFile.jsp?fn=add

It will show add page

3) if you write http://localhost:8080/BankProject/add_edit_delete_search/NewFile.jsp?fn=edit&id=20 it will show value of record 20. there you can update the values of record 20

4)  if you write http://localhost:8080/BankProject/add_edit_delete_search/NewFile.jsp?fn=delete&id=20 it will delete record no 20.

Write all above scenario in a single jsp

 

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″ import=”java.util.*,java.sql.*,bean.*”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<style>
BODY
{

BACKGROUND-COLOR: #efefef;

}

INPUT
{
BACKGROUND-COLOR: #ffffff;
FONT-FAMILY: Century
}
THEAD
{
BACKGROUND-COLOR: #006699;
font-weight: bold;
color: white;
font-size: 18;
font-family:’Century’;
border: none;
}
TABLE
{

BACKGROUND-COLOR:#efefef;
border-color: black;
border-left-color:black;
border-right-color:black;
border-top-color:black;
border-bottom-color:black;
}

BUTTON
{
BACKGROUND-COLOR:lightgray;
border-width: medium;
border-style: outset;

}

TD
{
border: none;
border-style: none;
}

TR
{
border: none;
border-style: none;
}

A
{
color: blue;
}
</style>

function add()
{ var f=document.frm;
f.action=’NewFile.jsp?fn=add’;
f.submit();
}
function on_update(id){
var f=document.frm;
f.action=’NewFile.jsp?fn=update&id=’+id;
f.submit();
}
function on_search(){
var f=document.frm;
var search = f.txtSearch.value;
f.action=’NewFile.jsp?fn=search&search=’+search;
f.submit();
}

function on_cancel(){

document.frm.bookName.value=””;
document.frm.bookAuthor.value=””;
}

<title>ADD-EDIT-DELETE-SEARCH</title>
</head>
<body >
<form name=frm method=”post” >
<% String Querystr = request.getQueryString();
System.out.println(“queryString=”+Querystr);
System.out.println(“search=”+request.getParameter(“txtSearch”));%>
<%
if((Querystr!=null)){%>
<%
if(request.getParameter(“fn”).equals(“ShowList”)){%>
<TABLE border =1>
<THEAD>
<tr >
<td colspan=”16″ align=”left” ><font size=”3″>View Details</font></td>

</tr>
</THEAD>
<TBODY>
<tr bgcolor=”#d6d6d6″ align=”left”>
<td><INPUT id=txtSearch name=txtSearch size=”24″ value =””></td>
<td><BUTTON type=button value=search name=cmdsearch onclick=”on_search()” >Search</BUTTON>&nbsp;&nbsp; </td>
</tr>

<TR bgcolor=”#d6d6d6″ align=”left”>
<TD nowrap><FONT size=3 ><B>SL No</B></FONT></TD>
<TD nowrap><FONT size=3 ><B>BookId</B></FONT></TD>
<TD nowrap><FONT size=3 ><B>Book Name</B></FONT></TD>
<TD nowrap><FONT size=3 ><B>Book Author Name</B></FONT></TD>
<TD nowrap><FONT size=3 ><B><A HREF=”NewFile.jsp?fn=add”>Add </A></B></FONT></TD>

</tr>
<%!
private String checkNull(String value) {
if(value==”null” || value==null)
{return “”;}
return value;
}

public Connection getLocalConnection()
{
Connection con = null;
try
{
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,”root”,”root”);

}
catch (ClassNotFoundException e)
{
System.err.println(“ClassNotFoundException in getConnection, ” + e.getMessage());

}
catch (SQLException e)
{
System.err.println(“SQLException in getConnection, ” + e.getMessage());
}
return con;
}
%>

<%
Connection con1 = null;
con1 =getLocalConnection();
ResultSet rs = null;
Statement stmt = null;
stmt = con1.createStatement();
Vector vReq=new Vector();

try {

String strSql = “select BookId,BookName,BookAuthor from bookdetail order by BookId desc”;
rs = stmt.executeQuery(strSql);

while (rs.next()) {
String temp[] = new String[3];
temp[0] = rs.getString(“BookId”);
temp[1] = rs.getString(“BookName”);
temp[2] = rs.getString(“BookAuthor”);
vReq.add(temp);
}

} catch (Exception e) {
System.err.print(“allBookDetailList Exception : ” + e.getMessage());
}

for(int i=0;i<vReq.size();i++)
{
String temp[]=new String[3];
temp = (String[])vReq.get(i);

%>
<TR bgcolor=”#d6d6d6″ align=”left”>
<TD nowrap><%=i+1%></TD>
<TD nowrap><%=checkNull(temp[0])%></TD>
<TD nowrap><%=checkNull(temp[1])%></TD>
<TD nowrap><%=checkNull(temp[2])%></TD>
<td><A HREF= “NewFile.jsp?fn=edit&id=<%=temp[0]%>”>Edit </A> </td>
<td><A HREF= “NewFile.jsp?fn=delete&id=<%=temp[0]%>”>Delete </A> </td>
<% }%>
</TR>
</TBODY>
</table>
<%}else if(request.getParameter(“fn”).equals(“add”)){

%>

<TABLE border =1> <THEAD>
<tr >
<td colspan=”16″ align=”left” ><font size=”3″>Add Book Details</font></td>

</tr>
</THEAD>
<%

String bookName=request.getParameter(“bookName”);
String bookAuthor=request.getParameter(“bookAuthor”);
if((request.getParameter(“bookName”)!=null)&&(request.getParameter(“bookName”).trim().length()>0)){
try {
Connection con = null;
con = getLocalConnection();
PreparedStatement pre = con.prepareStatement(“insert into bookdetail (BookName,BookAuthor) values(?,?)”);
pre.setString(1,bookName);
pre.setString(2,bookAuthor);
pre.executeUpdate();

} catch (Exception e) {
System.err.println(“In InsertBookDetailTable Exception “+ e);
}
String L_url1=response.encodeRedirectURL(“./NewFile.jsp?fn=ShowList”);
response.sendRedirect(L_url1);
}
%>

<tr bgcolor=”#d6d6d6″ align=”left”>
<td>Book Name: </td>
<td><input type=”text” name=”bookName” value=””></td>
</tr>
<tr bgcolor=”#d6d6d6″ align=”left”>
<td>Book Author: </td>
<td><input type=”text” name=”bookAuthor” value=””></td>

</tr >
<tr bgcolor=”#d6d6d6″ align=”left”><td></td><td>
<BUTTON type=button value=save name=cmdsave onclick=”add()” >Save</BUTTON>
<BUTTON type=”button” value=”Cancel” id=”button” name=”cmdCancel”ONCLICK=”on_cancel()”>Cancel</BUTTON></td>
<td><a href=’./NewFile.jsp?fn=ShowList’>Click here to go to List page</a></td>
</tr>
</TABLE>
<% }else if(request.getParameter(“fn”).equals(“edit”)){
%>

<TABLE border =1> <THEAD>
<tr >
<td colspan=”16″ align=”left” ><font size=”3″>Edit Book Details</font></td>

</tr>
</THEAD>
<%
String id=request.getParameter(“id”);
Vector vReq1=new Vector();
ResultSet rs = null;
Statement stmt = null;
Connection con2 = null;
try {
con2 = getLocalConnection();
stmt = con2.createStatement();
String strSql = “select BookId,BookName,BookAuthor from bookdetail where BookId ='”+id+”‘”;
rs = stmt.executeQuery(strSql);

while (rs.next()) {
String temp[] = new String[3];

temp[0] = rs.getString(“BookId”);
temp[1] = rs.getString(“BookName”);
temp[2] = rs.getString(“BookAuthor”);

vReq1.add(temp);
}

} catch (Exception e) {

System.err.println(“getRecord Exception : ” + e.getMessage());
}

for(int i=0;i<vReq1.size();i++)
{
String temp1[]=new String[3];
temp1 = (String[])vReq1.get(i);

%>

<tr bgcolor=”#d6d6d6″ align=”left”>
<td>Book Name: </td>
<td><input type=”text” name=”bookName” value=”<%=temp1[1]%>”></td>
</tr>
<tr bgcolor=”#d6d6d6″ align=”left”>
<td>Book Author: </td>
<td><input type=”text” name=”bookAuthor” value=”<%=temp1[2]%>”></td>

</tr>
<tr bgcolor=”#d6d6d6″ align=”left”><td></td><td>
<BUTTON type=button value=save name=cmdsave onclick=”on_update(<%=temp1[0]%>);” >Save</BUTTON>
<BUTTON type=”button” value=”Cancel” id=”button” name=”cmdCancel”ONCLICK=”on_cancel()”>Cancel</BUTTON></td>
<td><a href=’./NewFile.jsp?fn=ShowList’>Click here to go to List page</a></td>
</tr>

</TABLE>
<% }}else if(request.getParameter(“fn”).equals(“update”)){

%>
<%

String bookName=request.getParameter(“bookName”);
String bookAuthor=request.getParameter(“bookAuthor”);
String id=request.getParameter(“id”);
try {
Connection con1 = null;
Statement stmt = null;
con1 =getLocalConnection();
stmt = con1.createStatement();
String query = “update bookdetail set BookName='”+bookName+”‘,BookAuthor='”+bookAuthor+”‘ where BookId='”+id+”‘”;
stmt.executeUpdate(query);

} catch (Exception e) {
System.err.println(“In updateDetailTable Exception “+ e);
}
%>
<table border =1 ><tr bgcolor=”#d6d6d6″ align=”left”><tr><td>updated successfully</td><td><a href=’./NewFile.jsp?fn=ShowList’>Click here to go to List page</a> </td></tr></table>
<%}else if(request.getParameter(“fn”).equals(“delete”)){
%>
<table border =1><tr bgcolor=”#d6d6d6″ align=”left”><tr><td>Deleted Successfully</td><td><a href=’./NewFile.jsp?fn=ShowList’>Click here to go to List page</a> </td></tr></table>
<%

String id=request.getParameter(“id”);
try {
Connection con1 = null;
Statement stmt = null;

con1 =getLocalConnection();
stmt = con1.createStatement();
String query = “delete from bookdetail where BookId=”+id+””;
stmt.executeUpdate(query);

} catch (Exception e) {
System.err.println(“In deleted Exception “+ e);
} %>
<%}else if(request.getParameter(“fn”).equals(“search”)){ %>
<% if((request.getParameter(“search”)!=null) && !(request.getParameter(“search”).trim().equalsIgnoreCase(“”))){
System.out.println(“search”);
%>

<TABLE border =1>
<THEAD>
<tr >
<td colspan=”16″ align=”left” ><font size=”3″>View Details</font></td>

</tr>
</THEAD>
<TBODY>
<tr bgcolor=”#d6d6d6″ align=”left”>
<td><INPUT id=txtSearch name=txtSearch size=”24″ value =”<%=checkNull(request.getParameter(“txtSearch”))%>”></td>
<td><BUTTON type=button value=search name=cmdsearch onclick=”on_search()” >Search</BUTTON>&nbsp;&nbsp; </td>
</tr>

<TR bgcolor=”#d6d6d6″ align=”left”>
<TD nowrap><FONT size=3 ><B>SL No</B></FONT></TD>
<TD nowrap><FONT size=3 ><B>BookId</B></FONT></TD>
<TD nowrap><FONT size=3 ><B>Book Name</B></FONT></TD>
<TD nowrap><FONT size=3 ><B>Book Author Name</B></FONT></TD>
<TD nowrap><FONT size=3 ><B><A HREF=”NewFile.jsp?fn=add”>Add </A></B></FONT></TD>
</tr>

<%
Connection con1 = null;
con1 =getLocalConnection();
ResultSet rs = null;
Statement stmt = null;
stmt = con1.createStatement();
Vector vReq=new Vector();

try {
String searchInput = request.getParameter(“txtSearch”);
String strSql = “select BookId,BookName,BookAuthor from bookdetail where BookName LIKE ‘”+searchInput+”%’ order by BookId desc;”;
rs = stmt.executeQuery(strSql);

while (rs.next()) {
String temp[] = new String[3];
temp[0] = rs.getString(“BookId”);
temp[1] = rs.getString(“BookName”);
temp[2] = rs.getString(“BookAuthor”);
vReq.add(temp);
}

} catch (Exception e) {
System.err.print(“allBookDetailList Exception : ” + e.getMessage());
}

for(int i=0;i<vReq.size();i++)
{
String temp[]=new String[3];
temp = (String[])vReq.get(i);

%>
<TR bgcolor=”#d6d6d6″ align=”left”>
<TD nowrap><%=i+1%></TD>
<TD nowrap><%=checkNull(temp[0])%></TD>
<TD nowrap><%=checkNull(temp[1])%></TD>
<TD nowrap><%=checkNull(temp[2])%></TD>
<td><A HREF= “NewFile.jsp?fn=edit&id=<%=temp[0]%>”>Edit </A> </td>
<td><A HREF= “NewFile.jsp?fn=delete&id=<%=temp[0]%>”>Delete </A> </td>
<% }%>
<% }else{
System.out.println(“$$”);
response.sendRedirect(“./NewFile.jsp?fn=ShowList”);
}%>

<%}else{}%>

</TR>
</TBODY>
</table>
<%}else{ %>
<table border =1><tr bgcolor=”#d6d6d6″ align=”left”><tr><td><a href=’./NewFile.jsp?fn=ShowList’>Click here to go to List page</a></td></tr></table>
<%}%>
</form>
</body>
</html>

Advertisements

Add-Edit-Delete-Search Criteria in JSP-SERVLET-JDBC-JAVA

1) Add bookdetails,edit book details,delete book details and search book details

    Fields are bookId,bookName,bookAuthorName

   Create a table in MySQL database

  CREATE TABLE `bookdetail` (
`BookAuthor` varchar(30) default NULL,
`BookName` varchar(30) default NULL,
`BookId` int(11) NOT NULL auto_increment,
PRIMARY KEY (`BookId`)
)

2) Create a javaBean

i.e. book.java

public class book implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String bookName=””;
String id=””;
String bookAuthorName=””;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookAuthorName() {
return bookAuthorName;
}
public void setBookAuthorName(String bookAuthorName) {
this.bookAuthorName = bookAuthorName;
}

3) create a JDBC-Connection class that is Labcon.java

public class Labcon {
Connection con = null;
public Connection getLocalConnection()

//for oracle
/*
{

try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:mydb”,”anshu”,”anshu”);

}
catch (ClassNotFoundException e)
{
System.err.println(“ClassNotFoundException in getConnection, ” + e.getMessage());

}
catch (SQLException e)
{
System.err.println(“SQLException in getConnection, ” + e.getMessage());
}

return con;
}*/

//for mysql
{

try
{
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,”root”,”root”);

}
catch (ClassNotFoundException e)
{
System.err.println(“ClassNotFoundException in getConnection, ” + e.getMessage());

}
catch (SQLException e)
{
System.err.println(“SQLException in getConnection, ” + e.getMessage());
}

return con;
}
public void setConnectionClose() throws SQLException
{
con.close();
}

}

4) Create add.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”&gt;
<html>
<head>

function save()
{
document.frm.action=”../bookServlet”;
document.frm.submit();
}

function on_cancel(){

document.frm.action=”add.jsp”;
document.frm.submit();
}

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>AddBookDetail</title>
</head>
<body>
<form name=frm method=”post” >
<table>
<tr>
<TD><b>Book Name</b></TD>
<td><INPUT id=txtBookName name=txtBookName size=”24″ value =””></TD>
</tr>
<tr>
<TD><b>Book Author Name</b></TD>
<td><INPUT id=txtBookAuthorName name=txtBookAuthorName size=”24″ value =””></TD>
<td><INPUT type=”hidden” name=hidval size=”24″ value=”Add”></td>
</tr>
<tr><TD>
<BUTTON type=button value=save name=cmdsave onclick=”save()” >Save</BUTTON>&nbsp;&nbsp;
<BUTTON type=”button” value=”Cancel” id=”button” name=”cmdCancel”ONCLICK=”on_cancel()”>Cancel</BUTTON>
</TD></tr>
</table>
</form>
</body>
</html>

5) Create edit.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″ import=”java.sql.*,servlet.*,java.util.*,generalClass.*”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Edit book detail</title>
</head>
<body>
<form method=”post” action=”../bookServlet”>
<table border=”0″>
<tr><th>Book Name</th><th>Book Author</th></tr>
<%
String id=request.getParameter(“id”);
Vector vReq=new Vector();
bookDetail bookdet = new bookDetail();
vReq=bookdet.getRecord(id);

for(int i=0;i<vReq.size();i++)
{
String temp[]=new String[3];
temp = (String[])vReq.get(i);

%>
<tr>
<td><input type=”text” name=”bookName” value=”<%=temp[1]%>”></td>
<td><input type=”text” name=”bookAuthor” value=”<%=temp[2]%>”></td>
<td><input type=”hidden” name=”id” value=”<%=temp[0]%>”></td>
<td><INPUT type=”hidden” name=hidval size=”24″ value=”Update”></td>
</tr>
<%}%>
<tr>
<td><input type=”submit” name=”Submit” value=”Update” style=”background-color:#49743D;font-weight:bold;color:#ffffff;”></td>
</tr>

</table>
</form>
</body>
</html>

6) Create list.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″ import=”commonFunction.*,generalClass.*,java.util.*”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>

function add()
{
document.frm.action=”add.jsp”;
document.frm.submit();
}
function editRecord(id){

var f=document.frm;
f.method=”post”;
f.action=’edit.jsp?id=’+id;
f.submit();
}
function deleteRecord(id){
var myid=id;
var hid=”Delete”;
var f=document.frm;
f.method=”post”;
f.action=’../bookServlet?myid=’+myid+ ‘&hidval=’ + hid;
f.submit();
}
function search(){
document.frm.action=”list.jsp”;
document.frm.submit();
}

<title>Book List</title>
</head>
<body>
<form name=frm method=”post” >
<TABLE border=1 ID=”customer” style=”background-color: #efefef; WIDTH: 590px; POSITION: absolute; TOP: 50px;”>
<tr><TD>
<BUTTON type=button value=save name=cmdsave onclick=”add()” >Add</BUTTON>&nbsp;&nbsp;
</TD></tr>
<tr>
<td><INPUT id=txtSearch name=txtSearch size=”24″ value =””></td>
<td><BUTTON type=button value=search name=cmdsearch onclick=”search()” >Search</BUTTON>&nbsp;&nbsp; </td>
</tr>
<THEAD>
<tr>
<td colspan=”16″ align=”left”><font size=”3″>View Details</font></td>

</tr>
</THEAD>
<TBODY>
<TR bgcolor=”#d6d6d6″ align=”left”>
<TD nowrap><FONT size=3 color=green><B>SL No</B></FONT></TD>
<TD nowrap><FONT size=3 color=green><B>BookId</B></FONT></TD>
<TD nowrap><FONT size=3 color=green><B>Book Name</B></FONT></TD>
<TD nowrap><FONT size=3 color=green><B>Book Author Name</B></FONT></TD>

</tr>
<%!
private String checkNull(String value) {
if(value==”null” || value==null)
{return “”;}
return value;
}
%>

<%

bookDetail bookdet = new bookDetail();
String searchInput = request.getParameter(“txtSearch”);
System.out.println(“searchInput –” + searchInput);
if((searchInput == null) || (searchInput == “null”)|| (searchInput == “”)){
Vector vReq=new Vector();
vReq= bookdet.allBookDetailList();

for(int i=0;i<vReq.size();i++)
{
String temp[]=new String[3];
temp = (String[])vReq.get(i);

%>
<TR bgcolor=”#d6d6d6″>
<TD nowrap><%=i+1%></TD>
<TD nowrap><%=checkNull(temp[0])%></TD>
<TD nowrap><%=checkNull(temp[1])%></TD>
<TD nowrap><%=checkNull(temp[2])%></TD>
<td><input type=”button” name=”edit” value=”Edit” style=”background-color:green;font-weight:bold;color:white;” onclick=”editRecord(<%=temp[0]%>);” ></td>
<td><input type=”button” name=”delete” value=”Delete” style=”background-color:red;font-weight:bold;color:white;” onclick=”deleteRecord(<%=temp[0]%>);” ></td>

</TR>
<% } }else{
Vector vReq1=new Vector();
vReq1= bookdet.allBookDetailList(searchInput);

for(int i=0;i<vReq1.size();i++)
{
String temp1[]=new String[3];
temp1 = (String[])vReq1.get(i);

%>
<TR bgcolor=”#d6d6d6″>
<TD nowrap><%=i+1%></TD>
<TD nowrap><%=checkNull(temp1[0])%></TD>
<TD nowrap><%=checkNull(temp1[1])%></TD>
<TD nowrap><%=checkNull(temp1[2])%></TD>
<td><input type=”button” name=”edit” value=”Edit” style=”background-color:green;font-weight:bold;color:white;” onclick=”editRecord(<%=temp1[0]%>);” ></td>
<td><input type=”button” name=”delete” value=”Delete” style=”background-color:red;font-weight:bold;color:white;” onclick=”deleteRecord(<%=temp1[0]%>);” ></td>

</TR>
<%}}%>
</TBODY>
</table>
</form>
</body>
</html>

7) Write All methods(For inserting to db, for editing&updating , for delete and for searach) write in class file 

public class bookDetail {
Connection con = null;
public void InsertBookDetailTable(book BookObj) throws SQLException {

try {

Labcon lc = new Labcon();
con = lc.getLocalConnection();
PreparedStatement pre = con.prepareStatement(“insert into bookdetail (BookName,BookAuthor) values(?,?)”);
pre.setString(1,BookObj.getBookName());
pre.setString(2,BookObj.getBookAuthorName());
pre.executeUpdate();

} catch (Exception e) {
System.err.println(“In InsertBookDetailTable Exception “+ e);
}
}
public Vector allBookDetailList() throws SQLException {
Vector vList = new Vector();
ResultSet rs = null;
Statement stmt = null;
try {
// String userId=”ID00000000”;
Labcon lc = new Labcon();
con = lc.getLocalConnection();
stmt = con.createStatement();
String strSql = “select BookId,BookName,BookAuthor from bookdetail”;
rs = stmt.executeQuery(strSql);

while (rs.next()) {
String temp[] = new String[3];
temp[0] = rs.getString(“BookId”);
temp[1] = rs.getString(“BookName”);
temp[2] = rs.getString(“BookAuthor”);
vList.add(temp);
}

} catch (Exception e) {
System.err.print(“allBookDetailList Exception : ” + e.getMessage());
}

return vList;
}
public Vector allBookDetailList(String search) throws SQLException {
Vector vList = new Vector();
ResultSet rs = null;
Statement stmt = null;
try {
// String userId=”ID00000000″;
Labcon lc = new Labcon();
con = lc.getLocalConnection();
stmt = con.createStatement();
String strSql = “select BookId,BookName,BookAuthor from bookdetail where BookName LIKE ‘”+search+”%’;”;
rs = stmt.executeQuery(strSql);

while (rs.next()) {
String temp[] = new String[3];
temp[0] = rs.getString(“BookId”);
temp[1] = rs.getString(“BookName”);
temp[2] = rs.getString(“BookAuthor”);
vList.add(temp);
}

} catch (Exception e) {
System.err.print(“allBookDetailList Exception : ” + e.getMessage());
}

return vList;
}
public Vector getRecord(String id) throws SQLException {
Vector vList = new Vector();
ResultSet rs = null;
Statement stmt = null;
try {
Labcon lc = new Labcon();
con = lc.getLocalConnection();
stmt = con.createStatement();
String strSql = “select BookId,BookName,BookAuthor from bookdetail where BookId ='”+id+”‘”;
rs = stmt.executeQuery(strSql);

while (rs.next()) {
String temp[] = new String[3];

temp[0] = rs.getString(“BookId”);
temp[1] = rs.getString(“BookName”);
temp[2] = rs.getString(“BookAuthor”);

vList.add(temp);
}

} catch (Exception e) {

System.err.println(“getRecord Exception : ” + e.getMessage());
}

return vList;
}
public void UpdateBookDetail(book objbook) throws SQLException

{
Connection con1 = null;
Statement stmt = null;
try
{

Labcon lc = new Labcon();
con1 = lc.getLocalConnection();
stmt = con1.createStatement();
String query = “update bookdetail set BookName='”+objbook.getBookName()+”‘,BookAuthor='”+objbook.getBookAuthorName()+”‘ where BookId='”+objbook.getId()+”‘”;
stmt.executeUpdate(query);

}
catch(Exception e)
{
System.err.println(“In UpdateBookDetail Exception “+e.getMessage());
}
}
public void Delete(String Myid) throws SQLException

{
Connection con1 = null;
Statement stmt = null;
try
{

Labcon lc = new Labcon();
con1 = lc.getLocalConnection();
stmt = con1.createStatement();
String query = “delete from bookdetail where BookId=”+Myid+””;
System.err.println(“query in Delete execute–:::”+query);
stmt.executeUpdate(query);

}
catch(Exception e)
{
System.err.println(“In Delete Exception “+e.getMessage());
}

}

}

Upload Image to local drive and path to db

  1. Upload Jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″ session=”true” import =”java.io.File”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Upload Here…</title>
</head>
<body>

function validate() {

if(document.form1.empName.value == null || document.form1.empName.value == “”) {
alert(“Please Select Employee Name”);
return false;
}else if(document.form1.docType.value == null || document.form1.docType.value == “”) {
alert(“Please Select Document Type”);
return false;

}else if( document.form1.attachFile.value == null || document.form1.attachFile.value == “”) {
alert(“Please attach File”);
return false;

}

}

<form action=”./UploadFilesServlet” method=”post” enctype=”multipart/form-data” name=”frm” id=”frm” onsubmit=”return validate()”>
<center>
<table>

<tr><td><b>Employee Name</b>
</td>
<td>
<select name=”empName” >
<option value=”” selected>(please select:)</option>
<option value=”ABC”>ABC</option>
<option value=”DEF”>DEF</option>
<option value=”PQR”>PQR</option>
<option value=”XYZ”>XYZ</option>
</select>
</td>
</tr>

<tr><td><b>Document Type</b>
</td>
<td>
<select name=”docType”>
<option value=”” selected>(please select:)</option>
<option value=”AdhaarCard”>AdhaarCard</option>
<option value=”DrivingLicense”>DrivingLicense</option>
<option value=”VoterId”>VoterId</option>
<option value=”Passport”>Passport</option>
</select>
</td>
</tr>
<tr><td><b>Attach Document</b></td>
<td>
<input type=”file” name=”file” id=”file” size=”50″ />
<input type=”hidden” name=”ok” id=”ok” size=”50″ value= “123”/>

<td>

</tr>
<tr><td style=”color: green”>
<%
HttpSession session1=request.getSession(true);
String val=(String )session1.getAttribute(“AllVal”);
session1.invalidate();
%>
<%= val == null ? “” : val%> </td></tr>
<tr>
<td><a href=”view_files.jsp”>View File</a> </td>
</tr>
<tr>
<td align=”center”>
<input type=”submit” name=”Submit” value=”Submit”/></td><td>
<input type=”reset” name=”Reset” value=”Reset”/>
</td>
</tr>
</table>
</center>
</form>
</body>

</html>

2. UploadFilesServlet

package servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import bean.UploadBean;
import common.CommonUtils;

/**
* Servlet implementation class UploadFilesServlet
*/
public class UploadFilesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public UploadFilesServlet() {
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 {
try {
String savedpath=””;
UploadBean ubean = new UploadBean();
String sysPath = “F:\\git\\Hotel-Management\\Hotel-Management”;
String UPLOAD_DIRECTORY = sysPath + File.separator+ “WebContent”+ File.separator + “images”+ File.separator;
System.out.println(“UPLOAD_DIRECTORY==”+UPLOAD_DIRECTORY);
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
String inputName = null;
String username = null;
String docName = null;
for (FileItem item : multiparts) {

if (item.isFormField()) {
inputName = (String) item.getFieldName();
if (inputName.equalsIgnoreCase(“docType”)) {
docName = (String) item.getString();
ubean.setDocType(docName);
}
if (inputName.equalsIgnoreCase(“empName”)) {
username = (String) item.getString();
ubean.setEmpName(username);
}

}
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
File dir = new File(UPLOAD_DIRECTORY + username+File.separator);
if (!dir.exists()) {
dir.mkdir();
}
int length =name.length();
int dotPos =name.indexOf(“.”);
String formattedName=docName+name.substring(dotPos,length);
item.write(new File(dir + File.separator + formattedName));
savedpath = dir + File.separator + formattedName;
ubean.setImagePath(savedpath);
}

}
CommonUtils common = new CommonUtils();
common.UploadFileToDB(ubean);

HttpSession session1=request.getSession(true);
String ServletVal= ” Hello ” + username + “,”+docName+”- Uploaded successfully”;
session1.setAttribute(“AllVal”, ServletVal);

String L_url1 = response.encodeRedirectURL(“upload_files.jsp”);
response.sendRedirect(L_url1);
} catch (Exception ex) {
System.out.println(“Exception is in UploadFilesServlet ”
+ ex.getMessage());
}
}
}

3. Method to save image to local drive and path to db

public void UploadFileToDB(UploadBean upbean) throws InstantiationException, IllegalAccessException, NamingException {
try{

Connection con = null;
Statement stmt = null;
con = DBCon.getLocalDBConnection();
stmt = con.createStatement();

String imagepath = upbean.getImagePath();
imagepath = imagepath.replace(“\\”, “\\\\”);
CommonFunction cfun = new CommonFunction();
String img_id= cfun.getGenerateId(“IMAGEID”);
String sqlQuery=”INSERT INTO employedetails(empname,doctype,filepath,slno) VALUES (‘”+ upbean.getEmpName() +”‘,'”+ upbean.getDocType() +”‘,'”+ imagepath +”‘,'”+img_id+”‘)”;
System.out.println(“inserting::”+sqlQuery);
stmt.executeUpdate(sqlQuery);
}catch(SQLException ex){
System.out.println(“Exception is in UploadFileToDB method :: ” + ex.getMessage());

}
}

4. view_file.jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″ session=”true” import =”java.io.File,common.CommonUtils,java.util.*”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>View Files Here…</title>
</head>
<body>

function changeFunc() {
document.frm.action=”view_files.jsp”;
document.submit();

}

<form name=”frm” id=”frm” >
<center>
<table>

<tr><td><b>Employee Name</b>
</td>
<td>
<select name=”empName” id=”empName” onchange=”changeFunc();”>
<option value=”” selected>(please select:)</option>
<option value=”ABC”>ABC</option>
<option value=”DEF”>DEF</option>
<option value=”PQR”>PQR</option>
<option value=”XYZ”>XYZ</option>
</select>
</td><td><input type=”submit” name=”View” value=”View”/></td>
</tr>
<tr>
<td><a href=”upload_files.jsp”>Upload File</a> </td>
</tr>
<%
if(request.getParameter(“empName”) != null){
CommonUtils com = new CommonUtils();
ArrayList<String> arr = new ArrayList<String>();
arr=com.getImagePath(request.getParameter(“empName”));
for(int i=0;i<arr.size();i++)
{

String temp =arr.get(i).toString();
int a = temp.indexOf(‘,’);
String temp1 = temp.substring(0, a);

String temp2 = temp.substring(a+1, temp.length());

%>
<tr>
<td>
<a href=”<%=temp1%>”><%=temp2%></a>
</td>
<% }} %>
</tr>

</table>
</center>
</form>
</body>

</html>

5. Method to retrive image path

public ArrayList<String> getImagePath(String empName){
ArrayList<String> arr = new ArrayList<String>();

ResultSet rs;
try{
con = DBCon.getLocalDBConnection();
stmt = con.createStatement();
String query = “SELECT filepath,doctype from employedetails where empname = ‘”+empName+”‘”;
System.out.println(“query=”+query);
rs = stmt.executeQuery(query);
while ( rs.next() ) {
String temp1 =rs.getString(“filepath”);
String temp2 =rs.getString(“doctype”);
arr.add(temp1+”,”+temp2);
}
}catch(Exception ex){
System.out.println(“Exception in getImagePath :: ” + ex.getMessage());
}
return arr;
}

Configuring JNDI DataSource for Database Connection Pooling in a jsp/servlet web application

JNDI (Java Naming and Directory Interface) organizes its names into a hierarchy. A name can be any string such as “com.mydomain.ejb.MyBean”. A name can also be an object that implements the Name interface; however a string is the most common way to name an object. A name is bound to an object in the directory by storing either the object or a reference to the object in the directory service identified by the name.

The JNDI API defines a context that specifies where to look for an object. The initial context is typically used as a starting point.

In the simplest case, an initial context must be created using the specific implementation and extra parameters required by the implementation. The initial context will be used to look up a name. The initial context is analogous to the root or top of a directory tree for a file system.

By getting Connection object using JNDI we have adavntages

1. We no need to worry about object creation and destroy after usage.

2. Performance is more .

3. No Multithreading issues.

The following examples are tested in Tomcat and MySQL Database.

1. Sample MySQL database

First, we need to create a sample database. Let’s execute the following MySQL script:

1
2
3
4
5
6
7
8
9
10
11
create database usersdb;
use usersdb;
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  PRIMARY KEY (`user_id`)
);

That creates a database called usersdb and a table called users. Remember to insert some dummy data into this table.To interact with MySQL database from Java applications, the MySQL Connector/J library must present in the classpath. Here, we need to copy the mysql-connector-java-VERSION-bin.jar file to the $CATALINA_BASE/lib directory. If you have only one Tomcat instance on your computer, then $CATALINA_BASE is the Tomcat’s installation directory, e.g. c:\Program Files\Apache Software Foundation\Tomcat 7.0 on Windows platform. Doing so help Tomcat loads MySQL JDBC driver when it discovers the JNDI DataSource configuration.

2. Configuring context

To declare a JNDI DataSource for the MySQL database above, create a Resource XML element with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
<Resource
    name="jdbc/UsersDB"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="100"
    maxIdle="30"
    maxWait="10000"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/usersDB"
    username="root"
    password="secret"
    />

Add this element inside the root element <Context> in a context.xml file. There are two places where the context.xmlfile can reside (create one if not exist):

  • Inside /META-INF directory of a web application: the JNDI DataSource is only available to the application itself, thus it cannot be shared among other ones. In addition, this makes the configuration dependent on the application.
  • Inside $CATALINA_BASE/conf directory: this is the preferred place because the JNDI DataSource will be available to all web applications and it’s independent of any applications.

Therefore, we declare above Resource element in the context.xml file under the $CATALINA_BASE/conf directory. The following table describes the attributes specified in the above configuration:

Attribute name Description
name Name of the resource.
auth Specify authentication mechanism for the application code, can be Application or Container.
type The fully qualified Java class name expected by the web application when it performs a lookup for this resource.
maxActive Maximum number of database connections in pool. Set to -1 for no limit.
maxIdle Maximum number of idle database connections to retain in pool. Set to -1 for no limit.
maxWait Maximum time to wait for a database connection to become available in ms, in this example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely.
driverClassName The fully qualified Java class name of the database driver. For MySQL Connector/J, it is com.mysql.jdbc.Driver.
url The JDBC connection URL.
username MySQL database user name.
password MySQL database user password.

For more information about the attributes, visit the reference links mentioned the end of this tutorial.NOTES:

  • If you are using Tomcat inside Eclipse IDE, you need to modify the context.xml file under the Servers project. That is because Eclipse made a copy of Tomcat configuration:Modify context.xml in Eclipse
  • If two resources with the same name both declared in the context.xml files under the web application’s META-INFdirectory and in the $CATALINA_BASE/conf directory, then the internal version takes precedence.

3. Configuring web.xml

Add the following declaration into the web.xml file:

1
2
3
4
5
6
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/UsersDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

This is necessary in order to make the JNDI DataSource available to the application under the specified namespacejdbc/UsersDB.

4. Coding test Java servlet

We can look up the configured JNDI DataSource using Java code as follows:

1
2
3
4
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/UsersDB");
Connection conn = ds.getConnection();

After obtaining the connection, we can use it as trivial JDBC code:

1
2
3
4
Statement statement = conn.createStatement();
String sql = "select username, email from users";
ResultSet rs = statement.executeQuery(sql);
// iterates over the result set...

Here’s the source code of an example Java servlet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package net.codejava.jdbc;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
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.sql.DataSource;
/**
 * This servlet class demonstrates how to access a JNDI DataSource that
 * represents a JDBC connection.
 */
@WebServlet("/listUsers")
public class UsersListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/UsersDB");
            Connection conn = ds.getConnection();
            
            Statement statement = conn.createStatement();
            String sql = "select username, email from users";
            ResultSet rs = statement.executeQuery(sql);
            
            int count = 1;
            while (rs.next()) {
                writer.println(String.format("User #%d: %-15s %s", count++,
                        rs.getString("username"), rs.getString("email")));
                
            }
        } catch (NamingException ex) {
            System.err.println(ex);
        } catch (SQLException ex) {
            System.err.println(ex);
        }
    }
}

Java To Read Mail(inbox) Using Your gmail.

First get JavaMail jar file and put them in your classpath.

Then use the following code. Make sure you put valid gmail username and a password.

import java.io.*;
import java.util.*;
import javax.mail.*;

public class ReadMail {

/**
* @param args
*/
public static void main(String[] args) throws Exception {

//Set the host smtp address
Properties props = new Properties();
props.setProperty(“mail.smtp.host”, “smtp.gmail.com”);
props.setProperty(“mail.smtp.socketFactory.port”, “465”);
props.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.auth”, “true”);
props.put(“mail.smtp.port”, “465”);

Session session = Session.getDefaultInstance(props, null);

Store store = session.getStore(“imaps”);
store.connect(“smtp.gmail.com”, “xyz@gmail.com”,”12345″);

//gmail user name=xyz@gmail.com

//gmail password =12345
System.out.println(store);

Folder inbox = store.getFolder(“inbox”);
inbox.open(Folder.READ_WRITE); // Folder.READ_ONLY
int messageCount = inbox.getMessageCount();
System.out.println(“Total Messages” + messageCount);
int startMessage = messageCount – 10;
int endMessage = messageCount;

if (messageCount < 5) {
startMessage = 0;
}

Message[] messages = inbox.getMessages(startMessage, endMessage);

for (Message message : messages) {

boolean isMessageRead = true;

for (Flags.Flag flag : message.getFlags().getSystemFlags()) {
if (flag == Flags.Flag.SEEN) {
isMessageRead = true;
break;
}
}

message.setFlag(Flags.Flag.SEEN, true);
System.out.println(message.getSubject() + ” ”
+ (isMessageRead ? ” [READ]” : ” [UNREAD]”));

}

inbox.close(true);
System.out.println(“Done….”);
store.close();
}
}

Retrieving Columns From Two Tables(Hibernate)

1.Create two tables

CREATE TABLE “BORROW”
( “BOOKID” VARCHAR2(4000 BYTE),
“MEMBERID” VARCHAR2(4000 BYTE),
“DAYOFBORROWED” VARCHAR2(4000 BYTE),
“DAYOFRETURN” VARCHAR2(4000 BYTE),
“BORROWID” VARCHAR2(4000 BYTE) NOT NULL ENABLE,
CONSTRAINT “BORROW_PK” PRIMARY KEY (“BORROWID”)
)

CREATE TABLE “MEMBERS”
( “MEMBERID” VARCHAR2(4000 BYTE) NOT NULL ENABLE,
“LOGINID” VARCHAR2(4000 BYTE),
“LOGINPASSWORD” VARCHAR2(4000 BYTE),
“NAME” VARCHAR2(4000 BYTE),
“EMAIL” VARCHAR2(4000 BYTE),
“MAJOR” VARCHAR2(4000 BYTE),
“NUMBEROFBOOKS” VARCHAR2(4000 BYTE),
“EXPIRED” VARCHAR2(4000 BYTE),
“LOGINREPASSWORD” VARCHAR2(255 CHAR),
CONSTRAINT “MEMBERS_PK” PRIMARY KEY (“MEMBERID”)

)

2.Insert some data in to the tables

3.Create two beans means getter and setter for MEMBERS and BORROW

import java.io.Serializable;

public class BORROW implements Serializable{
String BORROWID=””;
public String getBORROWID() {
return BORROWID;
}
public void setBORROWID(String bORROWID) {
BORROWID = bORROWID;
}
public String getBOOKID() {
return BOOKID;
}
public void setBOOKID(String bOOKID) {
BOOKID = bOOKID;
}
public String getMEMBERID() {
return MEMBERID;
}
public void setMEMBERID(String mEMBERID) {
MEMBERID = mEMBERID;
}
public String getDAYOFBORROWED() {
return DAYOFBORROWED;
}
public void setDAYOFBORROWED(String dAYOFBORROWED) {
DAYOFBORROWED = dAYOFBORROWED;
}
public String getDAYOFRETURN() {
return DAYOFRETURN;
}
public void setDAYOFRETURN(String dAYOFRETURN) {
DAYOFRETURN = dAYOFRETURN;
}
String BOOKID=””;
String MEMBERID=””;
String DAYOFBORROWED=””;
String DAYOFRETURN=””;
}
import java.io.Serializable;

public class MEMBERS implements Serializable{
String MEMBERID=””;
public String getMEMBERID() {
return MEMBERID;
}
public void setMEMBERID(String mEMBERID) {
MEMBERID = mEMBERID;
}
public String getLOGINID() {
return LOGINID;
}
public void setLOGINID(String lOGINID) {
LOGINID = lOGINID;
}
public String getLOGINPASSWORD() {
return LOGINPASSWORD;
}
public void setLOGINPASSWORD(String lOGINPASSWORD) {
LOGINPASSWORD = lOGINPASSWORD;
}
public String getNAME() {
return NAME;
}
public void setNAME(String nAME) {
NAME = nAME;
}
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String eMAIL) {
EMAIL = eMAIL;
}
public String getMAJOR() {
return MAJOR;
}
public void setMAJOR(String mAJOR) {
MAJOR = mAJOR;
}
public String getNUMBEROFBOOKS() {
return NUMBEROFBOOKS;
}
public void setNUMBEROFBOOKS(String nUMBEROFBOOKS) {
NUMBEROFBOOKS = nUMBEROFBOOKS;
}
public String getEXPIRED() {
return EXPIRED;
}
public void setEXPIRED(String eXPIRED) {
EXPIRED = eXPIRED;
}
String LOGINID=””;
String LOGINPASSWORD=””;
String LOGINREPASSWORD=””;
public String getLOGINREPASSWORD() {
return LOGINREPASSWORD;
}
public void setLOGINREPASSWORD(String lOGINREPASSWORD) {
LOGINREPASSWORD = lOGINREPASSWORD;
}
String NAME=””;
String EMAIL=””;
String MAJOR=””;
String NUMBEROFBOOKS=””;
String EXPIRED=””;
}

4. Create hibernate.cfg.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;
<hibernate-configuration>
<session-factory name=””>
<property name=”hibernate.connection.driver_class”>oracle.jdbc.driver.OracleDriver</property>
<property name=”hibernate.connection.password”>anshu</property>
<property name=”hibernate.connection.url”>jdbc:oracle:thin:@localhost:1521:xe</property>
<property name=”hibernate.connection.username”>anshu</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.Oracle10gDialect</property>
<property name=”show_sql”>true</property>
<property name=”format_sql”>true</property>
<property name=”use_sql_comments”>true</property>
<property name=”hbm2ddl.auto”>update</property>
<property name=”connection.pool_size”>16</property>
<mapping class=”beans.BOOKS” resource=”beans/BOOKS.hbm.xml”/>
<mapping class=”beans.MEMBERS” resource=”beans/MEMBERS.hbm.xml”/>
<mapping class=”beans.BORROW” resource=”beans/BORROW.hbm.xml”/>
</session-factory>
</hibernate-configuration>

5.create BORROW.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;
<!– Generated Jul 22, 2013 5:02:47 PM by Hibernate Tools 3.4.0.CR1 –>
<hibernate-mapping>
<class name=”beans.BORROW” table=”BORROW”>
<id name=”BORROWID” type=”java.lang.String”>
<generator class=”sequence”>
<param name=”sequence”>BORROW_ID</param>
</generator></id>
<property name=”BOOKID” type=”java.lang.String”>
<column name=”BOOKID” />
</property>
<property name=”MEMBERID” type=”java.lang.String”>
<column name=”MEMBERID” />
</property>
<property name=”DAYOFBORROWED” type=”java.lang.String”>
<column name=”DAYOFBORROWED” />
</property>
<property name=”DAYOFRETURN” type=”java.lang.String”>
<column name=”DAYOFRETURN” />
</property>
</class>
</hibernate-mapping>

create MEMBERS.hbm.xml file

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;
<!– Generated Jul 22, 2013 10:46:41 AM by Hibernate Tools 3.4.0.CR1 –>
<hibernate-mapping>
<class name=”beans.MEMBERS” table=”MEMBERS”>
<id name=”MEMBERID” type=”java.lang.String”>
<generator class=”sequence”>
<param name=”sequence”>MEMBER_ID</param>
</generator></id>
<property name=”LOGINID” type=”java.lang.String”>
<column name=”LOGINID” />
</property>
<property name=”LOGINPASSWORD” type=”java.lang.String”>
<column name=”LOGINPASSWORD” />
</property>
<property name=”LOGINREPASSWORD” type=”java.lang.String”>
<column name=”LOGINREPASSWORD” />
</property>
<property name=”NAME” type=”java.lang.String”>
<column name=”NAME” />
</property>
<property name=”EMAIL” type=”java.lang.String”>
<column name=”EMAIL” />
</property>
<property name=”MAJOR” type=”java.lang.String”>
<column name=”MAJOR” />
</property>
<property name=”NUMBEROFBOOKS” type=”java.lang.String”>
<column name=”NUMBEROFBOOKS” />
</property>
<property name=”EXPIRED” type=”java.lang.String”>
<column name=”EXPIRED” />
</property>
</class>
</hibernate-mapping>

6.Create a jsp i.e. returningbook.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″ import=”sourceclass.*,java.util.*,beans.*”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Return</title>
<script>
function onMembID(){
document.frm.action=”returningbook.jsp”;
document.frm.submit();
}
</script>
</head>
<body>
<%@include file=”mainpage.jsp”%>
<form name=frm method=”post”>
<table>
<THEAD>
<tr><td colspan=”7″ align=”center”><b><font size=”3″>Return Book</font></b></td>
</tr>
</THEAD>
<tr><TD><B>Member Name</B></TD>
<TD><SELECT id=”cbomembID” name=”cbomembID” onchange=”onMembID()” >
<OPTION selected value=””>Select Member</OPTION>
<%String mid =””;
MemberDetails mdet1 = new MemberDetails();
List<MEMBERS> list1 = mdet1.getListOfMemberNames();
for (MEMBERS m1 : list1) {
if((request.getParameter(“cbomembID”)!=null)&&(request.getParameter(“cbomembID”).trim().equalsIgnoreCase(m1.getMEMBERID().trim()))){
out.println(“<OPTION value='”+m1.getMEMBERID()+”‘ selected>”+m1.getNAME()+”</OPTION>”);
mid=m1.getMEMBERID();
}else{
out.println(“<OPTION value='”+m1.getMEMBERID()+”‘>”+m1.getNAME()+”</OPTION>”);
}
}
%>
</SELECT></TD>
</tr>

<%
MemberDetails mdet = new MemberDetails();
List mylist=new ArrayList();
mylist=mdet.ListgetMemberBorrowedDetails(mid);
Object[] row1 =new Object[10];
for(Iterator it=mylist.iterator();it.hasNext();){
row1 = (Object[]) it.next();

}
%>

<tr>
<td>Member Name</td>
<td><INPUT type=”text” name=”membName” value=”<%=row1[2].toString()%>” size=”24″ ></td>
</tr>
<tr>
<td>Borrowed Day</td>
<td><INPUT type=”text” name=”membBorrwedDate” value=”<%=row1[0].toString()%>” size=”24″></td>
</tr>
<tr>
<td>Return Day</td>
<td><INPUT type=”text” name=”membReturnDate” value=”<%=row1[1].toString()%>” size=”24″></td>
</tr>
</table>
</form>
</body>
</html>

6.For member name combo box value write a method using hibernate in MemberDetails class

public List<MEMBERS> getListOfMemberNames(){
List<MEMBERS> list = new ArrayList<MEMBERS>();
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
try {
tx = session.getTransaction();
tx.begin();
list = session.createQuery(“from MEMBERS”).list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}

7. On select combo box — filling remaining value we have to write a method

public List ListgetMemberBorrowedDetails(String mid){

SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
List ls = new ArrayList();
try {
tx = session.getTransaction();
tx.begin();
System.out.println(“getMemberBorrowedDetails(String mid) method-“+mid);
String SQL_QUERY =”select b.DAYOFBORROWED,b.DAYOFRETURN,m.NAME from MEMBERS m,BORROW b where b.MEMBERID='”+mid+”‘ and b.MEMBERID = m.MEMBERID “;
Query query = session.createQuery(SQL_QUERY) ;
for(Iterator it=query.iterate();it.hasNext();){
Object[] row = (Object[]) it.next();
ls.add(row);
}

tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return ls;
}

Add and Update Check box values(JSP-Servlet-Hibernate)

This method for validate and insert the data into database

1.Create CHECKBOX table

CREATE TABLE “ANSHU”.”CHECKBOX”
( “LANGUAGE_ID” VARCHAR2(4000 BYTE) NOT NULL ENABLE,
“LANGUAGE” VARCHAR2(4000 BYTE)
)

2.Create a Sequence

CREATE SEQUENCE  “ANSHU”.”SEQ_LANGUAGE”  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 4 NOCACHE  NOORDER  NOCYCLE ;

3.Create checkbox.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><script type=”text/javascript”>function CheckVal(chk){chk.value=chk.checked?”on”:”0″; }function ValidateForm(){
var chk=0;

if(document.frm.hindi.checked)    {    chk=1;     }    if(document.frm.english.checked)    {    chk=1;        }    if(document.frm.kanada.checked)   {    chk=1;   }  if(document.frm.tamil.checked)   {  chk=1;   }  if(document.frm.telegu.checked)   {  chk=1;   }     if(chk==0){ alert(“Please Check Language”); return false;} return true;}function on_save(){ if(!ValidateForm()) return;{   document.frm.action=”AddCheckbox”;  document.frm.submit();  }}
</script></head><body> <form name=”frm” method=”post”> <table><tr><td>Language Knows</td><td><input type=”checkbox” name=”hindi”  onclick=”CheckVal(document.frm.hindi)”/>Hindi<input type=”checkbox” name=”english”  onclick=”CheckVal(document.frm.english)” />English<input type=”checkbox” name=”kanada”  onclick=”CheckVal(document.frm.kanada)”/>Kanada<input type=”checkbox” name=”tamil”  onclick=”CheckVal(document.frm.tamil)”/>Tamil<input type=”checkbox” name=”telegu”  onclick=”CheckVal(document.frm.telegu)”/>Telegu</tr></table> <BUTTON type=”button”  value=”Add CheckBox” name=”Add CheckBox” onclick=”on_save()”>Add CheckBox</BUTTON></form></body></html>

4.Create CHECKBOX bean file

public class CHECKBOX implements Serializable{
String Language_ID=””;
public String getLanguage_ID() {
return Language_ID;
}
public void setLanguage_ID(String language_ID) {
Language_ID = language_ID;
}
public String getLanguage() {
return Language;
}
public void setLanguage(String language) {
Language = language;
}
String Language=””;}

5.create CHECKBOX.hbm.xml file

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;
<!– Generated Jul 16, 2013 1:41:40 PM by Hibernate Tools 3.4.0.CR1 –>
<hibernate-mapping>
<class name=”bean.CHECKBOX” table=”CHECKBOX”>
<id name=”Language_ID” type=”java.lang.String”>
<column name=”LANGUAGE_ID” />
<generator class=”sequence”>
<param name=”sequence”>SEQ_LANGUAGE</param>
</generator>
</id>
<property name=”Language” type=”java.lang.String”>
<column name=”LANGUAGE” />
</property>
</class>
</hibernate-mapping>

6.create hibernate.cfg.xml file

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;
<hibernate-configuration>
<session-factory name=””>
<property name=”hibernate.connection.driver_class”>oracle.jdbc.driver.OracleDriver</property>
<property name=”hibernate.connection.password”>hello</property>
<property name=”hibernate.connection.url”>jdbc:oracle:thin:@localhost:1521:xe</property>
<property name=”hibernate.connection.username”>hello</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.Oracle10gDialect</property>
<property name=”hibernate.show_sql”>true</property>
<mapping resource=”bean/CHECKBOX.hbm.xml”/>
</session-factory>
</hibernate-configuration>

7.Create AddCheckbox servlet

package sample;

import generalClass.PatientsInformation;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.*;
/**
* Servlet implementation class AddCheckbox
*/
public class AddCheckbox extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public AddCheckbox() {
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
try {
CHECKBOX checkObj = new CHECKBOX();
String checkboxVal=checkObj.CheckVal1(request.getParameter(“hindi”))+”,”+checkObj.CheckVal1(request.getParameter(“english”))+”,”+checkObj.CheckVal1(request.getParameter(“kanada”))+”,”+checkObj.CheckVal1(request.getParameter(“tamil”))+”,”+checkObj.CheckVal1(request.getParameter(“telegu”))+”,”;
System.out.println(“checkboxVal-“+checkboxVal);
checkObj.setLanguage(checkboxVal);
checkObj.InserCheckBox(checkObj);
String L_url1=response.encodeRedirectURL(“checkbox.jsp”);
response.sendRedirect(L_url1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

8.Write a method CheckVal1

public String CheckVal1(String val)
{
String c=”on”;
if(val!=null)
{
return val;
}
else
{
return “0”;
}

}

9.write a method  for insert the data into database

public void InserCheckBox(CHECKBOX chkobj) throws SQLException {

try{
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
session.save(chkobj);
tx.commit();
}
catch(Exception ex){
System.out.println(“Exception InsertCheckBox method-“+ex.getMessage());
}
}

10.Run checkbox.jsp

chk————————————————————————————————-

This code for edit and update the radio button values

1.Create editCheckbox.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″ import=”generalClass.*,java.util.*,bean.*”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Insert title here</title>
<script type=”text/javascript”>
function CheckVal(chk)
{
chk.value=chk.checked?”on”:”0″;
}
function ValidateForm()
{

var chk=0;
if(document.frm.hindi.checked)
{
chk=1;

}
if(document.frm.english.checked)
{
chk=1;

}
if(document.frm.kanada.checked)
{
chk=1;

}
if(document.frm.tamil.checked)
{
chk=1;

}
if(document.frm.telegu.checked)
{
chk=1;

}

if(chk==0)
{
alert(“Please Check Language”);
return false;
}
return true;
}
function on_save()
{
if(!ValidateForm()) return;
{
document.frm.action=”UpdateCheckbox”;
document.frm.submit();
}
}
function onchkID(){
document.frm.action=”editCheckbox.jsp”;
document.frm.submit();
}
</script>
</head>
<body>
<form name=”frm” method=”post”>
<table>
<tr><TD><B>Language ID</B></TD>
<TD><SELECT id=”cbochkID” name=”cbochkID” onchange=”onchkID()” >
<OPTION selected value=””>Select LanguageID</OPTION>
<%String chkid =””;
CHECKBOX chkObj = new CHECKBOX();
List<CHECKBOX> list1 = chkObj.getChkIDs();
for (CHECKBOX u1 : list1) {
if((request.getParameter(“cbochkID”)!=null)&&(request.getParameter(“cbochkID”).trim().equalsIgnoreCase(u1.getLanguage_ID().trim()))){
out.println(“<OPTION value='”+u1.getLanguage_ID()+”‘ selected>”+u1.getLanguage_ID()+”</OPTION>”);
chkid=u1.getLanguage_ID();
}else{
out.println(“<OPTION value='”+u1.getLanguage_ID()+”‘>”+u1.getLanguage_ID()+”</OPTION>”);
}
}
%>
</SELECT></TD>
</tr>
<%
CHECKBOX checkObj = new CHECKBOX();
List<CHECKBOX> mylist=new ArrayList<CHECKBOX>();
CHECKBOX e = new CHECKBOX();
mylist=checkObj.getCheckBox(chkid);
System.out.println(“–size-*”+mylist.size());
Iterator it=mylist.iterator();
while(it.hasNext())
{
e=(CHECKBOX)it.next();
}
%>
<tr>

<%!
private String checkNull(String valStr){

if(valStr==null || valStr.equals(“null”))
return “”;
return valStr;
}
String strOldSel=null;
%>
<%
Vector vChk=new Vector();
String [] chkboxObj = new String[6];
vChk=checkObj.getDelimitedList(e.getLanguage(),”,”);
for(int i=0;i<vChk.size();i++){
chkboxObj[i]=checkObj.Val((String)vChk.get(i));
}
%>
<tr>
<td>Language Knows</td>
<td>
<%if(checkNull(chkboxObj[0]).equals(“on”)){%>
<INPUT type=”checkbox” name=”hindi” size=”18″ onclick=”CheckVal(document.frm.hindi)” checked=”checked”>
<%}else{%>
<INPUT type=”checkbox” name=”hindi” size=”18″ onclick=”CheckVal(document.frm.hindi)”>
<%}%>hindi
<%if(checkNull(chkboxObj[1]).equals(“on”)){%>
<INPUT type=”checkbox” name=”english” size=”18″ onclick=”CheckVal(document.frm.english)” checked=”checked”>
<%}else{%>
<INPUT type=”checkbox” name=”english” size=”18″ onclick=”CheckVal(document.frm.english)”>
<%}%>english
<%if(checkNull(chkboxObj[2]).equals(“on”)){%>
<INPUT type=”checkbox” name=”kanada” size=”18″ onclick=”CheckVal(document.frm.kanada)” checked=”checked”>
<%}else{%>
<INPUT type=”checkbox” name=”kanada” size=”18″ onclick=”CheckVal(document.frm.kanada)”>
<%}%>kanada
<%if(checkNull(chkboxObj[3]).equals(“on”)){%>
<INPUT type=”checkbox” name=”tamil” size=”18″ onclick=”CheckVal(document.frm.tamil)” checked=”checked”>
<%}else{%>
<INPUT type=”checkbox” name=”tamil” size=”18″ onclick=”CheckVal(document.frm.tamil)”>
<%}%>tamil
<%if(checkNull(chkboxObj[4]).equals(“on”)){%>
<INPUT type=”checkbox” name=”telegu” size=”18″ onclick=”CheckVal(document.frm.telegu)” checked=”checked”>
<%}else{%>
<INPUT type=”checkbox” name=”telegu” size=”18″ onclick=”CheckVal(document.frm.telegu)”>
<%}%>telegu
</tr>
</table>
<BUTTON type=”button” value=”Add CheckBox” name=”Add CheckBox” onclick=”on_save()”>Update CheckBox</BUTTON>
</form>
</body>
</html>

2.Write a servlet UpdateCheckbox

package sample;

import java.io.IOException;
import java.sql.SQLException;

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

import bean.CHECKBOX;

/**
* Servlet implementation class UpdateCheckbox
*/
public class UpdateCheckbox extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public UpdateCheckbox() {
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
try {
CHECKBOX checkObj = new CHECKBOX();
String checkboxVal=checkObj.CheckVal1(request.getParameter(“hindi”))+”,”+checkObj.CheckVal1(request.getParameter(“english”))+”,”+checkObj.CheckVal1(request.getParameter(“kanada”))+”,”+checkObj.CheckVal1(request.getParameter(“tamil”))+”,”+checkObj.CheckVal1(request.getParameter(“telegu”))+”,”;
System.out.println(“checkboxVal-“+checkboxVal);
checkObj.setLanguage_ID(request.getParameter(“cbochkID”));
checkObj.setLanguage(checkboxVal);
checkObj.updateCheckBox(checkObj);
String L_url1=response.encodeRedirectURL(“editCheckbox.jsp”);
response.sendRedirect(L_url1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

3.Write three methods

i)getChkIDs->For combo-box values

public List<CHECKBOX> getChkIDs(){
List<CHECKBOX> list = new ArrayList<CHECKBOX>();
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
try {
tx = session.getTransaction();
tx.begin();
list = session.createQuery(“from CHECKBOX”).list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}

ii)getCheckBox(String chkid)->on select combobox checkbox values will come

public List<CHECKBOX> getCheckBox(String chkid){
List<CHECKBOX> list = new ArrayList<CHECKBOX>();
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
try {
tx = session.getTransaction();
tx.begin();
System.out.println(“getCheckBox(String chkid) method-“+chkid);
String SQL_QUERY =”from CHECKBOX where LANGUAGE_ID='”+chkid+”‘”;
List query = session.createQuery(SQL_QUERY).list();
Iterator it=query.iterator();
while(it.hasNext())
{
CHECKBOX e=(CHECKBOX)it.next();
System.out.println(“in side while loop method-“+e.getLanguage());
list.add(e);
}
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}

iii)getDelimitedList method->it helps you to eliminate comma(,)

public Vector getDelimitedList(String temp,String deLimitType){
int i =0;
boolean flag=true;
Vector tempList = new Vector();
if(temp.length()>0){
while(flag){
i= temp.indexOf(deLimitType);
String str = temp.substring(0,i);
tempList.addElement(str);
temp = temp.substring(i+1,temp.length());
i=0;
if(temp.length()>0)
flag=true;
i= temp.indexOf(deLimitType);
if (i<=0){
i=temp.length();
flag=false;
}
}
}
return tempList;
}

iv)write a method val

public String Val(String str)
{
return (str.equals(“0″))?””:str;
}

v)updateCheckBox->update the database value

public void updateCheckBox(CHECKBOX chkobj) throws SQLException {

try{
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
System.out.println(“###”+chkobj.getLanguage());
Query query = session.createQuery(“update CHECKBOX set LANGUAGE='”+chkobj.getLanguage()+”‘where LANGUAGE_ID='”+chkobj.getLanguage_ID()+”‘”);
int result = query.executeUpdate();
tx.commit();
}
catch(Exception ex){
System.out.println(“exception updateCheckBox method-“+ex.getMessage());
}
}

4.Run editCheckbox.jsp

Upchk

Add and Update Radio Button Values(JSP-Servlet-Hibernate)

This code for validate and insert radio button values into database

1.Create a table

CREATE TABLE “RADIOBUTTON”
( “GENDER_ID” VARCHAR2(4000 BYTE),
“GENDER” VARCHAR2(4000 BYTE))

2. create a sequence for gender_id

CREATE SEQUENCE  “SEQ_GENDER”  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 4 NOCACHE  NOORDER  NOCYCLE ;

3.create checkbox.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”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Insert title here</title>
<script type=”text/javascript”>
function ValidateForm()
{

var rad=0;

for (i=0;i<document.frm.gender.length;i++)
{
if (document.frm.gender[i].checked)
{
rad=1;
}
}
if(rad==0)
{
alert(“Select Gender”);
return false;
}

return true;
}
function on_save()
{
if(!ValidateForm()) return;
{
document.frm.action=”Addradiobutton”;
document.frm.submit();
}
}

</script>
</head>
<body>
<form name=”frm” method=”post”>
<table>
<tr>
<td>Gender :</td>
<td><input type=”radio” name=”gender” value=”m” />Male
<input type=”radio” name=”gender” value=”f” />Female
</tr>
</table>
<BUTTON type=”button” value=”Add Radio” name=”Add Radio” onclick=”on_save()”>Add Radio</BUTTON>

</form>
</body>
</html>

4.create a ‘RADIOBUTTON’ bean means getter and setter

public class RADIOBUTTON implements Serializable{

String Gender_ID=””;
public String getGender_ID() {
return Gender_ID;
}
public void setGender_ID(String gender_ID) {
Gender_ID = gender_ID;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
String Gender=””;

}

5.write a hibernate.cfg.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;
<hibernate-configuration>
<session-factory name=””>
<property name=”hibernate.connection.driver_class”>oracle.jdbc.driver.OracleDriver</property>
<property name=”hibernate.connection.password”>hello</property>
<property name=”hibernate.connection.url”>jdbc:oracle:thin:@localhost:1521:xe</property>
<property name=”hibernate.connection.username”>hello</property>
<property name=”hibernate.dialect”>org.hibernate.dialect.Oracle10gDialect</property>
<property name=”hibernate.show_sql”>true</property>

<mapping resource=”bean/RADIOBUTTON.hbm.xml”/>

</session-factory>
</hibernate-configuration>

6.write RADIOBUTTON.hbm.xml file

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;
<!– Generated Jul 16, 2013 12:29:28 PM by Hibernate Tools 3.4.0.CR1 –>
<hibernate-mapping>
<class name=”bean.RADIOBUTTON” table=”RADIOBUTTON”>
<id name=”Gender_ID” type=”java.lang.String”>
<column name=”GENDER_ID” />
<generator class=”sequence”>
<param name=”sequence”>SEQ_GENDER</param>
</generator>
</id>
<property name=”Gender” type=”java.lang.String”>
<column name=”GENDER” />
</property>
</class>
</hibernate-mapping>

7.write Addradiobutton servlet

package sample;

import java.io.IOException;
import java.sql.SQLException;

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

import bean.RADIOBUTTON;

/**
* Servlet implementation class Addradiobutton
*/
public class Addradiobutton extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Addradiobutton() {
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
try {
RADIOBUTTON radObj= new RADIOBUTTON();
radObj.setGender(request.getParameter(“gender”));

radObj.InserRadio(radObj);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String L_url1=response.encodeRedirectURL(“radiobutton.jsp”);
response.sendRedirect(L_url1);
}

}

8. Write a method ‘InserRadio’ for insert the data into database

public void InserRadio(RADIOBUTTON radobj) throws SQLException {

try{
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
session.save(radobj);
tx.commit();
}
catch(Exception ex){
System.out.println(“Exception InserRadio method-“+ex.getMessage());
}
}

9.Run radiobutton.jsp

addcheck

————————————————————————————————-

This code for update radio button values into database

1.create editRadiobutton.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″ import=”generalClass.*,java.util.*,bean.*”%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Insert title here</title>
<script type=”text/javascript”>
function ValidateForm()
{

var rad=0;

for (i=0;i<document.frm.gender.length;i++)
{
if (document.frm.gender[i].checked)
{
rad=1;
}
}
if(rad==0)
{
alert(“Select Gender”);
return false;
}

return true;
}
function on_save()
{
if(!ValidateForm()) return;
{
document.frm.action=”UpdateRadiobutton”;
document.frm.submit();
}
}
function onradID(){
document.frm.action=”editRadiobutton.jsp”;
document.frm.submit();
}
</script>
</head>
<body>
<form name=”frm” method=”post”>
<table>
<tr><TD><B>Patient Name</B></TD>
<TD><SELECT id=”cboradID” name=”cboradID” onchange=”onradID()” >
<OPTION selected value=””>Select RadioID</OPTION>
<%String rid =””;
RADIOBUTTON radObj = new RADIOBUTTON();
List<RADIOBUTTON> list1 = radObj.getRAdioIDs();
for (RADIOBUTTON u1 : list1) {
if((request.getParameter(“cboradID”)!=null)&&(request.getParameter(“cboradID”).trim().equalsIgnoreCase(u1.getGender_ID().trim()))){
out.println(“<OPTION value='”+u1.getGender_ID()+”‘ selected>”+u1.getGender_ID()+”</OPTION>”);
rid=u1.getGender_ID();
}else{
out.println(“<OPTION value='”+u1.getGender_ID()+”‘>”+u1.getGender_ID()+”</OPTION>”);
}
}
%>
</SELECT></TD>
</tr>
<%

List<RADIOBUTTON> mylist=new ArrayList<RADIOBUTTON>();
RADIOBUTTON e = new RADIOBUTTON();
mylist=radObj.getRadioName(rid);
System.out.println(“–size-*”+mylist.size());
Iterator it=mylist.iterator();
while(it.hasNext())
{
e=(RADIOBUTTON)it.next();
}
%>
<tr>
<td>Gender :</td><td>
<%if(e.getGender().equals(“m”)){%>
<INPUT type=”radio” size=”18″ value=”m” name=”gender” CHECKED>Male

<%}else{%>
<INPUT type=”radio” size=”18″ value=”m” name=”gender”>Male
<%}%>
<%if(e.getGender().equals(“f”)){%>
<INPUT type=”radio” tabIndex=5 size=”19″ value=”f” name=”gender” CHECKED>Female

<%}else{%>
<INPUT type=”radio” size=”19″ value=”f” name=”gender”>Female
<%}%>
</td>
</tr>
</table>
<BUTTON type=”button” value=”Add Radio” name=”Add Radio” onclick=”on_save()”>Update Radio</BUTTON>

</form>
</body>
</html>

2.Write a UpdateRadiobutton servlet

package sample;

import java.io.IOException;
import java.sql.SQLException;

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

import bean.RADIOBUTTON;

/**
* Servlet implementation class UpdateRadiobutton
*/
public class UpdateRadiobutton extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public UpdateRadiobutton() {
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
try {
RADIOBUTTON radObj= new RADIOBUTTON();
radObj.setGender(request.getParameter(“gender”));
radObj.setGender_ID(request.getParameter(“cboradID”));
radObj.updateRadio(radObj);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String L_url1=response.encodeRedirectURL(“editRadiobutton.jsp”);
response.sendRedirect(L_url1);
}

}

3.Write three methods

i)getRAdioIDs()->For combo box values

public List<RADIOBUTTON> getRAdioIDs(){
List<RADIOBUTTON> list = new ArrayList<RADIOBUTTON>();
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
try {
tx = session.getTransaction();
tx.begin();
list = session.createQuery(“from RADIOBUTTON”).list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}

ii)getRadioName(String rid)->on select combobox radio button value will come.

public List<RADIOBUTTON> getRadioName(String rid){
List<RADIOBUTTON> list = new ArrayList<RADIOBUTTON>();
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
try {
tx = session.getTransaction();
tx.begin();
System.out.println(“getRadioName(String rid) method-“+rid);
String SQL_QUERY =”from RADIOBUTTON where GENDER_ID='”+rid+”‘”;
List query = session.createQuery(SQL_QUERY).list();
Iterator it=query.iterator();
while(it.hasNext())
{
RADIOBUTTON e=(RADIOBUTTON)it.next();
System.out.println(“in side while loop method-“+e.getGender());
list.add(e);
}
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}

iii)updateRadio(RADIOBUTTON Radobj)->For update the radio button values

public void updateRadio(RADIOBUTTON Radobj) throws SQLException {
try{
SessionFactory sessFact = new Configuration().configure().buildSessionFactory();
Transaction tx = null;
Session session = sessFact.openSession();
tx = session.beginTransaction();
System.out.println(“###”+Radobj.getGender_ID());
Query query = session.createQuery(“update RADIOBUTTON set GENDER='”+Radobj.getGender()+”‘ where GENDER_ID='”+Radobj.getGender_ID()+”‘”);
int result = query.executeUpdate();
tx.commit();
}
catch(Exception ex){
System.out.println(“exception updateDetails method-“+ex.getMessage());
}
}

4.Run editRadiobutton.jspup1

How to read Web.xml file

Here is web.xml

<<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; id=”WebApp_ID” version=”2.5″>
<display-name>Hotel-Management</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>

<context-param>
<param-name>db_name</param-name>
<param-value>test</param-value>
</context-param>
<context-param>
<param-name>dbuser_name</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>dbuser_pwd</param-name>
<param-value>root</param-value>
</context-param>

<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>RoomBookingServlet</display-name>
<servlet-name>RoomBookingServlet</servlet-name>
<servlet-class>servlet.RoomBookingServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>RoomBookingServlet</servlet-name>
<url-pattern>/RoomBookingServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>TableBookingServlet</display-name>
<servlet-name>TableBookingServlet</servlet-name>
<servlet-class>servlet.TableBookingServlet</servlet-class>

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

</web-app>

now here is DBDETAIL servlet

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

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

/**
* Servlet implementation class DBDETAIL
*/
public class DBDETAIL extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public DBDETAIL() {
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

try {
ServletContext servletContext = getServletContext();
String db_name=servletContext.getInitParameter(“db_name”);
String db_user_name=servletContext.getInitParameter(“dbuser_name”);
String db_user_pwd=servletContext.getInitParameter(“dbuser_pwd”);

} catch (IOException ex) {
ex.printStackTrace();
}
}

}

Write & Read Properties File

Java code for writing something in .properties files.

create a config.properties file in C:/Users/readwrite folder then run this code

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class WriteProperties {
public static void main(String[] args) {
Properties prop = new Properties();
try {
//set the properties value
prop.setProperty(“uploadDate”, “12-03-2013”);

//save properties to project root folder
prop.store(new FileOutputStream(“C:/Users/readwrite/config.properties”), null);

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

————————————————————————————

Java code for reading above config.properties files.

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadProperties {
public static void main(String[] args) {

try {
Properties properties = new Properties();
properties.load(new FileInputStream(“C:/Users/readwrite/config.properties/config.properties”));
String update = properties.getProperty(“uploadDate”);
System.out.println(“date is:”+update);
} catch (IOException e)
{
System.out.println(e);
}
}
}