专栏首页calmoundstruts2+Hibernate实现用户登陆功能

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 条评论
登录 后参与评论

相关文章

  • 畅通工程(最小生成树)

    首先要判断能否构成生成树,刚开始的思路是用hash遍历城市,看是否所有的城市都记录进取,被测试数据误导,如果给这组数据(1,2)(3,4)这么没办法构成单树。 ...

    用户1624346
  • 基于iframe的移动端嵌套

    需求描述 上上周接到了新的项目,移动端需要做一个底部有五个导航,点击不同的导航页面主体显示不同的页面,其中两个页面是自己做,而另外三个页面是引用另外三个网址,其...

    用户1624346
  • Catch That Cow

    经过+1,-1,*2的操作,使第一个数等于第二个数 求最少步骤都是用的广搜 #include<stdio.h> #include<queue> #include...

    用户1624346
  • Hibernate框架简单应用步骤

    用户1127987
  • android 应用模式之mvp

    说到MVP就不得不提到MVC,做过J2EE的猿友们肯定知道MVC是个什么东西。MVC即 Model、View、Controller, 那MVP就Model、Vi...

    xiangzhihong
  • Retrofit网络请求库应用02——json解析

    PS:上一篇写了Retrofit网络请求库的简单使用,仅仅是获取百度的源码,来证明连接成功,这篇讲解如何解析JSON数据,该框架不再是我们之前自己写的那样用Js...

    cMusketeer
  • javaWeb项目(SSH框架+AJAX+百度地图API+Oracle数据库+MyEclipse+Tomcat)之二 基础Hibernate框架搭建篇

       我们在搭建完Struts框架之后,从前台想后端传送数据就显得非常简单了。Struts的功能不仅仅是一个拦截器,这只是它的核心功能,此外我们也可以自定义拦截...

    ShenduCC
  • [ SSH框架 ] Struts2框架学习之二

      前面已经对 Struts2的流程已经执行完成了,但是如果表单中有参数如何进行接收又或者我们需要向页面保存一些数据,又要如何完成呢?我们可以通过学习 Stru...

    Kevin_Zhang
  • Hibernate笔记(二)

    1.一对多的关系映射 对于一的一方: package domain; import java.util.HashSet; import java.util.S...

    lwen
  • Java自动化测试(登陆接口测试 14)

    zx钟

扫码关注云+社区

领取腾讯云代金券