MVC in action part2: DAO + Bean Classes

So far I have shown how to write a simple web application using jsp servlets while connecting to sql db. Now I am going to go deep down of it, more readable and understandable way, not just MVC (Model - business logic class in logical tier or data tier, View- presentation layer jsp or html file, Controller- again logical tier routing class such as servlet). Data tier contains db. In regular scenarios, other than directly fetching data from db, you passed them or access them through data structures such as list, vectors, map or etc, more convenient. Using bean classes (getters and setters) known as entity classes (depend on logic you implement) is more appropriate while data interchanging takes place from db.
Below example shows how you can implement simple web application using MVC architecture plus DAOs and Bean classes using sql database.
First create dynamic web application project in eclipse. I use eclipse 3.7 Idigo.
Then create jsp page in 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
Login
                   
                            
                                       Username
                                
                             <tr> 
                               
Password
                                     
                            
                            
                                      <%=(request.getAttribute("errMessage") == null) ? ""
                                                          : request.getAttribute("errMessage")%>
                            
                            
                                      
                                      
                                                          type="reset" value="Reset">
                            
                  
         
         

Then create servlet to which you send your request for handling purpose.

package com.mvc.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.bean.LoginBean;
import com.mvc.dao.LoginDao;

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

/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
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 {
accessUserCredentials(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private void accessUserCredentials(HttpServletRequest request,
HttpServletResponse response) throws Exception, IOException {
// TODO Auto-generated method stub
String userName = request.getParameter("username");
String password = request.getParameter("password");

LoginBean loginBean = new LoginBean(); // creating object for LoginBean
// class, which is a normal java
// class, contains just setters
// and getters. Bean classes are
// efficiently used in java to
// access user information
// wherever required in the
// application.

loginBean.setUserName(userName); // setting the username and password
// through the loginBean object then
// only you can get it in future.
loginBean.setPassword(password);

LoginDao loginDao = new LoginDao(); // creating object for LoginDao.
// This class contains main logic of
// the application.

String userValidate = loginDao.authenticateUser(loginBean); // Calling
// authenticateUser
// function

if (userValidate.equals("SUCCESS")) // If function returns success
// string then user will be rooted
// to Home page
{
request.setAttribute("userName", userName); // with setAttribute()
// you can define a
// "key" and value pair
// so that you can get
// it in future using
// getAttribute("key")
request.getRequestDispatcher("/Home.jsp")
.forward(request, response);// RequestDispatcher is used to
// send the control to the
// invoked page.
} else {
request.setAttribute("errMessage", userValidate); // If
// authenticateUser()
// function
// returnsother
// than SUCCESS
// string it
// will be sent
// to Login page
// again. Here
// the error
// message
// returned from
// function has
// been stored
// in a
// errMessage
// key.
request.getRequestDispatcher("/Login.jsp").forward(request,
response);// forwarding the request
}
}

}

Then it creates Bean class object and set data in that bean class.

package com.mvc.bean;

public class LoginBean {
String userName;
String password;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}

DAO class is created

package com.mvc.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mvc.bean.LoginBean;
import com.mvc.util.DBConnection;
public class LoginDao {
public String authenticateUser(LoginBean loginBean){

String userName = loginBean.getUserName(); //Keeping user entered values in temporary variables.
String password = loginBean.getPassword();

Connection con = null;
Statement statement = null;
ResultSet resultSet = null;

String userNameDB = "";
String passwordDB = "";

try{
con = DBConnection.createConnection(); //establishing connection
statement = con.createStatement(); //Statement is used to write queries. Read more about it.
resultSet = statement.executeQuery("select userName,password from users"); //Here table name is users and userName,password are columns. fetching all the records and storing in a resultSet.

while(resultSet.next()) // Until next row is present otherwise it return false
{
userNameDB = resultSet.getString("userName"); //fetch the values present in database
passwordDB = resultSet.getString("password");
}

if(userName.equals(userNameDB) && password.equals(passwordDB)){
return "SUCCESS"; ////If the user entered values are already present in database, which means user has already registered so I will return SUCCESS message.
}
}catch(SQLException e){
e.printStackTrace();
}
return "Invalid user credentials"; // Just returning appropriate message otherwise
}
}

If you want, you can seperate db creation code snipt from this class, then it would not act as a boiler plate code part.

Comments

Popular Posts