Pages

Friday 22 March 2013

Java Servlet + JSP + MySQL Connectivity Example


This tutorial include one login page when user login successfully then one page with customer list appear with id as link when user click on that link the address of that user will display on new jsp page.







Table need in MYSQL.

TBLLOGIN - Contain Login user data (username,password)
TBLCUSTOMER - Contain list of customer. (cid,cname)
TBLADDRESS - Contain Address of the customer (cid,address)

Now First of all We create LOGIN.JSP page in Eclipse IDE.

login.jsp
                             

<body>
    <form name="loginPage" action="Login" method="post">
        <table align="center">
            <tr>
                <td align="right">User Name :</td>
                <td align="right"><input type="text" name="name" id="txtName"></td>
            </tr>
            <tr>
                <td align="right">Password :</td>
                <td align="right"><input type="password" name="pass" id="txtPass"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Login"></td>
                <td></td>
            </tr>
        </table>
    </form>
</body>


When User submit the page Login Servlet in called...

Login.java 
Code for doPost()

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        String uname = request.getParameter("name");
        String pass = request.getParameter("pass");
       
        List custData = new ArrayList();
       
        DatabaseConnection dbConn = new DatabaseConnection();
        Connection conn = dbConn.mySqlConnection();
        try{
            int count = 0;
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT uname,pass FROM tbllogin WHERE                   uname        ='"+uname+"' AND pass='"+pass+"'");
            while(rs.next()){
                count++;
            }
           
            if(count != 0){
               
                rs = stmt.executeQuery("SELECT CID,CNAME FROM tblcustomer");
               
                while(rs.next()){
                    custData.add(rs.getInt("CID"));
                    custData.add(rs.getString("CNAME"));
                }
               
                request.setAttribute("cdata",custData);
                request.getRequestDispatcher("customer_list.jsp").forward(request, response);
            }
            else{
                System.out.println("Error In connection...");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }


We use connection class for connecting with MySQL database.

DatabaseConnection.java class


import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class DatabaseConnection {

    Connection conn = null;
    String url;
    String driver;
    String userName;
    String password;

    public Connection mySqlConnection() {

        url = "jdbc:mysql://localhost:3306/test";
        driver = "com.mysql.jdbc.Driver";
        userName = "root";
        password = "root";

        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("Connected.");
           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}


Now After Login Customer Detail page will load with all customer list in table.
customer_list.jsp

                             
<script type="text/javascript">
    function getAddress(id) {
        alert(id);
        document.forms[0].action="/TestDemo/AddressDetail?cid="+id;
        document.forms[0].submit();

    }
</script>

<body>
    <form name="custData" method="post">
        <table border="1" align="center">
            <tr>
                <td>CID</td>
                <td>CNAME</td>
            </tr>
            <%
                Iterator itr;
            %>
            <%
                List data = (List) request.getAttribute("cdata");
                for (itr = data.iterator(); itr.hasNext();) {
            %>
            <tr>
                <td><input type="text" value=<%=itr.next()%>
                    onclick="getAddress(this.value);" style="cursor: pointer;" /></td>
                <td><%=itr.next()%></td>
            </tr>
            <%
                }
            %>
        </table>
    </form>
</body>


When user click on ID field of table address of that customer will display on other page.
call AddressDetail.java servlet when user click on id field of the table.

protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
   
        int id = Integer.parseInt(request.getParameter("cid"));

        DatabaseConnection dbConn = new DatabaseConnection();
        Connection conn = dbConn.mySqlConnection();
        String address = null;
        try {
            int count = 0;
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt
                    .executeQuery("SELECT address FROM tbladdress WHERE cid = "+id);
            while (rs.next()) {
                address = rs.getString("address");
            }

            if (address != null) {
                request.setAttribute("address", address);
                request.getRequestDispatcher("cust_address.jsp").forward(
                        request, response);
            } else {
                System.out.println("Error In connection...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


Now finally address of the customer display on JSP page.
cust_address.jsp


<p>Address Of Selected Client : ${address}</p>