Struts2与Hibernate的整合实例_2

基于慕课网教程的学习笔记


1.创建用户自定义的SessionFactory类

package db;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class MyHibernateSessionFactory {

    private static SessionFactory sessionFactory;//会话工厂属性

    //构造方法私有化,保证单利模式
    private MyHibernateSessionFactory(){

    }


    /**
     * 公有的静态方法
     * 返回一个会话工厂对象SessionFactory
     * @return
     */
    public static SessionFactory getSessionFactory(){

        if(sessionFactory==null){
            Configuration config = new Configuration().configure();
            //创建服务注册对象
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
            //创建sessionFactory
            SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
            return sessionFactory;
        }else{
            return sessionFactory;
        }

    }

}

2.用户业务逻辑类和接口

package service;

import entity.Users;

//用户业务逻辑接口
public interface UsersDAO {

    public boolean usersLogin(Users u);

}
@Override
    public boolean usersLogin(Users u) {
        // TODO Auto-generated method stub
        //事物对象
        Transaction tx = null;
        String hql = "";
        try{
            Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
            tx = session.beginTransaction();//开启事物
            hql = "form Users where username=? and password=? ";
            Query query = session.createQuery(hql);
            query.setParameter(0, u.getUsername());
            query.setParameter(1, u.getPassword());

            List list = query.list();
            tx.commit();//提交事物
            System.out.print("111111111111111111111111111111111111");
            if(list.size()>0){
                return true;
            }else{
                return false;
            }
        }
        catch(Exception e){
            e.printStackTrace();
            return false;
        }
        finally{
            if(tx!=null){

                tx = null;
            }
        }
    }


    }

进行单元测试

@Test
    public void test() {
        Users u = new Users(1,"zhangsan","123456");
        UsersDAO udao = new UsersDAOImpl();
        Assert.assertEquals(false, udao.usersLogin(u));
    }

3.设计所有Action的父类

package action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

//所有action动作的父类
public class SuperAction extends ActionSupport implements ServletResponseAware,ServletRequestAware,ServletContextAware{

    private static final long serialVersionUID = 1L;
    protected HttpServletRequest request;//请求对象
    protected HttpServletResponse response;//响应对象
    protected ServletContext application;//全局对象
    protected HttpSession session;//会话对象

    @Override
    public void setServletContext(ServletContext application) {
        // TODO Auto-generated method stub
        this.application=application;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        // TODO Auto-generated method stub
        this.request=request;
        this.session=this.request.getSession();
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
        // TODO Auto-generated method stub

    }

}

4.设计用户Action

package action;

import service.UsersDAO;
import service.impl.UsersDAOImpl;

import com.opensymphony.xwork2.ModelDriven;

import entity.Users;

public class UsersAction extends SuperAction implements ModelDriven<Users> {

private Users user = new Users();
private static final long serialVersionUID = 1L;

//用户登录动作
public String login(){

    UsersDAO udao = new UsersDAOImpl();
    if(udao.usersLogin(user)){

        //在session中保存登陆成功的用户名
        session.setAttribute("loginUserName", user.getUsername());

        return "login_success";
    }else{
        return "login_failure";
    }
}

    //用户注销方法
    public String logout(){
        if(session.getAttribute("loginUserName")!=null){
            session.removeAttribute("loginUserName");
        }
        return "logout_success";
    }

    //登陆验证
    public void validate(){
        //用户名不能为空
        if("".equals(user.getUsername().trim())){
            this.addFieldError("usernameError", "用户名不能为空");
        }

    }


    @Override
    public Users getModel() {
        // TODO Auto-generated method stub
        return null;
    }

}

5.配置Struts文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

     <package name="default"  namespace="/" extends="struts-default">


    </package>

    <package name="users" namespace="/" extends="default">
         <action name="*_*" class="action.{1}Action" method="{2}">
         <result name="login_success">/users/Users_login_success.jsp</result>
          <result name="login_failure">/users/Users_login.jsp</result>
          <result name="logout_success">/users/Users_login.jsp</result>
          <result name="input">/users/Users_login.jsp</result>
         </action>
    </package>

    <package name="students" namespace="/students" extends="default">
     <action name="*_*" class="action.{1}Action" method="{2}">
       <result name="query_success">/students/Students_query_success.jsp </result>
       </action>
    </package>
    <!-- Add packages here -->

</struts>

在页面上的调用

<form name="loginForm" 
action="<%=path%>/users/Users_login.action" method="post">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值