yes java beans are piece of reusable codes,this means that you can reuse it any where. Following is an example.
package customer;
import java.io.*;
import java.util.*;
import java.sql.*;
public class Customer implements Serializable
{
private String custID;
private String custName;
private int qty;
private float price;
private float total;
private int storeCust;
public String getCustID() {
return custID;
}
public void setCustID(String custID) {
this.custID = custID;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public int setStoreCust()
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
PreparedStatement pstmt=null;
String query=null;
query="insert into customer values(?,?,?,?,?)";
pstmt=con.prepareStatement(query);
pstmt.setString(1,custID);
pstmt.setString(2,custName);
pstmt.setInt(3,qty);
pstmt.setFloat(4,price);
pstmt.setFloat(5,total);
int i=pstmt.executeUpdate();
this.storeCust=i;
}
catch(Exception e)
{
}
return storeCust;
}
}
and this is a jsp page
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="customer.Customer" %>
<html>
<head>
<title>JSP and JavaBean</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="customer.Customer">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%
int x=cObj.setStoreCust();
if(x>=1)
{
%>
<jsp:forward page="Success.jsp" />
<%
}
else
{
%>
<jsp:forward page="Failure.jsp" />
<%
}
%>
when you run this jsp page it will ask for cutomer id,quantity,total etc and after you submit it then it will insert it into database. For example you want to enter 1000 records so in this point you are not creating 1000 times java file,just you create once and then everything will be done by bean.
Following are some rules of javabeans,keep it in mind
1.javabean must contain a constructor that does not accept any arguements.
2.javabean cant declare any public instance variables;
3.javabeans must contain get and set methods for all of the properties that need to be accessed by JSPs.