struts2+Hibernate实现用户登陆功能

实现的功能,在登陆页面输入Username和PassWord后,将username和password通过Hibernate匹对数据库是否含有一样的username和password,若有则登陆进去,若没有则返回到登陆页面

显示层

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
    <form action="userlogin">
          用户名:<input type="text" name="username"><br/>
          密码:<input type="password" name="password"><br/>
        <input type="submit" value="submit">
        <input type="reset" value="reset">
    </form>
</body>
</html>

model层

User

package com.zs.model;

public class User {
    private String username;
    private String password;
    private Short sex;
    private String email;
    private String address;
    private String grade;

    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;
    }

    public Short getSex() {
        return sex;
    }

    public void setSex(Short sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}

User.hbm.xml:

<?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 2014-12-14 14:51:48 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.zs.model.User" table="USER">
        <id name="username" type="java.lang.String">
            <column name="USERNAME" />
            <generator class="assigned" />
        </id>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
        <property name="sex" type="java.lang.Short">
            <column name="SEX" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="EMAIL" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="ADDRESS" />
        </property>
        <property name="grade" type="java.lang.String">
            <column name="GRADE" />
        </property>
    </class>
</hibernate-mapping>

Hibernate:

配置hibernate.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
         <!--连接数据库的配置-->
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///hibernate</property>
        
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!--数据库映射Java用户-->
        <mapping resource="com/zs/model/User.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Struts:

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

<struts>

    <package name="default" extends="struts-default">
        <!--登陆主页面时候的Action-->
        <action name="index">
            <result>/index.jsp</result>
        </action>
        <!--在index.jsp提交submit后若登陆成功则转到adminlogin,否则转到index-->
        <action name="userlogin" class="com.zs.web.admin.AdminLoginAction">
            <result name="success">/admin/adminlogin.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>

</struts>

Action:

package com.zs.web.admin;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.zs.dao.UserDao;
import com.zs.dao.impl.UserDaoImpl;
import com.zs.model.User;

public class AdminLoginAction extends ActionSupport implements SessionAware {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    UserDao dao = new UserDaoImpl();
    private String username;
    private String password;
    private Map<String,Object> session;
    
    public String execute(){
            User user = dao.isValidAdmin(username, password);//将username和password传递到dao层交个hibernate判断
            if(user!=null){
                session.put("user", user);//若登陆成功则将该user记录在session中
                return SUCCESS;
            }else{
                addActionError("你没有管理权限");
                return INPUT;
            }
    }
    
    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;
    }

    public Map getSession() {
        return session;
    }

    public void setSession(Map session) {
        this.session = session;
    }

}

判断用户和密码是否存在于数据库中

package com.zs.dao.impl;

import java.util.List;

import com.zs.dao.BaseDaoImpl;
import com.zs.dao.UserDao;
import com.zs.model.User;

public class UserDaoImpl extends BaseDaoImpl implements UserDao {

    @Override
    public void saveUser(User user) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public List<User> getAll(Class clazz) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public User isValidUser(String username, String password) {
        // TODO Auto-generated method stub
        return null;
    }

    //判断数据库中时候含有该用户
    @Override
    public User isValidAdmin(String username, String password) {
        User user = null;
        //调用hibernate
        List<User> list =super.search("FROM User WHERE grade='admin' AND username ='"+username+"' AND password = '"+password+"'");
        if(list!=null && list.size()>0){//若找到的list不为空那么则说明数据库中包含这个人
            user = list.get(0);
        }
        return user;
    }

}

Hibernate初始化借口并且从数据库中取数据

package com.zs.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class BaseDaoImpl implements IBaseDao {

    private  SessionFactory sessionFactory;
    private  Session session;
    private  Transaction transaction;
    
    //初始session接口
    public void init(){
        Configuration configuration = new Configuration().configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                                  .buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
    }
    @Override
    public Session getSession() {
        init();
        return session;
    }

    @Override
    public void closeSession() {
        session.close();

    }

    @Override
    public List search(String hql) {
        //调用session接口
        Session session = null;
        session = getSession();
        List alist = null;
        alist = session.createQuery(hql).list();//从数据库中查询
        session.close();
        return alist;
    }

}

可以先建好一个名为User的数据库,设置一个用户,然后便可以测试了

完整代码可以在我github下载:https://github.com/calmound/web/tree/master/web

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Java成神之路

HQL语句大全

Hibernate配备了一种非常强大的查询语言,这种语言看上去很像SQL。但是不要被语法结构 上的相似所迷惑,HQL是非常有意识的被设计为完全面向对象的查询,它...

1785
来自专栏函数式编程语言及工具

浅谈Slick(1)- 基本功能描述

   Slick (Scala language-integrated connection kit)是scala的一个FRM(Functional Relat...

1837
来自专栏Java成神之路

Java_脚本引擎_01_用法入门

最近有个需求,需要在js中调用java,这样能避免更新java,从而实现代码的热更新。

1244
来自专栏深度学习之tensorflow实战篇

Shapes and line types for R

Solution ? ? Note that with bitmap output, the filled symbols 15-18 may render ...

3908
来自专栏分布式系统进阶

Librdkafka的基础数据结构 4 --- String和ByteArray

1403
来自专栏别先生

Java枚举类使用和总结

1142
来自专栏MasiMaro 的技术博文

windows错误处理

在调用windows API时函数会首先对我们传入的参数进行校验,然后执行,如果出现什么情况导致函数执行出错,有的函数可以通过返回值来判断函数是否出错,比如对于...

1372
来自专栏Jerry的SAP技术分享

使用Java connector消费ABAP系统的函数

Java Connector(JCO)环境的搭建:Step by step to download and configure JCO in your lapt...

1892
来自专栏Hongten

spring开发_JDBC操作MySQL数据库

http://www.cnblogs.com/hongten/gallery/image/112450.html

1972
来自专栏Java编程技术

SpringBoot+MyBatis通用Mapper3实践浅析

MyBatis通用Mapper3是对mybaits的数据库操作的一层封装,之前使用时候是根据数据库表生成mapper.xml,mapper的接口类,这个mapp...

1551

扫码关注云+社区

领取腾讯云代金券