DILEEPKRISHNA
DAO Classes
5 Answer(s)      4 years ago
Posted in : JSP-Servlet

login page code for Dao classes

Advertisement
View Answers

June 7, 2011 at 12:22 PM


Hi DileepKrishna

Go through the given below link :

http://www.roseindia.net/struts/struts-login-form.shtml

The above link Contains full fledged example containing Login form with Dao and Action Class.



January 1, 2012 at 5:37 PM


/*
 *ConnectionManager
 *
 *
 *Version:1.0
 *
 *Date:25-Nov-2011
 *
 */
package com.student.dao;

import java.sql.*;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class ConnectionManager {

    static Connection con;
    static String url;
    static final Logger logger = Logger.getLogger(ConnectionManager.class);

    public static Connection getConnection() {
        PropertyConfigurator.configure("log4j.properties");
        try {
            String url = "jdbc:oracle:thin:@172.24.137.30:1521:ora10g";
            // assuming "DataSource" is your DataSource name

            Class.forName("oracle.jdbc.OracleDriver");

            try {
                con = DriverManager.getConnection(url, "e533121", "project1");

                // assuming your SQL Server's username is "username"
                // and password is "password"

            }

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

        catch (ClassNotFoundException e) {// "logger" prints in to a file;
            // Normally used to trace the
            // process

            logger.error(e);
        }

        return con;
    }
}



createid:
/*
 *CollegeRegistrationDao
 *
 *
 *Version:1.0
 *
 *Date:31-Nov-2011
 *
 */
package com.student.dao;

import java.sql.*;

import com.student.beans.*;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class CreateIdDAO {
    static Connection currentCon = null;
    static ResultSet rs = null;
    static PreparedStatement pstmt = null;
    static ResultSet rs1 = null;
    static PreparedStatement pstmt1 = null;
    static final Logger logger = Logger.getLogger(CreateIdDAO.class);

    public static StudentBean register(StudentBean bean) {
        /**
         * method to search student
         * 
         * @533026,533121
         * 
         */
        // preparing some objects for connection
        Statement stmt = null;
        PropertyConfigurator.configure("log4j.properties");
        try {
            // connect to DataBase
            // connect to DataBase
            currentCon = ConnectionManager.getConnection();
            stmt = currentCon.createStatement();
            String getMax = "select Max(std_id) from studentids";
            rs1 = stmt.executeQuery(getMax);
            rs1.next();
            int maxId = rs1.getInt(1);
            System.out.println(maxId);
            int nextId = maxId + 1;
            String stdId = "S" + Integer.toString(nextId);
            String query1 = "insert into studentids values(?)";
            pstmt1 = currentCon.prepareStatement(query1);
            pstmt1.setInt(1, nextId);
            pstmt1.executeUpdate();
            bean.setStudentId(stdId);
        } catch (Exception ex) {// "logger" prints in to a file; Normally used
            // to trace the process

logger.error("Registration failed: An Exception has occurred! "
+ ex);
}

// exception handling
finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
stmt = null;
}

if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}

currentCon = null;
}
}

return bean;


}

}


registration:

try {
            // connect to DataBase
            // connect to DataBase
            currentCon = ConnectionManager.getConnection();
            String stdId=bean.getStudentId();
            System.out.println(stdId);
            // query for inserting into the table
            String query = "insert into newstudent(std_id,std_name,maths,social,hindi,science,english) values(?,?,?,?,?,?,?)";
            pstmt = currentCon.prepareStatement(query);
            // inserting values
            pstmt.setString(1,stdId);
            pstmt.setString(2,bean.getStudentName());
            pstmt.setInt(3, bean.getMaths());
            pstmt.setInt(4, bean.getSocial());
            pstmt.setInt(5, bean.getHindi());
            pstmt.setInt(6, bean.getScience());
            pstmt.setInt(7, bean.getEnglish());
            pstmt.executeUpdate();
            bean.setValid(true);

        }

delete:
try
        {


        String std = bean.getStudentId();
        PropertyConfigurator.configure("log4j.properties");
        String searchQuery = "delete from newstudent where std_id='"+ std + "'";
        bean.setValid(true);

        // // "logger" prints in to a file; Normally used to trace the process

        logger.info("Your employee id is " + std);

        logger.info("Query: " + searchQuery);

        }

        catch (Exception ex) {
            logger.error("Log In failed: An Exception has occurred! " + ex);
        }


search:

Statement stmt = null;

        String username = bean.getStudentId();

        String searchQuery = "select * from newstudent where std_id ='"
                + username + "' ";

        // "logger" prints in to a file; Normally used to trace the process

        logger.info("Student ID is " + username);
        logger.info("Query: " + searchQuery);

        try {
            // connect to DB
            currentCon = ConnectionManager.getConnection();
            stmt = currentCon.createStatement();
            rs = stmt.executeQuery(searchQuery);
            boolean more = rs.next();

            // if user does not exist set the isValid variable to false
            if (!more) {
                logger
                        .warn("Sorry, you are not a registered user! Please sign up first");
                bean.setValid(false);
            }

            // if user exists set the isValid variable to true
            else if (more) {
                String studentId = rs.getString("std_id");
                String studentName = rs.getString("std_NAME");
                int maths = rs.getInt("maths");
                int social = rs.getInt("social");
                int hindi = rs.getInt("hindi");
                int science = rs.getInt("science");
                int english = rs.getInt("english");
                bean.setStudentId(studentId);
                bean.setStudentName(studentName);
                bean.setMaths(maths);
                bean.setSocial(social);
                bean.setHindi(hindi);
                bean.setScience(science);
                bean.setEnglish(english);
                bean.setValid(true);
                int total=maths+social+hindi+science+english;
                if(total>=450){
                    bean.setGrade("A+");
                }
                if(total>=400 && total<=449){
                    bean.setGrade("A");
                }
                if(total>=350 && total<=399){
                    bean.setGrade("B");
                }
                if(total>=300 && total<=349){
                    bean.setGrade("C");
                }
                if(total>=250 && total<=299){
                    bean.setGrade("D");
                }
                if(total>=200 && total<=249){
                    bean.setGrade("E");
                }
                if(total<200){
                    bean.setGrade("Fail");
                }
                }

        }

profile and update:
Statement stmt = null;

        String username = bean.getStudentId();
        // query to select row from College using College_Id
        String searchQuery = "select * from newstudent where std_Id='"
                + username + "' ";
        // "logger" prints in to a file; Normally used to trace the process
        logger.info("Your user name is " + username);
        logger.info("Query: " + searchQuery);

        try {
            // connect to DataBase
            currentCon = ConnectionManager.getConnection();
            stmt = currentCon.createStatement();
            rs = stmt.executeQuery(searchQuery);
            boolean more = rs.next();
            // check for rows
            if (more) {

                String studentId = rs.getString("std_id");
                String studentName = rs.getString("std_NAME");
                int maths = rs.getInt("maths");
                int social = rs.getInt("social");
                int hindi = rs.getInt("hindi");
                int science = rs.getInt("science");
                int english = rs.getInt("english");
                bean.setStudentId(studentId);
                bean.setStudentName(studentName);
                bean.setMaths(maths);
                bean.setSocial(social);
                bean.setHindi(hindi);
                bean.setScience(science);
                bean.setEnglish(english);
                bean.setValid(true);

            } else {
                bean.setValid(false);
            }
        }

        catch (Exception ex) {
            logger.error("Log In failed: An Exception has occurred! " + ex);
        }


public static StudentBean register(StudentBean bean) {
        Statement stmt = null;
        /**
         * method to search student
         * 
         * @533026
         * 
         */
        // preparing some objects for connection
        /*
         * String sName = bean.getStudentName(); String searchQuery =
         * "select * from Student where Student_Name='" + sName + "' "; //
         * "System.out.println" prints in the console; Normally used to trace
         * the process System.out.println("Your user name is " + sName);
         * System.out.println("Query: "+searchQuery);
         */
        PropertyConfigurator.configure("log4j.properties");
        try {
            // connect to DataBase
            currentCon = ConnectionManager.getConnection();

            // if user does not exist set the isValid variable to false

            // query for inserting into the table
            String sid = bean.getStudentId();
            String sn = bean.getStudentName();
            int ma = bean.getMaths();
            int sc = bean.getSocial();
            int hi = bean.getHindi();
            int si = bean.getScience();
            int eng = bean.getEnglish();

            String query = "update newstudent set std_name='" + sn + "',maths=" + ma + ",social="
                    + sc + ",hindi=" + hi + ",science=" + si + ",english=" + eng + " where std_id='" + sid + "'";
            // "logger" prints in to a file; Normally used to trace the process
            logger.info(query);
            pstmt = currentCon.prepareStatement(query);
            pstmt.executeUpdate();

        } catch (Exception ex) {
            logger.error("Log In failed: An Exception has occurred! " + ex);
        }


January 1, 2012 at 5:38 PM


package com.student.controllers;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.student.dao.*;
import com.student.beans.*;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * Servlet implementation class studentServlet
 */
public class studentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    static final Logger logger = Logger.getLogger(studentServlet.class);

    /**
     * Default constructor. 
     */
    public studentServlet() {
        // TODO Auto-generated constructor stub
        PropertyConfigurator.configure("log4j.properties");
        logger.info("Entered Servlet");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        try

        {
            HttpSession session = request.getSession(true);
            switch (Integer.parseInt(request.getParameter("name"))) {
            // case for college registration
            case 1:
                // creating object to java beans
                StudentBean createId = new StudentBean();
                createId = CreateIdDAO.register(createId);
                // storing the values in variables
                logger.info("Entered Case 1:Generation of ID");
                session.setAttribute("currentSessionUser", createId);
                String destination = "./jsp/studentReport.jsp";
                response.sendRedirect(response.encodeRedirectURL(destination));
                break;
            case 2:
                // creating object to java beans
                StudentBean registration = (StudentBean)(session.getAttribute("currentSessionUser"));
                // storing the values in variables
                logger.info("Entered Case 1:College Registration");
                registration.getStudentId();
                registration.setStudentName(request.getParameter("sn"));
                registration.setMaths(Integer.parseInt(request.getParameter("ma")));
                registration.setSocial(Integer.parseInt(request.getParameter("so")));
                registration.setHindi(Integer.parseInt(request.getParameter("hi")));
                registration.setScience(Integer.parseInt(request.getParameter("sc")));
                registration.setEnglish(Integer.parseInt(request.getParameter("eng")));
                registration = RegistrationDAO.register(registration);
                session.setAttribute("currentSessionUser", registration);
                String destination1 = "./jsp/collegeReportSuccess.jsp";
                response.sendRedirect(response.encodeRedirectURL(destination1));
                break;
            case 3:
                logger.info("Entered Case 2:College Search");
                StudentBean user = new StudentBean();
                user.setStudentId(request.getParameter("sid"));
                user = StudentSearchDao.search(user);
                if (user.isValid()) {
                    session.setAttribute("currentUser", user);
                    String destination2 = "./jsp/collegeSearchSuccess.jsp";
                    response.sendRedirect(response
                            .encodeRedirectURL(destination2)); // logged-in page
                } else {
                    String destination3 = "./jsp/invalidStudentSearch.jsp";
                    response.sendRedirect(response
                            .encodeRedirectURL(destination3)); // error page
                }
                break;
            case 4:
                logger.info("Entered Case 3:College Deletion");
                StudentBean collegeStudent = new StudentBean();
                collegeStudent.setStudentId(request.getParameter("sid"));

                collegeStudent = DeleteStudentDAO.login(collegeStudent);


                    session.setAttribute("currentSessionUser", collegeStudent);
                    response.sendRedirect("./jsp/collegeDeleteSuccess.jsp"); // logged-in
                    // page

                break;
            case 5:
                logger.info("Entered Case 4:Retreving college details");
                StudentBean studentProfile = new StudentBean();
                studentProfile.setStudentId(request.getParameter("sid"));
                studentProfile = StudentProfileDao.details(studentProfile);
                if (studentProfile.isValid()) {
                    session.setAttribute("current", studentProfile);
                    String destination2 = "./jsp/updateStudentProfile.jsp";
                    response.sendRedirect(response
                            .encodeRedirectURL(destination2));
                } else {
                    String destination2 = "./jsp/InvalidUpdateStudent.jsp";
                    response.sendRedirect(response
                            .encodeRedirectURL(destination2));
                }
                break;
            // case for updationg college details
            case 6:// creating object to java beans
                logger.info("Entered Case 5:Updating college details");
                StudentBean update = (StudentBean)(session.getAttribute("current"));
                // storing the values in variables
                update.setStudentId(update.getStudentId());
                update.setStudentName(request.getParameter("sn"));
                update.setMaths(Integer.parseInt(request.getParameter("ma")));
                update.setSocial(Integer.parseInt(request.getParameter("so")));
                update.setHindi(Integer.parseInt(request.getParameter("hi")));
                update.setScience(Integer.parseInt(request.getParameter("sc")));
                update.setEnglish(Integer.parseInt(request.getParameter("eng")));
                update = StudentUpdateDao.register(update);
                session.setAttribute("currentUpdateUser", update);
                String destination9 = "./jsp/updateStudentSuccess.jsp";
                response.sendRedirect(response.encodeRedirectURL(destination9));
                break;
        }

}catch (Exception e) {
    e.printStackTrace();
}
}
}


January 1, 2012 at 5:39 PM


/*
 *college Registration Bean
 *
 *
 *Version:1.0
 *
 *Date:2-DEC-2011
 *
 */

package com.student.beans;

public class StudentBean {
    /**
     * Bean class for Student details
     * 
     * @author 533026,533121 version1.0 27/11/2011
     */
    // declaring attributes of the student table
    private String studentId;
    private String studentName;
    private int maths;
    private int social;
    private int hindi;
    private int science;
    private int english;
    private String grade;
    public boolean valid;

    // getter method for college id
    public String getStudentId() {
        return studentId;
    }

    // setter method for college id
    public void setStudentId(String newStudentId) {
        studentId = newStudentId;
    }

    // getter method for college name
    public String getStudentName() {
        return studentName;
    }

    // setter method for college name
    public void setStudentName(String newStudentName) {
        studentName = newStudentName;
    }

    // getter method for college authority
    public int getMaths() {
        return maths;
    }

    // setter method for college authority
    public void setMaths(int newMaths) {
        maths= newMaths;
    }

    // getter method for college address
    public int getSocial() {
        return social;
    }

    // setter method for college address
    public void setSocial(int newSocial) {
        social = newSocial;
    }

    // getter method for college address2
    public int getHindi() {
        return hindi;
    }

    // setter method for college address2
    public void setHindi(int newHindi) {
        hindi = newHindi;
    }

    // getter method for college city
    public int getScience() {
        return science;
    }

    // setter method for college city
    public void setScience(int newScience) {
        science = newScience;
    }

    // getter method for college state
    public int getEnglish() {
        return english;
    }

    // setter method for college state
    public void setEnglish(int newEnglish) {
        english = newEnglish;
    }
    // getter method for college state
    public String getGrade() {
        return grade;
    }

    // setter method for college state
    public void setGrade(String newGrade) {
        grade = newGrade;
    }


    // getter method for is valid
    public boolean isValid() {
        return valid;
    }

    // setter method for set valid
    public void setValid(boolean newValid) {
        valid = newValid;
    }

}


January 1, 2012 at 5:39 PM


/*
 *college Registration Bean
 *
 *
 *Version:1.0
 *
 *Date:2-DEC-2011
 *
 */

package com.student.beans;

public class StudentBean {
    /**
     * Bean class for Student details
     * 
     * @author 533026,533121 version1.0 27/11/2011
     */
    // declaring attributes of the student table
    private String studentId;
    private String studentName;
    private int maths;
    private int social;
    private int hindi;
    private int science;
    private int english;
    private String grade;
    public boolean valid;

    // getter method for college id
    public String getStudentId() {
        return studentId;
    }

    // setter method for college id
    public void setStudentId(String newStudentId) {
        studentId = newStudentId;
    }

    // getter method for college name
    public String getStudentName() {
        return studentName;
    }

    // setter method for college name
    public void setStudentName(String newStudentName) {
        studentName = newStudentName;
    }

    // getter method for college authority
    public int getMaths() {
        return maths;
    }

    // setter method for college authority
    public void setMaths(int newMaths) {
        maths= newMaths;
    }

    // getter method for college address
    public int getSocial() {
        return social;
    }

    // setter method for college address
    public void setSocial(int newSocial) {
        social = newSocial;
    }

    // getter method for college address2
    public int getHindi() {
        return hindi;
    }

    // setter method for college address2
    public void setHindi(int newHindi) {
        hindi = newHindi;
    }

    // getter method for college city
    public int getScience() {
        return science;
    }

    // setter method for college city
    public void setScience(int newScience) {
        science = newScience;
    }

    // getter method for college state
    public int getEnglish() {
        return english;
    }

    // setter method for college state
    public void setEnglish(int newEnglish) {
        english = newEnglish;
    }
    // getter method for college state
    public String getGrade() {
        return grade;
    }

    // setter method for college state
    public void setGrade(String newGrade) {
        grade = newGrade;
    }


    // getter method for is valid
    public boolean isValid() {
        return valid;
    }

    // setter method for set valid
    public void setValid(boolean newValid) {
        valid = newValid;
    }

}









Related Tutorials/Questions & Answers:
DAO Classes
DAO Classes  login page code for Dao classes
How to connect to dao n bean classes with jsp
How to connect to dao n bean classes with jsp  I have made this edao pkg package edao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import
Advertisements
DAO Example
DAO Example  Dear Friends Could any one please give me any example of DAO application in struts? Thanks & Regards Rajesh
DAO in Struts
DAO in Struts  Can Roseindia provide a simple tutorial for implementation of DAO with struts 1.2? I a link already exits plz do tell me. Thank you
DAO - JDBC
DAO  what is dao ? and how to use it?  Hi Friend, The DAO is a pattern that provides a technique for separating object persistence and data access logic from any particular persistence mechanism or API. Thanks
doubt on DAO's
doubt on DAO's  hai frnds.... can anyoneexplain about how... our own plugin????? and please help me. how to use dao s while integrating struts with hibernate..??? actually what is the purpose of dao's ????? please help
doubt on DAO's
doubt on DAO's  hai frnds.... can anyoneexplain about how... our own plugin????? and please help me. how to use dao s while integrating struts with hibernate..??? actually what is the purpose of dao's ????? please help
dao pack
dao pack  package com.tsi.dao; import java.sql.*; import com.tsi.constants.*; public class DaoPack { public static Connection conn = null; public static Connection createConnection() { try
dao pack
dao pack  package com.tsi.dao; import java.sql.*; import com.tsi.constants.*; public class DaoPack { public static Connection conn = null; public static Connection createConnection() { try
dao
CRUD DAO
CRUD DAO  how to create dao for create,read,update and delete?   /* *ConnectionManager * * *Version:1.0 * *Date:25-Nov-2011 * */ package com.student.dao; import java.sql.*; import org.apache.log4j.Logger
spring DAO module turorial
spring DAO module turorial  how to integrate springDAO and spring webMVC
implementing DAO - Struts
writing DAO Implementation classes." This is her advice. But as a beginner who just..., exam in 3 days, and just now i found out our lecturer post a demo on DAO... divided into DAO factory Impl,employeeDAOImpl,DAOFactory,EmployeeDAO. "I strongly
What is the DAO Layer in any application?
What is the DAO Layer in any application?  Hi, What is the use of the DAO layer in any application and how to develop it. Explain with the example code. Thanks   The DAO layer is also known as data access layer
DAO DTO design pattern
DAO DTO design pattern  Hi,using dao and dto i want to perform insert,update and delete operation.and the data should navigate from 1 frame 2 another.that page should b smthng like this: <%@ page language="java" import
DAO DTO design pattern
DAO DTO design pattern  Hi,using dao and dto i want to perform insert,update and delete operation.and the data should navigate from 1 frame 2 another.that page should b smthng like this: <%@ page language="java" import
DAO DTO design pattern
DAO DTO design pattern  Hi,using dao and dto i want to perform insert,update and delete operation.and the data should navigate from 1 frame 2 another.that page should b smthng like this: <%@ page language="java" import
DAO DTO design pattern
DAO DTO design pattern  Hi,using dao and dto i want to perform insert,update and delete operation.and the data should navigate from 1 frame 2 another.that page should b smthng like this: <%@ page language="java" import
how to create dao
how to create dao   code1: package com.dao; import java.sql.*; import com.beans.*; public class DbAccess { public void createStudent(SampleBean sampleBean) throws SQLException { Connection con=null; try
DAO,DTO,VO Design patterns
DAO,DTO,VO Design patterns  explain dao,dto,vo design patterns in strut 1.3?   Data Access Object (DAO) pattern is the most popular design patterns. It is used when you want to separate your presentation code from
DAO Layer explained
DAO Layer explained       In this section we will explain you the DAO Layer of our application.   DAO Layer Explained   DAO stand for Data
how to login form through spring dao module
how to login form through spring dao module  here i want to chek user details in database through form by using spring dao module.please give me some reference example to me
Java classes
Java classes  Which class is extended by all other classes
java classes
java classes  Which class is the super class for all classes in java.lang package
What is Spring Struts Hibernate DAO Layer?
What is Spring Struts Hibernate DAO Layer?  Hi, explain me the difference in between Spring Struts Hibernate DAO Layer? Thanks   Hi... Spring Struts Hibernate DAO Layer. Thanks
wrapper classes
wrapper classes  Explain wrapper classes and their use?   Java Wrapper Class Wrapper class is a wrapper around a primitive data type... of the primitive wrapper classes in Java are immutable i.e. once assigned a value
classes and objects
classes and objects  Define a class named Doctor whose objects... methods, and an equals method as well. Further, define two classes: Patient... classes a reasonable complement of constructors and accessor methods, and an equals
Inner classes
Inner classes   Hi I am bharat . I am student learning java course . I have one question about inner classes . question is how to access the instance method of Non-static classes which is defined in the outer
Creating Data Access Object (DAO) Design Pattern
Creating Data Access Object (DAO) Design Pattern Data Access Object... code contains in  DAO and it provides a simple interface to access the data. In DAO you need to create the Connection factory class. This class contains