SSM整合 Spring5.0 + Spring MVC5.0 + Mybatis3.5 + java 8
MyBatis-Spring MyBatis Spring Spring Batch Java
2.0 3.5+ 5.0+ 4.0+ Java 8+
配置文件:
jdbc.properties 数据库连接
log4j2.xml。 日志
mybatis-config.xml mybatis配置
spring-dao.xml。 spring 数据源,sqlSessionFactory注入,扫描mapper,映射entity配置
spring-service.xml。Spring 事物配置
spring-web.xml。 spring 视图配置
目录结构
com.controller @Controller (Spring MVC 控制层)
com.dao @Repository (中就事Mapper接口)
com.entity 实体类
com.service @Service(添加在接口实现类上)
com.test
需要的jar包
ant-1.10.3.jar
ant-launcher-1.10.3.jar
asm-7.0.jar
aspectjweaver.jar
c3p0-0.9.5.jar
cglib-3.2.10.jar
commons-logging-1.2.jar
jackson-annotations-2.9.5.jar
jackson-core-2.9.5.jar
jackson-databind-2.9.5.jar
javassist-3.24.1-GA.jar
javax.el-2.2.4.jar
javax.el-api-2.2.4.jar
javax.servlet.jsp.jstl.jar
jstl-impl-1.2.2.jar
jstl-impl.jar
log4j-api-2.12.1.jar
log4j-core-2.12.1.jar
log4j-slf4j-impl-2.12.1.jar
log4j-web-2.12.1.jar
mchange-commons-java-0.2.11.jar
mybatis-3.5.2.jar
mybatis-spring-2.0.0.jar
mysql-connector-java-5.1.0-bin.jar
ognl-3.2.10.jar
slf4j-api-1.7.28.jar
spring-aop-5.0.0.RELEASE.jar
spring-aspects-5.0.0.RELEASE.jar
spring-beans-5.0.0.RELEASE.jar
spring-context-5.0.0.RELEASE.jar
spring-core-5.0.0.RELEASE.jar
spring-expression-5.0.0.RELEASE.jar
spring-jdbc-5.0.0.RELEASE.jar
spring-test-5.0.0.RELEASE.jar
spring-tx-5.0.0.RELEASE.jar
spring-web-5.0.0.RELEASE.jar
spring-webmvc-5.0.0.RELEASE.jar
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mysql
jdbc.username=root
jdbc.password=root
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL --> <!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出--> <!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数--> <configuration status="WARN" monitorInterval="30"> <!--先定义所有的appender--> <Appenders> <!--这个输出控制台的配置--> <console name="Console" target="SYSTEM_OUT"> <!--输出日志的格式--> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> </console> <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用--> <File name="log" fileName="log/test.log" append="false"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/> </File> <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档--> <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/info.log" filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)--> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/warn.log" filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 --> <DefaultRolloverStrategy max="20"/> </RollingFile> <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/error.log" filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/> <Policies> <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> </Appenders> <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效--> <loggers> <root level="debug"> <appender-ref ref="Console"/> <appender-ref ref="RollingFileInfo"/> <appender-ref ref="RollingFileWarn"/> <appender-ref ref="RollingFileError"/> </root> </loggers> </configuration>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置全局属性 --> <settings> <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 --> <setting name="useGeneratedKeys" value="true" /> <!-- 使用列别名替换列名 --> <!-- <setting name="useColumnLabel" value="true"/> --> <!-- 开启驼峰命名转换(userId === user_id) --> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <typeAliases> <typeAlias type="com.entity.User" alias="User" /> </typeAliases> </configuration>
spring-dao.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 配置整合mybatis过程 --> <!-- 1、配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2、配置数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置连接池属性 --> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="{jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- c3p0连接池的私有属性 --> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!-- 关闭连接不自动commit --> <property name="autoCommitOnClose" value="false"/> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="10000"/> <!-- 当获取连接失败时重试次数 --> <property name="acquireRetryAttempts" value="2"/> </bean> <!-- 3、配置mybatis的sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mappers.xml文件 --> <property name="mapperLocations" value="classpath:com/dao*.xml"/> <!-- 扫描mybatis-config文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 扫描entity包,使用别名,或者在mybatis-config中配置,二选一 --> <property name="typeAliasesPackage" value="com.entity"></property> </bean> <!-- 4、DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <property name="basePackage" value="com.dao" /> </bean> </beans>
spring-service.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="com.service"/> <!-- 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <tx:advice id="txadvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="find*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" rollback-for="RuntimeException" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.service.*.*(..))" id="pointcut" /> <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut" /> </aop:config> </beans>
spring-web.xml
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 配置springmvc --> <!-- 扫描web相关的bean --> <context:component-scan base-package="com.controller"/> <!-- 静态资源默认servlet配置 --> <mvc:annotation-driven /> <!-- 静态资源映射 --> <!--<mvc:resources mapping="/layui/images/**" location="/WEB-INF/static/layui/images/"/>--> <!--<mvc:resources mapping="/layui/css/**" location="/WEB-INF/static/layui/css/"/>--> <!--<mvc:resources mapping="/layui/font/**" location="/WEB-INF/static/layui/font/"/>--> <!--<mvc:resources mapping="/layui/lay/**" location="/WEB-INF/static/layui/lay/"/>--> <mvc:resources mapping="/layui/**" location="layui/" /> <mvc:resources mapping="/font/**" location="font/" /> <mvc:resources mapping="/js/**" location="js/" /> <!-- 配置jsp 显示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- 设置字符集 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <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> <!-- 配置DispatcheServlet --> <servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup><!-- 加载优先 --> <async-supported>true</async-supported><!-- 支持异步处理。 --> </servlet> <servlet-mapping> <servlet-name>spring-dispatcher</servlet-name> <url-pattern>/</url-pattern><!-- 匹配所有请求 --> </servlet-mapping> </web-app>
Test
/*dao*/ @Repository public interface UserMapper { public List<User> select(); } /*service*/ @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> get() { return userMapper.select(); } } /*controller*/ @Controller public class UserController { @Resource UserService userService; @RequestMapping("list") public String userlist(Model model,HttpSession session) { List<User> list = userService.get(); session.setAttribute("userlist", list); return "list"; } /** * 负责转化Date日期类型,否则表单提交有Date类型警告 * Failed to convert value of type 'java.lang.String' to required type 'java.util.Date * @param binder * @param request */ @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // CustomDateEditor为自定义日期编辑器 } }
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dao.UserMapper"> <!-- resultType="User"因为在mybatis-config.xml 设置了别名,所有可以直接使用User 否则全路径com.entity.User <typeAliases> <typeAlias type="com.entity.User" alias="User" /> </typeAliases> --> <select id="select" resultType="User"> SELECT * FROM USER; </select> </mapper>
list.jsp页面
<tbody> <tr> <c:forEach items="${userlist}" var="user"> <td>${user.id }</td> <td>${user.name } </td> <td>${user.sex }</td> <td> <mfs:formatDate value="${user.birthday }" pattern="yyyy-MM-dd"/> </td> <td> <button type="button" class="layui-btn layui-btn-sm test2" > <i class="layui-icon"></i> </button> </td> <td> <button type="button" class="layui-btn layui-btn-sm layui-btn-del "> <i class="layui-icon"></i> </button> </td> </tr> </c:forEach> </tbody>
mysql中的user表
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(12) | YES | | NULL | |
| sex | varchar(10) | YES | | NULL | |
| age | int(5) | YES | | NULL | |
| birthday | date | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
哇!又赚了一天人民币
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库