Spring+Struts2+MyBatis集成

简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxdeng/article/details/52278663 加入Stru...
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxdeng/article/details/52278663

1. 加入Struts2, Spring3.3,MyBatis 和数据库驱动包

注意:当有包重复的时候选择高版本即可

2. 添加log4j文件和连接数据库的配置文件

log4j.rootLogger=DEBUG,File,Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c]%m%n

log4j.appender.File=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.File.File=D:/log/SmartBlog.log
log4j.appender.File.MaxFileSize=100MB

log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 

#\u5236\u5B9A\u6D88\u606F\u8F93\u51FA\u7684\u6700\u4F4E\u5C42\u6B21
#指定消息输出的最低层次
log4j.appender.File.Threshold=debug
#包含日志产生的时间、线程、类别等等信息
log4j.appender.File.layout=org.apache.log4j.TTCCLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
AI 代码解读

3. 修改web.xml文件

3.1 指定Spring配置文件的位置

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
AI 代码解读

3.2 添加Spring的监听器

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
AI 代码解读

3.3 添加Struts2的拦截器

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
AI 代码解读

4. 添加Struts2的核心配置文件(struts.xml)和Spring的核心配置文件(applaction.xml)

5. 修改Spring的核心配置文件

5.1 在Spring的核心配置文件中引入头文件

<beans  xmlns="http://www.springframework.org/schema/beans" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans   
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
                            http://www.springframework.org/schema/aop   
                            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
                            http://www.springframework.org/schema/tx   
                            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
                            http://www.springframework.org/schema/context   
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
AI 代码解读

5.2 引入数据库配置文件的位置

<!-- 数据库配置文件位置 -->
<context:property-placeholder location="classpath:jdbc.properties" />
AI 代码解读

5.3 配置数据源

5.3.1 Druid Data Source

<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/ssi" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="10" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />

        <property name="validationQuery" value="SELECT 1" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <property name="filters" value="mergeStat" />
    </bean>
AI 代码解读

5.3.2 dbcp

<!-- 配置dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <!-- 队列中的最小等待数 -->
    <property name="minIdle" value="${jdbc.minIdle}"></property>
    <!-- 队列中的最大等待数 -->
    <property name="maxIdle" value="${jdbc.maxIdle}"></property>
    <!-- 最长等待时间,单位毫秒 -->
    <property name="maxWait" value="${jdbc.maxWait}"></property>
    <!-- 最大活跃数 -->
    <property name="maxActive" value="${jdbc.maxActive}"></property>
    <property name="initialSize" value="${jdbc.initialSize}"></property>
</bean>
AI 代码解读

5.3.3 c3p0连接方式

<!-- 配置c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <!-- 队列中的最小连接数 -->
    <property name="minPoolSize" value="15"></property>
    <!-- 队列中的最大连接数 -->  
    <property name="maxPoolSize" value="25"></property>
    <!-- 当连接耗尽时创建的连接数 -->
    <property name="acquireIncrement" value="15"></property>
    <!-- 等待时间 -->
    <property name="checkoutTimeout" value="10000"></property>
    <!-- 初始化连接数 -->
    <property name="initialPoolSize" value="20"></property>
    <!-- 最大空闲时间,超出时间连接将被丢弃 -->
    <property name="maxIdleTime" value="${jdbc.maxIdleTime}"></property>
    <!-- 每隔60秒检测空闲连接 -->
    <property name="idleConnectionTestPeriod" value="60000"></property>
</bean>
AI 代码解读

5.4 配置SessionFactory

<!-- Spring 整合MyBatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描Mapper文件 -->
<property name="mapperLocations" value="classpath:com/hx/ssi/mapper/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置dao接口路径 -->
<property name="basePackage" value="com.hx.ssi.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
AI 代码解读

5.5 配置事务

<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
AI 代码解读

5.5 事务的通知方式

<!-- 事务的通知方式 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="find*" propagation="REQUIRED" read-only="true" />
        <tx:method name="search*" propagation="REQUIRED" read-only="true" />

        <tx:method name="add*" propagation="REQUIRED" />
        <tx:method name="save*" propagation="REQUIRED" />
        <tx:method name="insert*" propagation="REQUIRED" />

        <tx:method name="del*" propagation="REQUIRED" />
        <tx:method name="remove*" propagation="REQUIRED" />

        <tx:method name="update*" propagation="REQUIRED" />
        <tx:method name="*" propagation="REQUIRED" read-only="true" />
    </tx:attributes>
</tx:advice>
AI 代码解读

5.6 切面

<!-- AOP切面拦截事务 -->
<aop:config>
    <!-- 事务入口(Service的包路径) -->
    <aop:pointcut id="transactionPointcut" expression="execution(* com.hx.ssi.services.*.*(..))" />
    <!-- 将事务通知与切入点组合 -->
    <aop:advisor pointcut-ref="transactionPointcut" advice-ref="txAdvice" />
</aop:config>
AI 代码解读

5.7 引入Spring其他文件[bean…..]

<import resource="xxx.xxx.xxx.xxx.xml" />
AI 代码解读

5.8 在Spring核心配置文件中添加注解扫描的包

<!--  扫描包 -->
<context:component-scan base-package="com.hx.ssi.services" />
<context:component-scan base-package="com.hx.ssi.dao" />
AI 代码解读

5.9 编写各类bean

注意:Action的bean需要修改作用域,默认是单利模式,需要修改为每次请求进来重新创建Bean对象 scope="prototype"
AI 代码解读

6. 修改web.xml文件

6.1 添加编码格式过滤器

<filter>
    <description>字符集过滤器</description>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <description>字符集编码</description>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
AI 代码解读

6.2 添加系统session过期时间

<!-- 配置session超时时间,单位分钟 -->
<session-config>
    <session-timeout>15</session-timeout>
</session-config>
AI 代码解读

6.3 配置内存监听事件

<!-- 防止spring内存溢出监听器 -->
<listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
AI 代码解读

7. Strut2 + Spring + MyBatis整合注解

7.1 Struts注解

1) @Namespace(“/命名空间名字”)
2) @ParentPackage(“struts-default”)
3) @Action
@Action注解代替Action。
value 属性代表xml文件中Action的name属性
results 代表xml文件中的返回值类型,results中可以配置多个result
示例:

results = { @Result(name = "success", type = "redirect", location = "/succes.jsp"), @Result(name = "error", location = "/error.jsp") })
AI 代码解读

name 表示result的那么属性值,type为类型,location跳转的地址
当type为json的时候表示返回的是json字符串,通过params来制定返回那些json字符串

@Action(value = "/login", results = { 
    @Result(name = "success", type = "redirect", location = "/succes.jsp"), 
    @Result(name = "error", location = "/error.jsp"), 
    @Result(name = ActionSupport.LOGIN,type = "json",params = {"root","message"})})
AI 代码解读

注意1:需要使用Struts2注解必须添加struts2-convention-plugin-2.x.x.jar
注意2:如果Actin有集成关系的时候需要返回父类的json时
1. 非注解(xml)

<result type="json">  
    <param name="root">false</param>  
</result>
AI 代码解读

2. 注解

@Result(name = "json", type = "json",params = {"ignoreHierarchy","false"})
AI 代码解读

4) @Service
定义Services层的注解
5) @Repository
定义Dao层的注解
6) @Autowired
注入
2、 注解约定

1、  Struts2约定(了解)
1)  什么是约定
使用约定可以连注解都不写,是真正的零配置,但是它的能力有限,所以这种方式不可取的。
l  Struts2会对Action的命名,以及Action的包名都有限制;
l  Struts2会对结果页面的存放路径,以及结果页面的名称也都有限制。
使用约定与使用注解一样,也要导包:struts2-convention-plugin-2.3.15.jar
2)  约定对Action的限制
约定Action类名:
要求Action的命名必须以“Action”为后缀,例如:UserAction、BookAction等等。可以使用下面常量来修改后缀限制:
<constant name="struts.convention.action.suffix" value="Action"/>
约定Action包名:
要求Action必须放到action、actions、struts、struts2包中。例如:com.hy.action、com.hy.sturts、com.hy.action.user等等。可以使用下面常量来修改Actoin的包
<constant name="struts.convention.package.locators" value="action,actions,struts,struts2"/>
3)  通过Action的限制得到访问路径
上面已经知道约定对Action的限制,现在通过Action的包名和类名得到它的访问路径
例如:com.hy.action.UserAction,它的访问路径为/user.action
例如:com.hy.action.user.UserAction,它的访问路径为/user/user.action。因为在约定包action后面还有一层包user,那么这一层就是名称空间了。
例如:com.action.com.hy.user.UserAction,它的访问路径为/com/hy/user/user.action。
例如:com.hy.action.user.UserListAction, 它的访问路径为/user/user-list.action。当Action名称由多个单词构成,那么在访问路径中使用“-”来连接多个单词。
4)  通过Action的限制得到结果页面路径
Struts2约定限制结果页面必须放到/WEB-INF/content/目录中,可以通过下面常量来修改这个限制。
<constant name="struts.convention.result.path" value="/WEB-INF/content/"/>
AI 代码解读
目录
打赏
0
0
0
0
1
分享
相关文章
第16课:Spring Boot中集成 Shiro
第16课:Spring Boot中集成 Shiro
第15课: Spring Boot中集成ActiveMQ
第15课: Spring Boot中集成ActiveMQ
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
|
4月前
|
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
157 0
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
158 0
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
105 1
Spring boot 使用mybatis generator 自动生成代码插件
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
58 1
若依微服务的Mybatis-plus集成过程:一份详细的入门教程。
以上就是Spring Boot项目中集成MyBatis Plus的详细步骤。集成成功后,你就可以使用Mybatis-plus提供的强大功能,让你的增删改查操作更为简单。以上步骤简单易懂,非常适合初学者使用。希望对您有所帮助。
282 20

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问