说句实话,很久都没使用SSH开发项目了,但是出于各种原因,再次记录一下整合方式,纯注解零配置。

一。前期准备工作

gradle配置文件:

group 'com.bdqn.lyrk.ssh.study'
version '1.0-SNAPSHOT' apply plugin: 'war' repositories {
mavenLocal()
mavenCentral()
} dependencies {
// https://mvnrepository.com/artifact/org.apache.struts/struts2-core
compile group: 'org.apache.struts', name: 'struts2-core', version: '2.5.14.1' // https://mvnrepository.com/artifact/org.apache.struts/struts2-spring-plugin
compile group: 'org.apache.struts', name: 'struts2-spring-plugin', version: '2.5.14.1'
// https://mvnrepository.com/artifact/org.springframework/spring-context
compile group: 'org.springframework', name: 'spring-context', version: '5.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.springframework/spring-web
compile group: 'org.springframework', name: 'spring-web', version: '5.0.4.RELEASE' // https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final'
// https://mvnrepository.com/artifact/org.hibernate/hibernate-validator
compile group: 'org.hibernate', name: 'hibernate-validator', version: '5.4.1.Final' // https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
// https://mvnrepository.com/artifact/org.springframework/spring-orm
compile group: 'org.springframework', name: 'spring-orm', version: '5.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.springframework/spring-tx
compile group: 'org.springframework', name: 'spring-tx', version: '5.0.4.RELEASE' // https://mvnrepository.com/artifact/com.zaxxer/HikariCP
compile group: 'com.zaxxer', name: 'HikariCP', version: '2.7.4'
// https://mvnrepository.com/artifact/org.apache.struts/struts2-convention-plugin
compile group: 'org.apache.struts', name: 'struts2-convention-plugin', version: '2.5.14.1' testCompile group: 'junit', name: 'junit', version: '4.11'
}

结构文件:

注意在classpath下创建META-INF/services/javax.serlvet.ServletContainerInitializer文件,那么在文件中定义的类在servlet容器启动时会执行onStartup方法,我们可以在这里编码创建servlet,fliter,listener等,文件内容如下:

com.bdqn.lyrk.ssh.study.config.WebInitializer

二。具体的集成实现方案

1.定义 MyAnnotationConfigWebApplicationContext

package com.bdqn.lyrk.ssh.study.config;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

/**
* 自定义配置,为了在ContextLoaderListener初始化注解配置时使用
* @Author chen.nie
*/
public class MyAnnotationConfigWebApplicationContext extends AnnotationConfigWebApplicationContext { public MyAnnotationConfigWebApplicationContext(){
this.register(AppConfig.class);
}
}

2.定义WebInitializer

package com.bdqn.lyrk.ssh.study.config;

import org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import javax.servlet.*;
import javax.servlet.annotation.HandlesTypes;
import javax.servlet.http.HttpServlet;
import java.util.EnumSet;
import java.util.Set; /**
* 自定义servlet容器初始化,请参考servlet规范
*/
@HandlesTypes({HttpServlet.class, Filter.class})
public class WebInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
/*
创建struts2的核心控制器
*/
StrutsPrepareAndExecuteFilter strutsPrepareAndExecuteFilter = ctx.createFilter(StrutsPrepareAndExecuteFilter.class);
OpenSessionInViewFilter openSessionInViewFilter = ctx.createFilter(OpenSessionInViewFilter.class);
/*
向servlet容器中添加filter
*/
ctx.addFilter("strutsPrepareAndExecuteFilter", strutsPrepareAndExecuteFilter).
addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
FilterRegistration.Dynamic dynamic = ctx.addFilter("openSessionInViewFilter", openSessionInViewFilter);
dynamic.setInitParameter("flushMode", "COMMIT");
dynamic.setInitParameter("sessionFactoryBeanName","localSessionFactoryBean");
dynamic.setInitParameter("singleSession","true");
dynamic.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
/*
添加监听器
*/
ContextLoaderListener contextLoaderListener = new ContextLoaderListener();
ctx.addListener(contextLoaderListener);
ctx.setInitParameter("contextClass", "com.bdqn.lyrk.ssh.study.config.MyAnnotationConfigWebApplicationContext"); }
}

3.定义AppConfig

package com.bdqn.lyrk.ssh.study.config;

import com.zaxxer.hikari.HikariDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource;
import java.util.Properties; /**
* spring基于注解配置
*
* @author chen.nie
* @date 2018/3/21
**/
@Configuration
@ComponentScan("com.bdqn")
@EnableTransactionManagement
public class AppConfig { /**
* 定义数据源
* @return
*/
@Bean
public HikariDataSource dataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setDriverClassName("com.mysql.jdbc.Driver");
hikariDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/MySchool?characterEncoding=utf-8&useSSL=false");
hikariDataSource.setUsername("root");
hikariDataSource.setPassword("root");
return hikariDataSource;
} /**
* 定义spring创建hibernate的Session对象工厂
* @param dataSource
* @return
*/
@Bean
public LocalSessionFactoryBean localSessionFactoryBean(@Autowired DataSource dataSource) {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource);
localSessionFactoryBean.setPackagesToScan("com.bdqn.lyrk.ssh.study.entity");
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.setProperty("hibernate.show_sql", "true");
localSessionFactoryBean.setHibernateProperties(properties);
return localSessionFactoryBean;
} /**
* 定义hibernate事务管理器
* @param localSessionFactoryBean
* @return
*/
@Bean
public HibernateTransactionManager transactionManager(@Autowired SessionFactory localSessionFactoryBean) {
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager(localSessionFactoryBean);
return hibernateTransactionManager;
} /**
* 定义hibernateTemplate
* @param localSessionFactoryBean
* @return
*/
@Bean
public HibernateTemplate hibernateTemplate(@Autowired SessionFactory localSessionFactoryBean) {
HibernateTemplate hibernateTemplate = new HibernateTemplate(localSessionFactoryBean);
return hibernateTemplate;
}
}

4.定义实体类

package com.bdqn.lyrk.ssh.study.entity;

import javax.persistence.*;

@Table(name = "student")
@Entity
public class StudentEntity { @GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Integer id; @Column(name = "stuName")
private String stuName; @Column(name = "password")
private String password; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getStuName() {
return stuName;
} public void setStuName(String stuName) {
this.stuName = stuName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

5.定义service

package com.bdqn.lyrk.ssh.study.service;

import com.bdqn.lyrk.ssh.study.entity.StudentEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; @Service
public class StudentService { @Autowired
private HibernateTemplate hibernateTemplate; @Transactional
public int save(StudentEntity studentEntity){
hibernateTemplate.save(studentEntity);
return studentEntity.getId();
}
}

6.定义action 请大家留意关于struts2注解的注意事项

package com.bdqn.lyrk.ssh.study.action;

import com.bdqn.lyrk.ssh.study.entity.StudentEntity;
import com.bdqn.lyrk.ssh.study.service.StudentService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; /**
* struts2注解配置,注意:
* 1.所在的包名必须以action结尾
* 2.Action要必须继承ActionSupport父类;
* 3.添加struts2-convention-plugin-xxx.jar
*
* @author chen.nie
* @date 2018/3/21
**/
@Scope("prototype")
@ParentPackage("struts-default") //表示继承的父包
@Namespace(value = "/") //命名空间
public class IndexAction extends ActionSupport { @Autowired
private StudentService studentService; @Action(value = "index", results = {@Result(name = "success", location = "/index.jsp")})
public String index() {
StudentEntity studentEntity = new StudentEntity();
studentEntity.setStuName("test");
studentEntity.setPassword("123");
studentService.save(studentEntity);
ActionContext.getContext().getContextMap().put("student", studentEntity);
return com.opensymphony.xwork2.Action.SUCCESS;
}
}

7.index.jsp

<%--
Created by IntelliJ IDEA.
User: chen.nie
Date: 2018/3/21
Time: 下午6:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ssh基于零配置文件整合</title>
</head>
<body>
新增的学生id为:${student.id}
</body>
</html>

启动tomcat,访问http://localhost:8080/index得到如下界面:

总结:前面我写过ssm基于注解零配置整合,那么ssh其思路也大体相同,主要是@Configuration @Bean等注解的使用,但是大家请留意的是struts2的注解与servlet的规范(脱离web.xml,手动添加servlet filter listener等)

spring+hibernate+struts2零配置整合的更多相关文章

  1. SSH(struts+spring+hibernate)常用配置整理

    SSH(struts+spring+hibernate)常用配置整理 web.xml配置 <?xml version="1.0" encoding="UTF-8&q ...

  2. Spring4.X + spring MVC + Mybatis3 零配置应用开发框架搭建详解(1) - 基本介绍

    Spring4.X + spring MVC + Mybatis3 零配置应用开发框架搭建详解(1) - 基本介绍 spring集成 mybatis Spring4.x零配置框架搭建 两年前一直在做后 ...

  3. Spring 基于注解零配置开发

    本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址:< Spring 基于注解零配置开发 > 一:搜索Bean 再也不用在XML文件里写什么配置信息了. Sprin ...

  4. idea spring+springmvc+mybatis环境配置整合详解

    idea spring+springmvc+mybatis环境配置整合详解 1.配置整合前所需准备的环境: 1.1:jdk1.8 1.2:idea2017.1.5 1.3:Maven 3.5.2 2. ...

  5. Struts2 Convention Plugin ( struts2 零配置 )

    Struts2 Convention Plugin ( struts2 零配置 ) convention-plugin 可以用来实现 struts2 的零配置.零配置的意思并不是说没有配置,而是通过约 ...

  6. Spring+Hibernate+Struts(SSH)框架整合

    SSH框架整合 前言:有人说,现在还是流行主流框架,SSM都出来很久了,更不要说SSH.我不以为然.现在许多公司所用的老项目还是ssh,如果改成流行框架,需要成本.比如金融IT这一块,数据库dao层还 ...

  7. Spring+Hibernate+struts2+JPA 注解+跨域//完成手机端点击加载更多 下拉加载更多

    一.使用IDEA新建一个maven项目(student) 1.1.0编写pom文件,添加项目所需要的包 <?xml version="1.0" encoding=" ...

  8. 菜鸟学Struts2——零配置(Convention )

    又是周末,继续Struts2的学习,之前学习了,Struts的原理,Actions以及Results,今天对对Struts的Convention Plugin进行学习,如下图: Struts Conv ...

  9. Struts2零配置介绍(约定访问)

    从struts2.1开始,struts2 引入了Convention插件来支持零配置,使用约定无需struts.xml或者Annotation配置 需要 如下四个JAR包 插件会自动搜索如下类 act ...

随机推荐

  1. visualVM使用jstatd和jmx连接远程jvm及遇到的问题解决

    visualVM使用jstatd和jmx连接远程jvm及遇到的问题解决 JMX方式: 编辑Tomact里bin目录的catalina.sh . 在其头部加入 JAVA_OPTS=" -Dco ...

  2. nyoj 复杂度

    复杂度 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 for(i=1;i<=n;i++) for(j=i+1;j<=n;j++) for(k=j+1;k ...

  3. java 注解的实现机制

    一.什么是注解: 注解是标记,也可以理解成是一种应用在类.方法.参数.属性.构造器上的特殊修饰符.注解作用有以下三种: 第一种:生成文档,常用的有@param@return等. 第二种:替代配置文件的 ...

  4. 使用 HttpClient 请求 Web Api

    1.获取 post 请求 body 内容 [HttpPost] public string GetId() { //如果方法参数里面有 [FromBody],则需要重新调整内容指针,再进行读取. // ...

  5. ### Cause: org.apache.ibatis.binding.BindingException: Parameter 'name' not found. Available parameters are [arg1, arg0, param1, param2]

    org.apache.ibatis.exceptions.PersistenceException: ### Error updating database. Cause: org.apache.ib ...

  6. First:安装配置JDK and 部署Tomcat

    (一)准备 百度云地址(win,64Bit): 1.tomcat(7.0):链接:https://pan.baidu.com/s/1f60DOGO5Hnj9bq-987FNrw 密码:6q55 2.j ...

  7. Linux进程管理:查杀进程

    一.查看进程 Linux下显示系统进程的命令ps,最常用的有ps -ef 和ps aux.这两个到底有什么区别呢? 两者没太大差别,讨论这个问题,要追溯到Unix系统中的两种风格,System V风格 ...

  8. 记一次将公司网站http换成https

    看了博客园将近一年了,一直都只是在被动的看,总觉得应该写点什么,但是又不知道该写点什么.今天正好公司要把网站由http换成https,那我就顺便记录一下吧. 由于之前没有弄过,所以就面向百度编程. 首 ...

  9. DevExpress 控件中GridControl的使用

    近期开发用到了DevExpress系列的控件,GridControl是我用到的Dev系列控件最多的一个控件.现在先来总结一下: 首先先写一个简单的小例子来简单介绍一下GridControl的用法: 1 ...

  10. Python REST

    Django REST framework 1. 什么是REST REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译 ...