乐者为王

Do one thing, and do it well.

Struts 2 + Spring 3 + Hibernate 4登录实例

在pom.xml中添加Spring的依赖包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<!-- 注意:没有这个plugin包会导致Spring无法注入bean到Struts 2的Action中 -->
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-spring-plugin</artifactId>
    <version>2.3.4.1</version>
</dependency>

配置web.xml文件,加上Spring的监听器:

1
2
3
4
5
6
7
8
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

删除hibernate.cfg.xml,添加applicationContext.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
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- DriverManagerDataSource在每个连接请求时都新建一个connection。
         与DBCP的BasicDataSource不同,DriverManagerDataSource提供的连接没有进行池管理 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/jbookshelf" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.pool_size">1</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</prop>
                <prop key="show_sql">true</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>com/codemany/account/model/User.hbm.xml</value>
            </list>
        </property>
    </bean>

    <bean id="userDao" class="com.codemany.account.dao.UserDao">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Struts 2的action是有状态的,必须显式设置scope为prototype,这样每次请求过来都会创建新的action -->
    <bean id="loginAction" class="com.codemany.account.action.LoginAction" scope="prototype">
        <property name="userDao" ref="userDao" />
    </bean>
</beans>

删除HibernateUtil.java,修改UserDao.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
package com.codemany.account.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.codemany.account.model.User;

public class UserDao {
    // Spring 3集成Hibernate 4不再需要HibernateDaoSupport或HibernateTemplate了,
    // 直接使用原生API即可。
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

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

在struts.xml中将action元素中login的class属性改为applicationContext.xml配置文件中的loginAction:

1
2
3
4
<action name="login" class="loginAction">
    <result name="success">/index.jsp</result>
    <result name="input">/index.jsp</result>
</action>

修改LoginAction.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
33
34
35
36
37
38
39
40
41
42
43
package com.codemany.account.action;

import com.codemany.account.dao.UserDao;
import com.codemany.account.model.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private static final long serialVersionUID = -389833745243649130L;

    private String username;
    private String password;

    private UserDao userDao;

    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 || !password.equals(u.getPassword())) {
            return INPUT;
        }

        ActionContext.getContext().getSession().put("logined", true);
        return SUCCESS;
    }

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

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

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

Comments