overview of this exampel and download

Monday, March 8, 2010 Posted by Unknown 7 comments
MVC example download 


install java and netbeans
open netbeans and open project and select this project
install mysql and install sql yog
copy mysql connect jar files to tomcat server lib folder
open sql yog and go to tools and import db.sql file 
and run project
if you have any doubts please submit comment  
 
Labels:

Delete selected record

Posted by Unknown 0 comments
in this post we will delete selected record from view.jsp page
for this we will create deleteDetails method in dbclass

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.UserBean;
import validation.ValidateForm;
import database.DBClass;
import java.util.List;
/**
*
* @author Jagadeesh
*/
public class ControllerServlet extends HttpServlet {

//declare values to get form values from jsp page
String userName;
String dateOfBirth;
String email;
String phoneNo;
String action;

UserBean bean = new UserBean();
ValidateForm validateform = new ValidateForm();
DBClass dbobject = new DBClass();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//get the values from jsp page
userName = request.getParameter("userName");
dateOfBirth = request.getParameter("dateOfBirth");
email = request.getParameter("email");
phoneNo = request.getParameter("phoneNo");
action = request.getParameter("action");
if(action.equals("submit"))
{
//set values to bean.For this call below method
setValuesToBean();

//check all form values are valid or not. send bean object
UserBean checkedbean = validateform.validateData(bean);
if(!checkedbean.getIsValid())
{

//if data is invalid.set bean object in request and pass that request to
//insertupdate.jsp using forward
checkedbean.setAction("submit");
request.setAttribute("error",checkedbean);

RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
//now display errors in that jsp page
}
else
{
//using DBClass object call insertDetails method and pass bean object
dbobject.insertDetails(bean);
List list = dbobject.getAlldetails();
request.setAttribute("list", list);
//forward to insertupdate page using requestdispatcher
RequestDispatcher rd= request.getRequestDispatcher("view.jsp");
//display a message to client.store message in request object
//forwarding to jsp
rd.forward(request, response);


}
}
if(action.equals("edit"))
{
//get userdetails of particular name
UserBean ubean = dbobject.getDetails(userName);
request.setAttribute("updateuser",ubean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
}
if(action.equals("update"))
{
setValuesToBean();
UserBean checkedbean = validateform.validateData(bean);
if(!checkedbean.getIsValid())
{

//if data is invalid.set bean object in request and pass that request to
//insertupdate.jsp using forward
checkedbean.setAction("update");
request.setAttribute("error",checkedbean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
//now display errors in that jsp page
}
else
{
//using DBClass object call insertDetails method and pass bean object
dbobject.UpateDetails(bean,userName);
List list = dbobject.getAlldetails();
request.setAttribute("list", list);
//forward to insertupdate page using requestdispatcher
RequestDispatcher rd= request.getRequestDispatcher("view.jsp");
//display a message to client.store message in request object
//forwarding to jsp
rd.forward(request, response);


}

}
if(action.equals("delete"))
{
//delete userdetails of particular name
dbobject.deleteDetails(userName);
RequestDispatcher rd = request.getRequestDispatcher("view.jsp");
rd.forward(request, response);
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
//this method is used to setvalues to bean
public void setValuesToBean()
{
bean.setUserName(userName);
bean.setDateOfBirth(dateOfBirth);
bean.setEmail(email);
bean.setPhoneNo(phoneNo);

}


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


public String getServletInfo() {
return "Short description";
}

}

create method in DBClass
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.UserBean;

/**
*
* @author Jagadeesh
*/
public class DBClass {
public Connection createConnection() throws ClassNotFoundException,SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdbase", "root", "root");
return connection;
}
//we get values from servlet by passing bean object to insertdetails method
public int insertDetails(UserBean bb) throws SQLException, ClassNotFoundException
{
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("insert into userdetails values(?,?,?,?)");
//set values to prepared statement object by getting values from bean object
pstmt.setString(1,bb.getUserName());
pstmt.setString(2,bb.getDateOfBirth());
pstmt.setString(3,bb.getEmail());
pstmt.setString(4,bb.getPhoneNo());
int i = pstmt.executeUpdate();
return i;

}
public List getAlldetails()throws SQLException, ClassNotFoundException
{

Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("select * from userdetails");
ResultSet rs = pstmt.executeQuery();
List list = new ArrayList();
while(rs.next())
{
UserBean ubean = new UserBean();
ubean.setUserName(rs.getString(1));
ubean.setDateOfBirth(rs.getString(2));
ubean.setEmail(rs.getString(3));
ubean.setPhoneNo(rs.getString(4));
list.add(ubean);

}
return list;
}
public UserBean getDetails(String uname)throws SQLException, ClassNotFoundException
{
//here we will write code to get a single record from database
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("select * from userdetails where user_name=?");
pstmt.setString(1, uname);
ResultSet rs = pstmt.executeQuery();
List list = new ArrayList();
UserBean ubean = new UserBean();
while(rs.next())
{

ubean.setUserName(rs.getString(1));
ubean.setDateOfBirth(rs.getString(2));
ubean.setEmail(rs.getString(3));
ubean.setPhoneNo(rs.getString(4));
}
ubean.setAction("update");
return ubean;
}
public void UpateDetails(UserBean ubean, String name)throws SQLException, ClassNotFoundException
{

Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("update userdetails set date_of_birth=?,e_mail=?,phone_no=? where user_name=? ");
//set values to prepared statement object by getting values from bean object
pstmt.setString(1,ubean.getDateOfBirth());
pstmt.setString(2,ubean.getEmail());
pstmt.setString(3,ubean.getPhoneNo());
pstmt.setString(4,name);
pstmt.executeUpdate();


}
public void deleteDetails(String uname)throws SQLException, ClassNotFoundException
{
//here we will write code to get a single record from database
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("delete * from userdetails where user_name=?");
pstmt.setString(1, uname);

}

}
in next post we will see all files we created
Labels:

updating selected record

Posted by Unknown 9 comments
in this post we will create method for uploading record
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.UserBean;
import validation.ValidateForm;
import database.DBClass;
import java.util.List;
/**
*
* @author Jagadeesh
*/
public class ControllerServlet extends HttpServlet {

//declare values to get form values from jsp page
String userName;
String dateOfBirth;
String email;
String phoneNo;
String action;

UserBean bean = new UserBean();
ValidateForm validateform = new ValidateForm();
DBClass dbobject = new DBClass();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//get the values from jsp page
userName = request.getParameter("userName");
dateOfBirth = request.getParameter("dateOfBirth");
email = request.getParameter("email");
phoneNo = request.getParameter("phoneNo");
action = request.getParameter("action");
if(action.equals("submit"))
{
//set values to bean.For this call below method
setValuesToBean();

//check all form values are valid or not. send bean object
UserBean checkedbean = validateform.validateData(bean);
if(!checkedbean.getIsValid())
{

//if data is invalid.set bean object in request and pass that request to
//insertupdate.jsp using forward
checkedbean.setAction("submit");
request.setAttribute("error",checkedbean);

RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
//now display errors in that jsp page
}
else
{
//using DBClass object call insertDetails method and pass bean object
dbobject.insertDetails(bean);
List list = dbobject.getAlldetails();
request.setAttribute("list", list);
//forward to insertupdate page using requestdispatcher
RequestDispatcher rd= request.getRequestDispatcher("view.jsp");
//display a message to client.store message in request object
//forwarding to jsp
rd.forward(request, response);


}
}
if(action.equals("edit"))
{
//get userdetails of particular name
UserBean ubean = dbobject.getDetails(userName);
request.setAttribute("updateuser",ubean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
}
if(action.equals("update"))
{
setValuesToBean();
UserBean checkedbean = validateform.validateData(bean);
if(!checkedbean.getIsValid())
{

//if data is invalid.set bean object in request and pass that request to
//insertupdate.jsp using forward
checkedbean.setAction("update");
request.setAttribute("error",checkedbean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
//now display errors in that jsp page
}
else
{
//using DBClass object call insertDetails method and pass bean object
dbobject.UpateDetails(bean,userName);
List list = dbobject.getAlldetails();
request.setAttribute("list", list);
//forward to insertupdate page using requestdispatcher
RequestDispatcher rd= request.getRequestDispatcher("view.jsp");
//display a message to client.store message in request object
//forwarding to jsp
rd.forward(request, response);


}
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
//this method is used to setvalues to bean
public void setValuesToBean()
{
bean.setUserName(userName);
bean.setDateOfBirth(dateOfBirth);
bean.setEmail(email);
bean.setPhoneNo(phoneNo);

}


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


public String getServletInfo() {
return "Short description";
}

}

creating updatedetails method in dbclass
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.UserBean;

/**
*
* @author Jagadeesh
*/
public class DBClass {
public Connection createConnection() throws ClassNotFoundException,SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdbase", "root", "root");
return connection;
}
//we get values from servlet by passing bean object to insertdetails method
public int insertDetails(UserBean bb) throws SQLException, ClassNotFoundException
{
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("insert into userdetails values(?,?,?,?)");
//set values to prepared statement object by getting values from bean object
pstmt.setString(1,bb.getUserName());
pstmt.setString(2,bb.getDateOfBirth());
pstmt.setString(3,bb.getEmail());
pstmt.setString(4,bb.getPhoneNo());
int i = pstmt.executeUpdate();
return i;

}
public List getAlldetails()throws SQLException, ClassNotFoundException
{

Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("select * from userdetails");
ResultSet rs = pstmt.executeQuery();
List list = new ArrayList();
while(rs.next())
{
UserBean ubean = new UserBean();
ubean.setUserName(rs.getString(1));
ubean.setDateOfBirth(rs.getString(2));
ubean.setEmail(rs.getString(3));
ubean.setPhoneNo(rs.getString(4));
list.add(ubean);

}
return list;
}
public UserBean getDetails(String uname)throws SQLException, ClassNotFoundException
{
//here we will write code to get a single record from database
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("select * from userdetails where user_name=?");
pstmt.setString(1, uname);
ResultSet rs = pstmt.executeQuery();
List list = new ArrayList();
UserBean ubean = new UserBean();
while(rs.next())
{

ubean.setUserName(rs.getString(1));
ubean.setDateOfBirth(rs.getString(2));
ubean.setEmail(rs.getString(3));
ubean.setPhoneNo(rs.getString(4));
}
ubean.setAction("update");
return ubean;
}
public void UpateDetails(UserBean ubean, String name)throws SQLException, ClassNotFoundException
{

Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("update userdetails set date_of_birth=?,e_mail=?,phone_no=? where user_name=? ");
//set values to prepared statement object by getting values from bean object
pstmt.setString(1,ubean.getDateOfBirth());
pstmt.setString(2,ubean.getEmail());
pstmt.setString(3,ubean.getPhoneNo());
pstmt.setString(4,name);
pstmt.executeUpdate();


}
}

run insertupdate.jsp page and insert record.then it will show all records


after selecting one record




after updating record


Labels:

get details for update record

Posted by Unknown 0 comments
now in this post get command from view.jsp page and if that is equal to update then get user details using that name and display those details in insertupdate.jsp page and automatically the submit button change to update button because that value is getAction. we will set that action as update in database code.
1. get username and action from view.jsp page
2.create a method getDetails in database class
3.get details in servlet and forward to insertupdate.jsp page

1.get details from view.jsp
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.UserBean;
import validation.ValidateForm;
import database.DBClass;
import java.util.List;
/**
*
* @author Jagadeesh
*/
public class ControllerServlet extends HttpServlet {

//declare values to get form values from jsp page
String userName;
String dateOfBirth;
String email;
String phoneNo;
String action;

UserBean bean = new UserBean();
ValidateForm validateform = new ValidateForm();
DBClass dbobject = new DBClass();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//get the values from jsp page
userName = request.getParameter("userName");
dateOfBirth = request.getParameter("dateOfBirth");
email = request.getParameter("email");
phoneNo = request.getParameter("phoneNo");
action = request.getParameter("action");
if(action.equals("submit"))
{
//set values to bean.For this call below method
setValuesToBean();

//check all form values are valid or not. send bean object
UserBean checkedbean = validateform.validateData(bean);
if(!checkedbean.getIsValid())
{

//if data is invalid.set bean object in request and pass that request to
//insertupdate.jsp using forward
request.setAttribute("error",checkedbean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
//now display errors in that jsp page
}
else
{
//using DBClass object call insertDetails method and pass bean object
dbobject.insertDetails(bean);
List list = dbobject.getAlldetails();
request.setAttribute("list", list);
//forward to insertupdate page using requestdispatcher
RequestDispatcher rd= request.getRequestDispatcher("view.jsp");
//display a message to client.store message in request object
//forwarding to jsp
rd.forward(request, response);


}
}
if(action.equals("edit"))
{
//get userdetails of particular name
UserBean ubean = dbobject.getDetails(userName);
request.setAttribute("updateuser",ubean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
//this method is used to setvalues to bean
public void setValuesToBean()
{
bean.setUserName(userName);
bean.setDateOfBirth(dateOfBirth);
bean.setEmail(email);
bean.setPhoneNo(phoneNo);

}


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


public String getServletInfo() {
return "Short description";
}

}



2. create a method in database class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.UserBean;

/**
*
* @author Jagadeesh
*/
public class DBClass {
public Connection createConnection() throws ClassNotFoundException,SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdbase", "root", "root");
return connection;
}
//we get values from servlet by passing bean object to insertdetails method
public int insertDetails(UserBean bb) throws SQLException, ClassNotFoundException
{
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("insert into userdetails values(?,?,?,?)");
//set values to prepared statement object by getting values from bean object
pstmt.setString(1,bb.getUserName());
pstmt.setString(2,bb.getDateOfBirth());
pstmt.setString(3,bb.getEmail());
pstmt.setString(4,bb.getPhoneNo());
int i = pstmt.executeUpdate();
return i;

}
public List getAlldetails()throws SQLException, ClassNotFoundException
{

Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("select * from userdetails");
ResultSet rs = pstmt.executeQuery();
List list = new ArrayList();
while(rs.next())
{
UserBean ubean = new UserBean();
ubean.setUserName(rs.getString(1));
ubean.setDateOfBirth(rs.getString(2));
ubean.setEmail(rs.getString(3));
ubean.setPhoneNo(rs.getString(4));
list.add(ubean);

}
return list;
}
public UserBean getDetails(String uname)throws SQLException, ClassNotFoundException
{
//here we will write code to get a single record from database
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("select * from userdetails where user_name=?");
pstmt.setString(1, uname);
ResultSet rs = pstmt.executeQuery();
List list = new ArrayList();
UserBean ubean = new UserBean();
while(rs.next())
{

ubean.setUserName(rs.getString(1));
ubean.setDateOfBirth(rs.getString(2));
ubean.setEmail(rs.getString(3));
ubean.setPhoneNo(rs.getString(4));
}
ubean.setAction("update");
return ubean;
}
/* public int UpateDetails(int uid)throws SQLException, ClassNotFoundException
{
//here we will write code to update a record
}*/
}

now display selected record in insertupdate.jsp page
<%-- 
Document : index
Author : Jagadeesh
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@page import="model.UserBean" %>
<% UserBean bean;
bean = new UserBean();
//get request from servlet if data is invalid
if(request.getAttribute("error")!=null)
{
bean = (UserBean)request.getAttribute("error");
}
if(request.getAttribute("updateuser")!=null)
{
bean = (UserBean)request.getAttribute("updateuser");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>

<form method="post" action="ControllerServlet">
<CENTER>
<TABLE border="0"width="600px">
<TR>
<TD width="150px">Name:</TD>
<TD>
<INPUT TYPE="text" NAME="userName" value="<%=bean.getUserName()%>">
</TD>
<TD width="350px">
<font color="red"><%=bean.getUserNameError()%> &nbsp;</font>
</TD>
</TR>
<TR>
<TD width="150px">Date Of Birth:</TD>
<TD>
<INPUT TYPE="text" NAME="dateOfBirth" value="<%=bean.getDateOfBirth()%>" <%=request.getAttribute("updateuser")!=null?"readonly":""%>>
</TD>
<TD>
<font color="red"><%=bean.getDateOfBirthError()%> </font>
</TD>
</TR>
<TR>
<TD width="150px">E-Mail</TD>
<TD>
<INPUT TYPE="text" NAME="email" value="<%=bean.getEmail()%>">
</TD>
<TD>
<font color="red"><%=bean.getEmailError()%> </font>
</TD>
</TR>
<TR>
<TD width="150px">Phone no:</TD>
<TD>
<INPUT TYPE="text" NAME="phoneNo" value="<%=bean.getPhoneNo()%>">
</TD>
<TD>
<font color="red"><%=bean.getPhoneNoError()%> </font>
</TD>
</TR>
<TR>
<TD colspan="2" align="center">
<INPUT TYPE="submit" value="<%=bean.getAction()%>" name="action">
</TD>
<TD>
&nbsp;
</TD>
</TR>
</TABLE>
</CENTER>
</form>
</body>
</html>
run insertupdate.jsp page and enter somedetails and it will display all fidleda and select one record then it wil show following output with update button


in this post we got all details for selected user. in next post we will update that user details
Labels:

Displaying all records in view.jsp page

Sunday, March 7, 2010 Posted by Unknown 0 comments
<%-- 
Document : view
Created on : Mar 8, 2010, 10:49:03 AM
Author : Jagadeesh
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.*" %>
<%@page import="model.UserBean" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<a href="<%=request.getContextPath()%>/insertupdate.jsp">back</a>
<table width="100%"border="1">
<tr>
<th>Usename</th>
<th>date of birth</th>
<th>email</th>
<th>phone no</th>
<th>action</th>
</tr>
<%
List list = (List)request.getAttribute("list");
if(list!=null)
{
for(int i=0 ; i< list.size();i++)
{
UserBean ubean =(UserBean) list.get(i);

%>
<tr>
<td><%=ubean.getUserName()%></td>
<td><%=ubean.getDateOfBirth()%></td>
<td><%=ubean.getEmail()%></td>
<td><%=ubean.getPhoneNo()%></td>
<td>
<a href="ControllerServlet?action=edit&userName=<%=ubean.getUserName()%>">update</a>|
<a href="ControllerServlet?action=delete&userName=<%=ubean.getUserName()%>">delete</a></td>

</tr>
<%
}
}
%>
</table>
</body>
</html>
now run insertupdate.jsp page and insert details then it will give following output with your database details


in next post we will update record.
Labels:

Insert values into database

Wednesday, March 3, 2010 Posted by Unknown 0 comments
in this post we will call insertdetails method in servlet
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.UserBean;

/**
*
* @author Jagadeesh
*/
public class DBClass {
public Connection createConnection() throws ClassNotFoundException,SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.
getConnection("jdbc:mysql://localhost:3306/userdbase", "root", "root");
return connection;
}
//we get values from servlet by passing bean object to insertdetails method
public int insertDetails(UserBean bb) throws SQLException, ClassNotFoundException
{
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("insert into userdetails values(?,?,?,?)");
//set values to prepared statement object by getting values from bean object
pstmt.setString(1,bb.getUserName());
pstmt.setString(2,bb.getDateOfBirth());
pstmt.setString(3,bb.getEmail());
pstmt.setString(4,bb.getPhoneNo());
int i = pstmt.executeUpdate();
return i;

}
public List getAlldetails()throws SQLException, ClassNotFoundException
{
//here we will write code to get all records from database
Connection con = createConnection();
PreparedStatement pstmt = con.prepareStatement("select * from userdetails");
ResultSet rs = pstmt.executeQuery();
List list = new ArrayList();
while(rs.next())
{
UserBean ubean = new UserBean();
ubean.setUserName(rs.getString(1));
ubean.setDateOfBirth(rs.getString(2));
ubean.setEmail(rs.getString(3));
ubean.setPhoneNo(rs.getString(4));
list.add(ubean);

}
return list;
}
/* public UserBean getDetails(int uid)throws SQLException, ClassNotFoundException
{
//here we will write code to get a single record from database
}
public int UpateDetails(int uid)throws SQLException, ClassNotFoundException
{
//here we will write code to update a record
}*/
}


now call that insertdetails method in servlet

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.UserBean;
import validation.ValidateForm;
import database.DBClass;
/**
*
* @author Jagadeesh
*/
public class ControllerServlet extends HttpServlet {

//declare values to get form values from jsp page
String userName;
String dateOfBirth;
String email;
String phoneNo;
String action;

UserBean bean = new UserBean();
ValidateForm validateform = new ValidateForm();
DBClass dbobject = new DBClass();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//get the values from jsp page
userName = request.getParameter("userName");
dateOfBirth = request.getParameter("dateOfBirth");
email = request.getParameter("email");
phoneNo = request.getParameter("phoneNo");
action = request.getParameter("action");
if(action.equals("submit"))
{
//set values to bean.For this call below method
setValuesToBean();

//check all form values are valid or not. send bean object
UserBean checkedbean = validateform.validateData(bean);
if(!checkedbean.getIsValid())
{
//if data is invalid.set bean object in request and pass that request to
//insertupdate.jsp using forward
request.setAttribute("error",checkedbean);
RequestDispatcher rd = request.getRequestDispatcher("insertupdate.jsp");
rd.forward(request, response);
//now display errors in that jsp page
}
else
{
//using DBClass object call insertDetails method and pass bean object
dbobject.insertDetails(bean);
List list = dbobject.getAlldetails();
request.setAttribute("list", list);
//forward to insertupdate page using requestdispatcher
RequestDispatcher rd= request.getRequestDispatcher("view.jsp");
//display a message to client.store message in request object
//forwarding to jsp
rd.forward(request, response);

}
}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
//this method is used to setvalues to bean
public void setValuesToBean()
{
bean.setUserName(userName);
bean.setDateOfBirth(dateOfBirth);
bean.setEmail(email);
bean.setPhoneNo(phoneNo);

}


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


public String getServletInfo() {
return "Short description";
}

}

Labels:

Create Class for Database

Posted by Unknown 0 comments
create a package name as database and create a class in that database DBClass

package database;

/**
*
* @author Jagadeesh
*/
public class DBClass {

}


in this package we will create methods for insert,delete,update

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.UserBean;

/**
*
* @author Jagadeesh
*/
public class DBClass {
public Connection createConnection() throws ClassNotFoundException,SQLException
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/userdbase", "root", "root");
return connection;
}
public int insertDetails(UserBean bb) throws SQLException, ClassNotFoundException
{
//here we will write code for insert

}
public List getAlldetails()throws SQLException, ClassNotFoundException
{
//here we will write code to get all records from database
}
public UserBean getDetails(int uid)throws SQLException, ClassNotFoundException
{
//here we will write code to get a single record from database
}
public int UpateDetails(int uid)throws SQLException, ClassNotFoundException
{
//here we will write code to update a record
}
}

here
getAlldetails will return more than one user details so we returned list object.
getDetails will return only one user details so one bean object is enough.
here i used mysql fourth driver so no need to create any dsn name.you have to copy mysql-connector.jar files to tomcat commons library.if you dont want to use this you can use odbc jdbc bridge driver

in next post we will insert values into database
Labels:

Displaying errors in jsp page

Tuesday, March 2, 2010 Posted by Unknown 0 comments
now get the attribute from request from servlet.and display errors
<%-- 
Document : index
Author : Jagadeesh
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@page import="model.UserBean" %>
<% UserBean bean;
bean = new UserBean();
//get request from servlet if data is invalid
if(request.getAttribute("error")!=null)
{
bean = (UserBean)request.getAttribute("error");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="post" action="ControllerServlet">
<CENTER>
<TABLE border="0"width="600px">
<TR>
<TD width="150px">Name:</TD>
<TD>
<INPUT TYPE="text" NAME="userName" value="<%=bean.getUserName()%>">
</TD>
<TD width="350px">
<font color="red"><%=bean.getUserNameError()%> </font>
</TD>
</TR>
<TR>
<TD width="150px">Date Of Birth:</TD>
<TD>
<INPUT TYPE="text" NAME="dateOfBirth" value="<%=bean.getDateOfBirth()%>">
</TD>
<TD>
<font color="red"><%=bean.getDateOfBirthError()%> </font>
</TD>
</TR>
<TR>
<TD width="150px">E-Mail</TD>
<TD>
<INPUT TYPE="text" NAME="email" value="<%=bean.getEmail()%>">
</TD>
<TD>
<font color="red"><%=bean.getEmailError()%> </font>
</TD>
</TR>
<TR>
<TD width="150px">Phone no:</TD>
<TD>
<INPUT TYPE="text" NAME="phoneNo" value="<%=bean.getPhoneNo()%>">
</TD>
<TD>
<font color="red"><%=bean.getPhoneNoError()%> </font>
</TD>
</TR>
<TR>
<TD colspan="2" align="center">
<INPUT TYPE="submit" value="<%=bean.getAction()%>" name="action">
</TD>
<TD>
&nbsp;
</TD>
</TR>
</TABLE>
</CENTER>
</form>
</body>
</html>


here we have created two objects. one is for displaying empty fields when we run jsp page first time .
and second one is for displaying errors .
if you have any doubts post your comment below
we did not do any thing just get the request attribute from servlet and display errors using bean methods
now run insertupdate.jsp page

before sumbit

After Sumbit with empty fieilds



in next post we will learn if these values are valid then insert values to database .



Labels:

Creating validation class

Posted by Unknown 2 comments
Up to now we created
insertupdate.jsp
ControllerServlet.java
package model and bean class
now in this post we will create a package and a class
crate a package validation and with in this package create a class ValidateForm.

package validation;

/**
*
* @author Jagadeesh
*/
public class ValidateForm {


}

now go to servlet. in that servlet declare variables to get form values and create a method for setting values to bean
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.UserBean;
import validation.ValidateForm;

/**
*
* @author Jagadeesh
*/
public class ControllerServlet extends HttpServlet {

//declare values to get form values from jsp page
String userName;
String dateOfBirth;
String email;
String phoneNo;
String action;

UserBean bean = new UserBean();
ValidateForm validateform = new ValidateForm();

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//get the values from jsp page
userName = request.getParameter("userName");
dateOfBirth = request.getParameter("dateOfBirth");
email = request.getParameter("email");
phoneNo = request.getParameter("phoneNo");
action = request.getParameter("action");
if(action.equals("submit"))
{
//set values to bean.For this call below method
setValuesToBean();


}
}
catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}
//this method is used to setvalues to bean
public void setValuesToBean()
{
bean.setUserName(userName);
bean.setDateOfBirth(dateOfBirth);
bean.setEmail(email);
bean.setPhoneNo(phoneNo);

}


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}


public String getServletInfo() {
return "Short description";
}

}



in next post we will learn how to validate form values and how to send errors to jsp page
Labels: