博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[java web]Idea+maven+spring4+hibernate5+struts2整合过程
阅读量:6177 次
发布时间:2019-06-21

本文共 13407 字,大约阅读时间需要 44 分钟。

摘要

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

项目结构

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

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

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配置文件

内容分别如下:

me.demo.domain
true
true
update
org.hibernate.dialect.MySQL5Dialect
org.springframework.orm.hibernate5.SpringSessionContext
applicationContext.xml
jdbc.driverClass=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/sshdemojdbc.username=rootjdbc.password=abcd
jdbc.properties
log4j.rootCategory=INFO, consolelog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.layout=org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %t %c{
2}:%L - %m%n
log4j.properties
/index.jsp
/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")@Transactionalpublic 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、<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>,方言的配置,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.                ]]>                        

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

转载于:https://www.cnblogs.com/wolf-sun/p/9159547.html

你可能感兴趣的文章
packets
查看>>
使用SVN提示“工作副本已经锁定”的解决办法
查看>>
关于索引删除的策略IndexDeletionPolicy
查看>>
【Tesseract-OCR】在VS2012环境下调用API方法---注意避免名字冲突
查看>>
用C#.NET实现电子邮件客户程序
查看>>
【百度地图API】发布静态图API啦!只需一个网址,即可展示定制百度地图!
查看>>
微信连Wi-Fi专业设备列表
查看>>
介绍ASP.NET MVC4
查看>>
INSERT INTO .. ON DUPLICATE KEY更新多行记录
查看>>
Android 如何制作九宫格图片(.9.png)
查看>>
Linux系统的快速启动机制(内核切换) 【转】
查看>>
模板缓冲与阴影体 【转】
查看>>
PAT-B 1015. 德才论(同PAT 1062. Talent and Virtue)
查看>>
sql 简单事务例子
查看>>
每天进步一点点——Linux中的线程局部存储(二)
查看>>
hdu 3642 Get The Treasury (三维的扫描线)
查看>>
coffeeScript demo
查看>>
MySQL数据库服务器的架设
查看>>
iOS: 极光推送
查看>>
Tornado长轮询和WebSocket
查看>>