Structs2+Hibernate 简单登录验证实例


这里写图片描述


Structs2 和 Hibernate 简单登录验证实例

版本信息

Structs版本 2.3.31
Hibernate版本 4.3.11
Tomcat 8.0
JDK 1.8
Eclipse版本 Neon.1a Release (4.6.1)
Eclipse插件JBoss Tools 4.4.1
数据库 MySQL

案例

综合Structs 和 Hibernate,Structs 做页面跳转,Hibernate代替JDBC执行数据库的操作,登录就是条件查询,注册就是添加数据

这里写图片描述

Jar包,我会发源码

配置Structs环境

必不可缺的文件,直接给出源代码,下面就写这些文件了
数据库,root ,root,要先建立数据库,我建的数据库名为 sh
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>StructsAndHibernateTest</display-name>
  <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

struts.xml

<?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" namespace="/" extends="struts-default">

        <action name="user_login" method="login" class="jxust.action.UserAction">
            <result>/success.jsp</result>
            <result name="input">/index.jsp</result>
            <result name="registersuccess">/index.jsp</result>
        </action>
        <action name="user_register" method="register" class="jxust.action.UserAction">
            <result>/index.jsp</result>
            <result name="input">/register.jsp</result>

        </action>     
    </package>
</struts>

配置 Hibernate 环境

Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/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://127.0.0.1:3306/sh?useUnicod=true&amp;characterEncoding=utf8</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>

    <!-- 加载对应的关系映射文件-->
       <mapping resource="jxust/model/User.hbm.xml"/> 
    </session-factory>
</hibernate-configuration>

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 2016-11-18 10:02:06 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="jxust.model.User" table="USER">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="username" type="java.lang.String">
            <column name="USERNAME" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
    </class>
</hibernate-mapping>

源代码

这里写图片描述

这里写图片描述

源代码顺序是按包从上到下
源代码下载:http://download.csdn.net/detail/peng_hong_fu/9686886

jxust.action

UserAction.java

package jxust.action;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

import jxust.dao.impl.UserDaoImpl;
import jxust.model.User;

@SuppressWarnings("serial")
public class UserAction extends ActionSupport implements SessionAware {
    private String username;
    private String password;
    UserDaoImpl dao = new UserDaoImpl();
    private Map<String, Object> session;

    public  String login(){
        System.out.println(username +","+ password);
        User user = dao.isvalidateAdmin(username, password);
        if (user != null) {
            session.put("loginusername", user.getUsername());
            return SUCCESS;
        } else {
            addFieldError("loginerror", "用户名或密码错误!");
            return INPUT;
        }
    }
    public String register(){
        User user = new User(username,password);
        dao.saveUser(user);
        return "success";   
    }
    //validate验证
    public void validate() {
        if(username==null||"".equals(username)){
            this.addFieldError("username", "用户名不能为空");
        }
        if(password==null||"".equals(password)){
            this.addFieldError("password", "密码不能为空");
        }
    }
    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

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

jxust.dao

HBSessionDao.java

package jxust.dao;

import java.util.List;

import org.hibernate.Session;


public interface HBSessionDao {
    public Session getSession();
    public void closeSession();
    public List search(String hql);
}

UserDao.java

package jxust.dao;

import java.util.List;

import jxust.model.User;

public interface UserDao {
    public void saveUser(User user);
    public List<User> getAll();
    public User isvalidateAdmin(String username,String password);
}

jxust.dao.impl

HBSessionDaoImpl.java

package jxust.dao.impl;

import java.util.List;

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

import jxust.dao.HBSessionDao;

public class HBSessionDaoImpl implements HBSessionDao {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;


    private void init() {
        //创建配置对象
        Configuration cfg = new Configuration().configure(); 
        //创建服务注册对象
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()  
                .applySettings(cfg.getProperties()).build(); 
       //创建会话工厂对象
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);  
        //会话对象
        session =sessionFactory.openSession();
        //开启事务
        transaction = session.beginTransaction();
    }
    @Override
    public Session getSession() {
        init();
        return session;
    }

    @Override
    public void closeSession() {
        transaction.commit();//提交事务
        session.close();// 关闭对话
        sessionFactory.close();// 关闭会话工厂    
    }

    @Override
    public List search(String hql) {
        //查询不用事务管理
        Session session = null;
        session = getSession();
        List alist = null;
        alist = session.createQuery(hql).list();
        session.close();
        return alist;
    }
}

UserDaoImpl.java

package jxust.dao.impl;

import java.util.List;

import org.hibernate.Session;

import jxust.dao.HBSessionDao;
import jxust.dao.UserDao;
import jxust.model.User;

public class UserDaoImpl implements UserDao {

    @Override
    public void saveUser(User user) {
        System.out.println("添加数据...");
        HBSessionDao  hbsessionDao = new HBSessionDaoImpl();
        Session session = hbsessionDao.getSession();
        session.save(user);
        hbsessionDao.closeSession();
        System.out.println("添加数据成功...");
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getAll() {
        List<User> listuser = null;
        HBSessionDao  hbsessionDao = new HBSessionDaoImpl();
        Session session = hbsessionDao.getSession();
         listuser  = session.createQuery("from User").list();
        hbsessionDao.closeSession();//需要关闭
        return listuser;
    }

    @Override
    public User isvalidateAdmin(String username, String password) {
        HBSessionDaoImpl  hbsessionDao= new HBSessionDaoImpl();
        User user = null;
        System.out.println("查询数据库匹配数据...");

        @SuppressWarnings("unchecked")
        List<User> list = hbsessionDao.search(
                "FROM User where username = '" + username + "' and password = '" + password + "'");
        if (list != null && list.size() > 0) {
            user = list.get(0);
            System.out.println("查询到的数据:"+user.toString());
        }
        return user;
    }

    //测试UserDaoImpl
    /* public static void main(String[] args) {
        *//**
         * 插入数据,id为自增长
         *  UserDaoImpl dao = new UserDaoImpl();
            User user1  =new User("秦天明2","12345");
            dao.saveUser(user1);
         *//*
         *//**
          *查询数据
          *UserDaoImpl dao = new UserDaoImpl();
        User user = dao.isvalidateAdmin("秦天明2","12345");
        System.out.println(user.toString());
          *//*
         //查询user表所有数据
         UserDaoImpl dao = new UserDaoImpl();
         List <User> list = dao.getAll();
         System.out.println("共查询到"+list.size()+"条数据");
         for(User s:list){
             System.out.println(s.toString());
         }
    }*/
}

jxust.model

User.java

package jxust.model;
/**
 * 用户个人信息实体类
 * @author Peng
 *
 */
public class User {
    private Integer id;//id
    private String username;//用户名
    private String password;//密码


    public User() {
        super();
    }
    public User( String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
    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 getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }       
}

User 类对应关系映射文件,在配置Hibernate环境时已给出

Hibernate在控制台的一些输出sql语句

添加数据:
Hibernate: 
    select
        max(ID) 
    from
        USER
Hibernate: 
    insert 
    into
        USER
        (USERNAME, PASSWORD, ID) 
    values
        (?, ?, ?)

 查询数据:      
Hibernate: 
    select
        user0_.ID as ID1_0_,
        user0_.USERNAME as USERNAME2_0_,
        user0_.PASSWORD as PASSWORD3_0_ 
    from
        USER user0_ 
    where
        user0_.USERNAME='秦天明2' 
        and user0_.PASSWORD='12345'

 查询所有:      
Hibernate: 
    select
        user0_.ID as ID1_0_,
        user0_.USERNAME as USERNAME2_0_,
        user0_.PASSWORD as PASSWORD3_0_ 
    from
        USER user0_

JSP文件

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!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=UTF-8">
<title>index.jsp起始页</title>
</head>
<body>
   <h1>登录</h1>
    <%-- <s:fielderror fieldName="loginerror"></s:fielderror> --%>
     <s:fielderror></s:fielderror> 
    <form action="user_login.action" method="post">
        用户名:<input type="text" name="username"/><br/>
        密&nbsp;&nbsp;码:<input type="password" name="password"/><br/>
        <input type="submit" value="登录"/>&nbsp;&nbsp;<a href="register.jsp"><input type="button" value="注册"/></a>
    </form>
</body>
</html>

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!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=UTF-8">
<title>register.jsp起始页</title>
</head>
<body>
 <h1>注册</h1>
    <s:fielderror fieldName="registererror"></s:fielderror>
    <form action="user_register.action" method="post">
        用户名:<input type="text" name="username"/><br/>
        密&nbsp;码:<input type="password" name="password"/><br/>
        <input type="submit" value="注册"/><input type="reset" value="重置">
    </form>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>登录成功</title>
</head>
<body>
<h1>欢迎${loginusername},登录成功!</h1>
</body>
</html>

编写过程中的错误和收获

1.没有添加数据库连接驱动名

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

2.解决了一个Action中,多个方法验证失败返回同一个视图的问题
我配置两个action来解决

        <action name="user_login" method="login" class="jxust.action.UserAction">
            <result>/success.jsp</result>
            <result name="input">/index.jsp</result>
            <result name="registersuccess">/index.jsp</result>
        </action>
        <action name="user_register" method="register" class="jxust.action.UserAction">
            <result>/index.jsp</result>
            <result name="input">/register.jsp</result>

        </action>

源代码下载

http://download.csdn.net/detail/peng_hong_fu/9686886

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值