[java web]Idea+maven+spring4+hibernate5+struts2整合过程


摘要

最近也在网上找了些教程,试着使用maven进行包依赖关系的管理,也尝试着通过注解的方式来整合ssh框架。在这个过程中,踩了不少的坑。折腾很长时间,才算把架子折腾起来。这里把结果整理下,作为以后工作中的参考。

项目结构

关于maven如何使用,可自行搜索,默认你有一定的maven基础。maven建议中央仓库配置成阿里云的,可以下载速度快一些。地址

1、开始之前,需要通过maven进行ssh jar包引入。可以参考下面的pom.xml

<?xml version="1.0" encoding="UTF-8"?>

"http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

    com.demo
    mavenapp
    1.0-SNAPSHOT
    war

    mavenapp Maven Webapp
    
    http://www.example.com

    
        
        UTF-8
        1.7
        1.7
        
        4.3.8.RELEASE
        
        5.1.7.Final
        
        2.5.10

    

    
        
        
            junit
            junit
            4.12
            test
        
        
        
            org.springframework
            spring-core
            ${spring.version}
        
        
        
            org.springframework
            spring-web
            ${spring.version}
        
        
        
            org.springframework
            spring-orm
            ${spring.version}
        
        
        
            org.apache.struts
            struts2-core
            ${struts2.version}
        
        
        
            org.apache.struts
            struts2-spring-plugin
            ${struts2.version}
        
        
        
            org.hibernate
            hibernate-core
            ${hibernate.version}
        
        
        
            mysql
            mysql-connector-java
            5.1.42
        
        
        
            com.mchange
            c3p0
            0.9.5
        
        
        
            org.aspectj
            aspectjweaver
            1.8.10
        
        
        
            org.slf4j
            slf4j-log4j12
            1.7.25
        

    
    
        mavenapp
        
            
                
                    maven-clean-plugin
                    3.0.0
                
                
                
                    maven-resources-plugin
                    3.0.2
                
                
                    maven-compiler-plugin
                    3.7.0
                
                
                    maven-surefire-plugin
                    2.20.1
                
                
                    maven-war-plugin
                    3.2.0
                
                
                    maven-install-plugin
                    2.5.2
                
                
                    maven-deploy-plugin
                    2.8.2
                
            
        
    
pom.xml

2、将resources设置为资源目录,并添加如上图所示的jdbc属性文件,struts2配置文件,日志属性文件,spring配置文件

内容分别如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    
    
    
    "classpath:jdbc.properties"/>

    
    base-package="me.demo.*"/>

    
    "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        "jdbcUrl" value="${jdbc.url}"/>
        "driverClass" value="${jdbc.driverClass}"/>
        "user" value="${jdbc.username}"/>
        "password" value="${jdbc.password}"/>
    
    
    
    "sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        
        "dataSource" ref="dataSource"/>
        
        "packagesToScan">
            
                me.demo.domain
            
        
        "hibernateProperties">
            
                "hibernate.show_sql">true
                "hibernate.format_sql">true
                
                "hibernate.hbm2ddl.auto">update
                
                "hibernate.dialect">org.hibernate.dialect.MySQL5Dialect
                
                "hibernate.current_session_context_class">
                    org.springframework.orm.hibernate5.SpringSessionContext
                
            
        
        

    


    
    "transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        "sessionFactory" ref="sessionFactory"/>
    
    
    

    "transactionManager"/>
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
applicationContext.xml
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sshdemo
jdbc.username=root
jdbc.password=abcd
jdbc.properties
log4j.rootCategory=INFO, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %t %c{2}:%L - %m%n
log4j.properties
<?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.objectFactory" value="spring"/>
    "struts.i18n.encoding" value="utf-8"/>
    
    namespace="/" name="default" extends="struts-default">
        <default-action-ref name="default"/>
        "default">
            /index.jsp
        
    
    
    "user" namespace="/" extends="struts-default">
        "user_*" method="{1}" class="userAction">
            "success">/index.jsp
            
                register
            
        
    
struts.xml

3、三层结构,以及注解的使用

package me.demo.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import me.demo.domain.User;
import me.demo.service.UserService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller("userAction")
@Scope("prototype") //默认是单例模式,需配置多例
public class UserAction extends ActionSupport implements ModelDriven {

    private static final Logger log = LogManager.getLogger (UserAction.class);
    private User user = new User ();
    @Autowired
    private UserService userService;

    @Override
    public User getModel() {
        return user;
    }

    public String login() {
        String login = userService.login (user);
        return login;
    }

    public String register() {

        System.out.println (user);
        log.info (user);
        String register = userService.register (user);
        return register;
    }
}
UserAction
package me.demo.dao.Impl;

import me.demo.dao.UserDao;
import me.demo.domain.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository()
@Scope("prototype")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
    @Autowired
    public void setSessionFactoryOverride(SessionFactory sessionFactory) {
        super.setSessionFactory (sessionFactory);
    }

    @Override
    public void save(User user) {
        if (this.getHibernateTemplate () == null)
            System.out.println ("getHibernateTemplate == null");
        this.getHibernateTemplate ().save (user);
    }

    @Override
    public User find(String username, String password) {
        List users = (List) this.getHibernateTemplate ().find ("from User where username=? and password=?", username, password);
        if (users.size () > 0)
            return users.get (0);
        return null;
    }
}
UserDaoImpl
package me.demo.dao;

import me.demo.domain.User;

/**
 * 接口
 */
public interface UserDao {

    void save(User user);

    User find(String username, String password);
}
UserDao
package me.demo.domain;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "t_users")
public class User implements Serializable {
    @Id
    @GeneratedValue(generator = "autoGenerator")//根据数据库的主键生成策略
    @GenericGenerator(name = "autoGenerator", strategy = "native")
    private Integer id;
    @Column
    private String name;
    @Column
    private String password;
    @Column
    private Integer sex;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSex() {
        return sex;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex=" + sex +
                '}';
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
User
package me.demo.service.Impl;

import me.demo.dao.UserDao;
import me.demo.domain.User;
import me.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


@Service()
@Scope("prototype")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;


    public String login(User user) {
        User user1 = userDao.find (user.getName (), user.getPassword ());
        if (user1 != null)
            return "success";
        return "not found";
    }


    public String register(User user) {
        userDao.save (user);
        return "success";
    }
}
UserServiceImpl
package me.demo.service;


import me.demo.domain.User;

public interface UserService {
    String login(User user);

    String register(User user);
}
UserService

4、web

<%--
  Created by IntelliJ IDEA.
  User:
  Date: 2018/6/8
  Time: 17:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    首页



url:${pageContext.request.contextPath}
登录
注册
index.jsp
<%--
  Created by IntelliJ IDEA.
  User:
  Date: 2018/6/8
  Time: 17:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登录


姓名:
login.jsp
<%--
  Created by IntelliJ IDEA.
  User:
  Date: 2018/6/8
  Time: 17:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    注册


姓名:
密码: 性别:   
register.jsp

5、配置tomcat服务器,然后启动即可,会自动生成数据库表结构(前提自己手动创建好数据库)

6、测试

总结

1、虽然网络上这样的文章很多,但自己动手实现,发现还是有很多错误,发现最多的是,由jar的版本问题引起的,比如在配置问价中org.springframework.orm.hibernate5.LocalSessionFactoryBean这个类所在的包,在hibernate3,4,5中都有,如果你在配置文件中所写的,和HibernateDaoSupport所使用的包版本不一致,就会出错。

2、org.hibernate.dialect.MySQL5Dialect,方言的配置,hibernate关于mysql的方言就有三个,这里采用MySQL5Dialect。

3、然后就是事务了,采用事务的注解,需要在配置文件中进行配置事务管理器。

annotation-driven:

这是xsd中 对事务管理器的描述。

Indicates that transaction configuration is defined by Java 5
    annotations on bean classes, and that proxies are automatically
    to be created for the relevant annotated beans.

    The default annotations supported are Spring's @Transactional
    and EJB3's @TransactionAttribute (if available).

    Transaction semantics such as propagation settings, the isolation level,
    the rollback rules, etc are all defined in the annotation metadata.

    See org.springframework.transaction.annotation.EnableTransactionManagement Javadoc
    for information on code-based alternatives to this XML element.
                ]]>xsd:documentation>
            xsd:annotation>
            <xsd:attribute name="transaction-manager" type="xsd:string" default="transactionManager">
                <xsd:annotation>
                    <xsd:documentation source="java:org.springframework.transaction.PlatformTransactionManager">
    The bean name of the PlatformTransactionManager that is to be used
    to drive transactions.

    This attribute is not required, and only needs to be specified
    explicitly if the bean name of the desired PlatformTransactionManager
    is not 'transactionManager'.

4、一定要有耐心。一个个解决问题,也是一种积累。