乐者为王

Do one thing, and do it well.

Struts 2 + Hibernate 4登录实例

使用以下代码创建数据库:

1
2
3
4
5
6
7
8
9
10
11
12
CREATE DATABASE IF NOT EXISTS jbookshelf;

USE jbookshelf;

DROP TABLE IF EXISTS users;

CREATE TABLE users (
    id int NOT NULL AUTO_INCREMENT,
    username varchar(20) NOT NULL,
    password varchar(50) NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8;

在pom.xml中添加Hibernate的依赖配置:

1
2
3
4
5
6
7
8
9
10
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.6.Final</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
</dependency>

创建User.java类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.codemany.account.model;

public class User {
    private Long id;

    private String username;
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long 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;
    }
}

在同一目录下创建User.hbm.xml文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.codemany.account.model">
    <class name="User" table="users">
        <id name="id">
            <generator class="increment" />
        </id>

        <property name="username" length="20" />
        <property name="password" length="50" />
    </class>
</hibernate-mapping>

在resources目录下创建hibernate.cfg.xml配置文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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>
        <!-- MySQL connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/jbookshelf</property>
        <property name="connection.username">yourname</property>
        <property name="connection.password">yourpassword</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <mapping resource="com/codemany/account/model/User.hbm.xml" />
    </session-factory>
</hibernate-configuration>

建立管理Session的HibernateUtil.java类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.codemany.account.dao.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            configuration.configure();
            Properties props = configuration.getProperties();

            ServiceRegistry serviceRegistry =
                    new ServiceRegistryBuilder().applySettings(props).buildServiceRegistry();

            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

在dao包创建数据访问对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.codemany.account.dao;

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

import com.codemany.account.model.User;

public class UserDao {
    public static User getUser(String username) {
        Session session = HibernateUtil.getSession();
        try {
            Query query = session.createQuery("from User u where u.username = ?");
            query.setMaxResults(1);
            query.setString(0, username);
            return (User)query.uniqueResult();
        } finally {
            session.close();
        }
    }
}

现在可以访问数据库了,所以要修改LoginAction.java的execute方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public String execute() throws Exception {
    if (username == null || username.length() == 0
            || password == null || password.length() == 0) {
        return INPUT;
    }

    User u = UserDao.getUser(username);
    if (u == null) {
        return INPUT;
    }
    if (username.equals(u.getUsername()) && password.equals(u.getPassword())) {
        ActionContext.getContext().getSession().put("logined", true);
        return SUCCESS;
    }

    return INPUT;
}

如果显示jta-1.0.1b.jar缺失的错误,可以在pom.xml中添加以下语句:

1
2
3
4
5
6
<repositories>
    <repository>
        <id>java.net</id>
        <url>http://download.java.net/maven/2/</url>
    </repository>
</repositories>

代码下载:https://github.com/dohkoos/JBookShelf

Comments