struts2+hibernate整合-实现登录功能

最近一直学习struts2+hibernate框架,于是想把两个框架整合到一起,做一个小的登录项目。其他不多说,直接看例子。

1)、Struts2 和hibernate的环境配置

  包括jar包、web.xml以及hibernate.cfg.xml的配置,前面的文章有详细的讲述,这里就不在一一叙述。

2)、登录界面实现(使用了bootstrap自适应框架,详细内容见官网http://www.bootcss.com/)

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
<link rel="stylesheet" href="styles/bootstrap.min.css">
<link rel="stylesheet" href="styles/MyOwn.css">
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="navbar-header"></div>
    </nav>
    <div class="login-page  center-block">
        <div class="center-container">
            <h2 class="color text-center">登录系统</h2>
            <form class="form-horizontal center-block" role="form"
                action="login.action">
                <div class="form-group ">
                    <label class="col-sm-2 control-label">用户名</label>
                    <div class="col-sm-8">
                        <input type="text" class="form-control col-lg-sm" id="name"
                            name="username" placeholder="用户名">
                    </div>
                </div>
                <div class="form-group">
                    <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
                    <div class="col-sm-8">
                        <input type="password" class="form-control" id="inputPassword3"
                            name="pwd" placeholder="密码">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <div class="checkbox col-sm-5">
                            <label> <input type="checkbox"> 记住密码
                            </label>
                        </div>
                        <a class=" col-sm-4 control-label" href="register.html">新用户注册</a>
                    </div>
                </div>
                <div class="form-group ">
                    <div class="col-sm-8 col-sm-offset-2">
                        <button type="submit" class="btn btn-primary btn-block" id="btn">登录</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</body>

 

3)、生成实体类的对象关系映射文件,用户( User.java)以及对应的User.hbm.xml

package com.entity;

public class User {
    private Integer id;
    private String username;
    private String pwd;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public User(String username,String pwd) {
        this.username = username;
        this.pwd = pwd;
    }
    public User() {
        // TODO Auto-generated constructor stub
    }
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-11-26 16:32:02 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.entity.User" table="USER">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="username" type="java.lang.String">
            <column name="USERNAME" />
        </property>
        <property name="pwd" type="java.lang.String">
            <column name="PWD" />
        </property>
    </class>
</hibernate-mapping>

 

4)、创建用户自定义SessionFactory工厂(Hibernateutil.java)

package com.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class Hibernateutil {
    private static SessionFactory sessionFactory = null;

    // 采用单例模式
    private Hibernateutil() {
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            // 创建Configuration对象:对应hibernate的基本配置信息和对象关系映射信息
            Configuration config = new Configuration().configure();
            // 创建一个对象StandardServiceRegistry,configure("你的***.cfg.xml"),默认为hibernate.cfg.xml
            StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                    .configure().build();
            // 创建会话工厂对象
            sessionFactory = config.buildSessionFactory(registry);
            return sessionFactory;
        } else
            return sessionFactory;
    }

}

 

5)、创建用户业务逻辑接口和类(UserImpl.java和UserDao.java)

UserImpl.java

package com.service.impl;

import com.entity.User;

//用户业务逻辑接口
public interface UserImpl {
    // login登录
    public boolean Login(User user);
  //注册
    public boolean Register(User user);
}

UserDao.java

package com.service.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.entity.User;
import com.service.impl.UserImpl;
import com.util.Hibernateutil;

public class UserDao implements UserImpl {
    private Transaction ts = null;
    private String sql = "";
    private Session session = null;

    @Override
    public boolean Login(User user) {
        try {
            getSession();
            sql = "select username,pwd from User where username=?and pwd=?";
            Query query = session.createQuery(sql);
            query.setParameter(0, user.getUsername());
            query.setParameter(1, user.getPwd());
            List list = query.list();
            ts.commit();
            if (!list.isEmpty())
                return true;
            else
                return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    @Override
    public boolean Register(User user) {
        // TODO Auto-generated method stub
        try {
            getSession();
            session.save(user);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    public void getSession() {
        session = Hibernateutil.getSessionFactory().openSession();
        ts = session.beginTransaction();
    }
}

 

6)、设计用户Action类

UserAction.java

package com.action.userAction;

import java.util.Map;

import javax.enterprise.event.Observes;

import org.apache.struts2.interceptor.RequestAware;

import com.entity.User;
import com.service.dao.UserDao;

public class UserAction implements RequestAware {
    private String username;
    private String pwd;
    private Map<String, Object> request;
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String Login() {
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUsername(username);
        user.setPwd(pwd);
        if (userDao.Login(user)) {
            request.put("username", username);
            return "success";
        } else
            return "error";
    }
    public String Register() {
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUsername(username);
        user.setPwd(pwd);
        if(userDao.Register(user)){
            return "success";
        }else
        return "failure";
    }

    @Override
    public void setRequest(Map<String, Object> request) {
        // TODO Auto-generated method stub
        this.request = request;
    }
}

 

7)、注册struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">


<struts>
    <!-- 配置扩展名 -->
    <package name="struts" extends="struts-default" namespace="/">
        <action name="login" class="com.action.userAction.UserAction" method="Login">
            <result name="success">/index.html</result>
            <result name="error">/register.jsp</result>
        </action>
        <action name="register" class="com.action.userAction.UserAction" method="Register">
            <result name="success">/index.html</result>
            <result name="failure">/login.html</result>
        </action>
    </package>
</struts>

7)、效果预览

 8)、具体代码:https://github.com/starryfei/Login_ssh

posted @ 2016-12-01 17:17  starryfei  阅读(10244)  评论(0编辑  收藏  举报