JavaWeb实现MVC设计模式(实例解析)

本例使用MySQL数据库,实现了简单的用户登录验证

一、创建用户表 login_user ,插入一条数据 insert login_user value(“sa”,”1234”)

create table login_user(
    name varchar(20) primary key,
    pwd varchar(20) not null
)

二、新建web工程ch12,建立四个包:com.bo , com.dao , com.entity , com.control ,在com.entity包下新建User.java实体类,代码如下:

public class User {
    private String name;
    private String pwd;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public User() {
        super();
    }
    public User(String name, String pwd) {
        super();
        this.name = name;
        this.pwd = pwd;
    }   
}

三、在com.dao包下建立数据访问类UserDao.java,定义方法findById,代码如下:

public class UserDao {
    public User findById(String name){
        User user=null;
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        try{
            conn=DbUtil.getConn();
            String sql="select * from login_user where name=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1, name);
            rs=ps.executeQuery();
            while(rs.next()){
                user=new User();
                user.setName(rs.getString("name"));
                user.setPwd(rs.getString("pwd"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            DbUtil.closeConn(conn,ps,rs);
        }
        return user;
    }
}

四、DbUtil类主要提供了数据库连接的基本方法,代码如下:

public class DbUtil {

    private static String driver;
    private static String url;
    private static String userName;
    private static String password;

    //从properties文件中获取连接数据库所需的参数
     static{
        try {
            Properties prop=new Properties();
            InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");  
            prop.load(in);  
            driver=prop.getProperty("driver");
            url=prop.getProperty("url");
            userName=prop.getProperty("userName");
            password=prop.getProperty("password");

        }catch (FileNotFoundException e) {
            System.out.println("找不到文件!");
            e.printStackTrace();
        }catch (IOException e) {
            System.out.println("读取properties文件出错!");
            e.printStackTrace();
        }
    }

    //获取数据库连接
     public static Connection getConn(){
        Connection conn=null;
        try {
            Class.forName(driver);
            conn=DriverManager.getConnection(url,userName,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
     }

     //释放资源
     public static void closeConn(Connection conn,Statement stmt,ResultSet rs) {
         try{
            if(rs!=null){rs.close();}
            if(stmt!=null){stmt.close();}
            if (conn != null) {conn.close();}
         }catch (SQLException e) {e.printStackTrace();}
    }

}

在该类中获取的数据库连接所用的jdbc.properties文件位于src目录下,对其进行的配置如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/oa
userName=root
password=123456

五、在com.bo包下编写UserBo.java 业务逻辑类,定义方法checkUser:

public class UserBo {
    UserDao dao=new UserDao();
    //将用户输入的密码与在数据库中查到的进行匹配
    public boolean checkUser(String name,String pwd){
        boolean result=false;
        User user=dao.findById(name);
        if(user!=null&&user.getPwd().equals(pwd)){
            result=true;
        }
        return result;
    }
}   

六、编写登录页面和登录成功页面(本例的登录成功页面就不弄复杂的,创建名为loginSuccess.jsp的文件,内容随意填,这里就不描述了)

<body>
    <center>
    <h3>用户登录h3>
    <form action="UserLogin" method="post">
        用户名:<input type="text" name="username"/><br/>
        密 码:<input type="text" name="password"/> <br/>
        <input type="submit" value="登录"  /><br/>
    form>
    center>
body>

七、在com.control包下编写UserAction.java用于登录验证

public class UserAction extends HttpServlet {
    private static final long serialVersionUID = 1L;   

    public UserAction() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserBo userbo=new UserBo();
        String name=request.getParameter("username");
        String pwd=request.getParameter("password");
        //控制器并不做数据处理,而是调用相应的模型,
        boolean validate=userbo.checkUser(name, pwd);
        //根据模型的返回结果将符合要求的视图返回给用户
        if(validate){
            response.sendRedirect("loginSuccess.jsp");
        }else{
            response.sendRedirect("login.jsp");
        }
    }
}

OK,到此就可以将此例子运行到Web服务器上了,在服务器上运行成功后访问login.jsp,就可以开始完成简单的用户登录验证

你可能感兴趣的:(SSH框架)