简单的学生信息管理系统

Struts2+hibernate实现用户登录和增删改查案例

开发工具MyEclipse 10.7.1

创建一个项目 web项目project

部署好Struts2的开发环境:

     1、引入需要的类库文件 jar

     2、添加struts2的配置文件 struts.xml    //src路径  :classespath:

     3、在web.xml添加启动struts2 MVC框架的过滤器

     4、添加Hibernate所依赖的jar文件

         (注意:如果Hibernate添加的jar文件与struts2添加jar文件 名称完全一致(只需其中之一)(版本不一致保留高本版) )

5、同样添加hibernate的配置文件

   Classespath:  src路径下面

6、需要添加对应数据库操作的驱动文件jar

在此基础上 对 admin这个类 完成 增删改查的操作。

     在src下搭建开发框架,如图所示:


简单的学生信息管理系统_第1张图片

项目开始:

目录:

第1章 Struts2与Hibernate整合

1-3 Struts2与Hibernate整合

1)添加核心类库,注意:相同的jar包存在不同版本时,删去低版本
2)struts.xml

  
      
      

    
  

3)hibernate.cfg.xml

  
      
        org.hibernate.dialect.MySQLDialect  
        jdbc:mysql://localhost:3306/test  
        root  
        123456  
        com.mysql.jdbc.Driver  
        true  
        true  
        update  
        thread  
      
          
           
      
  

1-4 创建实体类 

1)创建entity包


2)Students.java

    package entity;  
    import java.util.Date;  
    public class Students {  
        private String sid;  
        private String sname;  
        private String gender;  
        private Date birthday;  
        private String address;  
          
        @Override  
        public String toString() {  
            return "Students [address=" + address + ", birthday=" + birthday  
                    + ", gender=" + gender + ", sid=" + sid + ", sname=" + sname  
                    + "]";  
        }  
        public Students() {  
      
      
        }  
        public Students(String sid, String sname, String gender, Date birthday,  
                String address) {  
            super();  
            this.sid = sid;  
            this.sname = sname;  
            this.gender = gender;  
            this.birthday = birthday;  
            this.address = address;  
        }  
        public String getSid() {  
            return sid;  
        }  
        public void setSid(String sid) {  
            this.sid = sid;  
        }  
        public String getSname() {  
            return sname;  
        }  
        public void setSname(String sname) {  
            this.sname = sname;  
        }  
        public String getGender() {  
            return gender;  
        }  
        public void setGender(String gender) {  
            this.gender = gender;  
        }  
        public Date getBirthday() {  
            return birthday;  
        }  
        public void setBirthday(Date birthday) {  
            this.birthday = birthday;  
        }  
        public String getAddress() {  
            return address;  
        }  
        public void setAddress(String address) {  
            this.address = address;  
        }     
    }  

3)Users.java

    package entity;  
    public class Users {  
        private int uid;  
        private String username;  
        private String password;  
          
        public Users() {  
              
        }  
          
        public Users(int uid, String username, String password) {  
            this.uid = uid;  
            this.username = username;  
            this.password = password;  
        }  
      
        public int getUid() {  
            return uid;  
        }  
      
        public void setUid(int uid) {  
            this.uid = uid;  
        }  
      
        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;  
        }     
    }  

1-5 生成实体类的对象关系映射文件

1)Students.hbm.xml

      
      
      
      
          
              
                  
              
                
              
              
                  
         
          
      

2)Users.hbm.xml

      
      
      
      
          
                          
                  
              
              
              
                
          
      

3)配置hibernate.cfg.xml

      
       

1-6 生成表结构

    //创建配置对象  
    Configuration cfg = new Configuration().configure();  
    SchemaExport export = new SchemaExport(cfg);  
    export.create(true,true);  

第2章 用户登录模块

2-1 本章简介

项目分层:
模型层:实体层(entity)、数据库层(db)、接口层(service)、接口实现层(serviceImpl)
控制层:动作层(action)
视图层:JSP页面

2-2 创建用户自定义的SessionFactory类

可使用自带


2-3 用户业务逻辑接口和类

1)UsersDao.java 接口

    public interface UsersDao {  
        public boolean usersLogin(Users u);  
    }  

2)UsersDaoImpl.java 类
    package serviceImpl;  
    public class UsersDaoImpl implements UsersDao {  
      
        public boolean usersLogin(Users u) {  
            //事务对象  
            Transaction tx=null;  
            String sql="";        
            try{  
                Session session = HibernateSessionFactory.getSession();  
                tx = session.beginTransaction();  
                sql="from Users  where username=? and password=? ";  
                Query query=session.createQuery(sql);  
                query.setParameter(0, u.getUsername());  
                query.setParameter(1,u.getPassword());  
                List list=query.list();  
                tx.commit();//提交事务  
                if(list.size()>0){  
                    return true;  
                }else{  
                    return false;  
                }  
                  
            }catch (Exception e) {  
                e.printStackTrace();  
                return false;  
            }finally{  
                if(tx!=null){  
                    tx=null;  
                }  
            }     
        }  
    }  

3)TestUserDaoImpl.java 测试类

    package test.userImpl;  
    public class TestUserDaoImpl {  
        @Test  
        public void testUserLogin(){  
            Users u=new Users(1,"张三","123");  
            UsersDaoImpl udao=new UsersDaoImpl();         
            Assert.assertEquals(true, udao.usersLogin(u));  
        }  
    }  

2-4 设计所有Action的父类

1)继承ActionSupport
2)为了获得常用的内置对象采用耦合IOC方式注入属性

SuperAction.java

    public class SuperAction extends ActionSupport implements ServletContextAware,  
            ServletRequestAware, ServletResponseAware ,SessionAware{  
        private static final long serialVersionUID = 1L;  
        protected ServletContext context;  
        protected HttpServletRequest request;  
        protected HttpServletResponse response;  
        protected Map session;  
      
      
        public void setServletContext(ServletContext context) {  
            this.context=context;  
        }  
      
      
        public void setServletRequest(HttpServletRequest request) {  
            this.request=request;  
        }  
      
      
        public void setServletResponse(HttpServletResponse response) {  
            this.response=response;       
        }  
      
      
        public void setSession(Map session) {  
            this.session = session;  
        }  
    }  

2-5 设计用户Action类 

strus2接受表单数据的方式
三种:普通属性、领域对象、模型驱动


1)UsersAction.java

    package action;  
    import com.opensymphony.xwork2.ModelDriven;  //模型驱动  
    import entity.Users;  
    public class UsersAction extends SuperAction implements ModelDriven{  
        private static final long serialVersionUID = 4317500994450323565L;  
        private Users user=new Users();  
          
        //用户登录动作  
        public String login(){  
            UsersDao udao=new UsersDaoImpl();  
            if(udao.usersLogin(user)){  
                return "login_success";  
            }else{  
                return "login_failure";  
            }         
        }  
          
        public Users getModel() {  
            return this.user;  
        }  
    }  

2)struts.xml  配置映射

      
          
            /users/users_login_success.jsp  
            /users/users_login.jsp  
          
      

2-6 页面调用

    

2-7 完成显示登录成功用户名和注销功能

1)在action实现attribute保存,以及注销动作

    //用户登录动作  
    public String login(){  
        UsersDao udao=new UsersDaoImpl();  
           
        if(udao.usersLogin(user)){    
            //在session中保存登录成功的用户名         
            session.put("loginUserName", user.getUsername());  
            return "login_success";  
        }else{  
            return "login_failure";  
        }         
    }  
      
      
    @SkipValidation  
    //用户注销操作,本操作不进行表单输入验证  
    public String logout(){       
        if(session.get("loginUserName")!=null){  
            session.remove("loginUserName");  
        }  
        return "logout_success";  
    }  

2)struts.xml  添加映射

    /users/users_login.jsp  

3)users_login_success.jsp 登录成功页面

    
欢迎${sessionScope.loginUserName}使用本系统

2-8 完成表单验证功能

1)在action实现ActionSupport的validate()方法

    @Override  
    public void validate() {  
        if("".equals(user.getUsername().trim()) ){  
            this.addFieldError("usernameError", "用户名不能为空!");  
        }  
        if(user.getPassword().trim().length()<6){  
            this.addFieldError("userpasswordError", "密码不能小于6位!");  
        }  
    }  

2)对不进行验证的方法上加注解@SkipValidatio

    @SkipValidation  
    //用户注销操作,本操作不进行表单输入验证  
    public String logout(){}  

3)Struts.xml

      
          
            /users/Users_login_success.jsp              
            /users/Users_login.jsp  
            /users/Users_login.jsp   
            /users/Users_login.jsp    
           
      

4)users_login.jsp 显示错误信息

    <%@ taglib prefix="s" uri="/struts-tags"%>  
      
      
    

第3章 学生信息管理模块

3-1 显示学生资料——准备 

为数据库输入数据

    @Test  
    public void testSaveStudents(){  
        Session session=HibernateSessionFactory.getSessionFactory().openSession();  
        Transaction tx=session.beginTransaction();  
          
        Students s1=new Students("800001","张三丰","男",new Date(),"武当山");  
        Students s2=new Students("800002","郭靖","男",new Date(),"桃花岛");             
        Students s3=new Students("800003","黄蓉","女",new Date(),"桃花岛");     
          
        session.save(s1);  
        session.save(s2);  
        session.save(s3);  
          
        tx.commit();  
        session.close();  
    }  

3-2 显示学生资料-设计学生业务逻辑接口

增删改查

    //学生业务逻辑接口  
    public interface StudentsDao {  
        //查询所有  
        public List queryAllStudents();  
        //查询单个  
        public Students queryStudentsBySid(String sid);  
        //增  
        public boolean addStudents(Students s);  
        //改  
        public boolean updateStudents(Students s);  
        //删  
        public boolean deleteStudents(String sid);    
    }  

3-3 显示学生资料-实现显示学生资料业务逻辑

    //查询所有  
    public List queryAllStudents() {  
        Transaction tx=null;  
        List list=null;  
        String sql="";  
        try{  
            Session session=HibernateSessionFactory.getSessionFactory().openSession();  
            tx=session.beginTransaction();  
              
            sql="from Students ";  
            Query query=session.createQuery(sql);  
              
            list=query.list();  
            tx.commit();  
        }catch(Exception ex){  
            ex.printStackTrace();  
            tx.commit();  
        }finally{  
            if(tx!=null){  
                tx=null;  
            }  
        }  
        return list;  
    }  

3-4 显示学生资料-实现显示学生资料Action 

1)Students.xml

        public String query(){  
    StudentsDao sDao=new StudentsDaoImpl();  
    List list=sDao.queryAllStudents();  
    if(list!=null && list.size()>0){  
        session.setAttribute("stundesList", list);            
    }   
    return "Students_query_success";  

2)struts.xml

      
          
            /stundents/Students_query_success.jsp  
          
      

3-5 显示学生资料-页面调用与数据展现

    <%@ taglib prefix="s" uri="/struts-tags"%>  
      
      
      
      
      
          
        ">  
          
          
          
        " οnclick="javascript: return confirm('真的要删除吗?');">删除  
      
      
      
      

3-6 删除学生资料

1)StudentsDaoImpl.java

    public boolean deleteStudents(String sid) {  
        Transaction tx=null;  
        List list=null;  
        String sql="";  
        try{  
            Session session=HibernateSessionFactory.getSessionFactory().openSession();  
            tx=session.beginTransaction();  
              
            Students s=(Students) session.get(Students.class,sid);  
            session.delete(s);            
                  
            tx.commit();  
            return true;  
        }catch(Exception ex){  
            ex.printStackTrace();  
            tx.commit();  
            return false;  
        }finally{  
            if(tx!=null){  
                tx=null;  
            }         
        }     
    }  

2)StudentsAction.java

    public String delete(){  
        StudentsDao sDao=new StudentsDaoImpl();       
        String sid= request.getParameter("sid");  
        sDao.deleteStudents( sid );       
        return "delete_success";          
    }  

3)Struts.xml

           
          
            /students/Students_query_success.jsp  
            Students_query.action               
           
      

4)Students_query_success.jsp  

    " οnclick="javascript: return confirm('真的要删除吗?');">删除  

3-7 添加学生资料-实现步骤和界面原型设计



3-8 添加学生资料-学生学号生成方法 


1)StudentsDaoImpl.java

    public String getNewSid(){  
            Transaction tx=null;  
            String sid=null;  
            String sql="";  
            try{  
                Session session=HibernateSessionFactory.getSessionFactory().openSession();  
                tx=session.beginTransaction();  
                  
                sql="select max(sid) from Students ";  
                Query query=session.createQuery(sql);  
                  
                sid=(String) query.uniqueResult();  
                  
                if(sid==null  ||  "".equals(sid.trim())){  
                    sid="S00001";  
                }else{  
                    String temp=sid.substring(1);  //取后几位  
                    int tempI=Integer.parseInt(temp)+1;  //int + 1  
                    temp=String.valueOf(tempI); //转成string  
                    int len=temp.length();  //数字位数  
                    for(int i=0;i<5-len;i++){  
                        temp="0"+temp;  
                    }  
                      
                    sid="S"+temp;  
                }  
                      
                tx.commit();              
            }catch(Exception ex){  
                ex.printStackTrace();  
                tx.commit();          
            }finally{  
                if(tx!=null){  
                    tx=null;  
                }         
            }     
            return sid;  
        }  


3-9 添加学生资料-实现添加学生资料业务逻辑 
2)StudentsDaoImpl.java

    public boolean addStudents(Students s) {  
        s.setSid(getNewSid());  
        Transaction tx=null;      
        String sql="";  
        try{  
            Session session=HibernateSessionFactory.getSessionFactory().openSession();  
            tx=session.beginTransaction();            
          
            session.save(s);              
                  
            tx.commit();  
        }catch(Exception ex){  
            ex.printStackTrace();  
            tx.commit();  
            return false;  
        }finally{  
            if(tx!=null){  
                tx=null;  
            }         
        }     
      
        return true;  
    }  

3) StudentsAction.java

    public String add(){  
        StudentsDao sDao=new StudentsDaoImpl();  
      
      
        try {  
            Students s=new Students();  
            s.setSname(request.getParameter("sname"));  
            s.setGender(request.getParameter("gender"));  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
            Date birthday;  
            birthday = sdf.parse(request.getParameter("birthday"));  
            s.setBirthday(birthday);  
            s.setAddress(request.getParameter("address"));  
              
            sDao.addStudents(s);              
        } catch (ParseException e) {  
            e.printStackTrace();  
        }         
        return "add_success";  
    }  



4)Struts.xml

    /students/Students_add_success.jsp   

5)Students_query_success.jsp

    添加学生  

6)Students_add.jsp
  
      

7)Students_add_success.jsp

继续添加? 

3-10 修改学生资料-实现步骤和界面原型演示


3-11 修改学生资料-实现页面显示要修改的生资料



1)StudentsDaoImpl.java

    public Students queryStudentsBySid(String sid) {  
        Transaction tx=null;  
        Students s=null;  
        String sql="";  
        try{  
            Session session=HibernateSessionFactory.getSessionFactory().openSession();  
            tx=session.beginTransaction();  
              
            sql="from Students where sid=?";  
            Query query=session.createQuery(sql);  
            query.setParameter(0,sid);  
              
            s=(Students) query.uniqueResult();  
            tx.commit();  
        }catch(Exception ex){  
            ex.printStackTrace();  
            tx.commit();  
        }finally{  
            if(tx!=null){  
                tx=null;  
            }  
        }  
        return s;     
    }  

2)StudentsAction.java

    public String modify(){  
        StudentsDao sDao=new StudentsDaoImpl();  
        Students s=sDao.queryStudentsBySid(request.getParameter("sid"));  
        session.put("modify_students", s);  
        return "modify_success";          
    }   

3)Struts.xml

    /students/Students_modify.jsp  

4)Students_query_success.jsp

"> 

3-12 修改学生资料-实现修改学生资料action和页面调用测试 


5)StudentsAction.java


    public String save(){  
        StudentsDao sDao=new StudentsDaoImpl();  
        try {  
            Students s=new Students();  
            s.setSid(request.getParameter("sid"));  
            s.setSname(request.getParameter("sname"));  
            s.setGender(request.getParameter("gender"));  
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
            Date birthday;  
            birthday = sdf.parse(request.getParameter("birthday"));  
            s.setBirthday(birthday);  
            s.setAddress(request.getParameter("address"));  
              
            sDao.addStudents(s);              
        } catch (ParseException e) {  
            e.printStackTrace();  
        }         
        return "save_success";        
    }  

6)Struts.xml

    /students/Students_modify_success.jsp  


7)Students_modify.jsp

 







你可能感兴趣的:(数据库--数据为王,关于框架--方便)