ssm(spring5.0.2.RELEASE-mybatis3.4.5)
1、项目结构
2、具体内容
2.1、maven依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="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"> <modelVersion>4.0.0</modelVersion> <groupId>com.ly.ssm</groupId> <artifactId>ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>13</maven.compiler.source> <maven.compiler.target>13</maven.compiler.target> <!--版本锁定--> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> </dependencies> <build> <finalName>ssm</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <!--解决IDEA maven变更后自动重置LanguageLevel和JavaCompiler版本的问题--> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
2.2、配置文件
2.2.1、springmvc配置文件:springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描注解白名单配置 1、若只想扫描Controller注解,仅仅增加扫描白名单没用,默认还会扫描到其它注解 2、若只想扫描白名单中的注解,需加上use-default-filters="false"配置 --> <!--配置注解扫描的包,springmvc只负责Controller注解的扫描--> <context:component-scan base-package="com.ly.ssm" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--配置视图解析器--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--开启springmvc注解驱动--> <mvc:annotation-driven/> </beans>
2.2.2、log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=info, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
2.2.3、jdbc.properties
jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/ssm jdbc.user = root jdbc.password = root
2.2.4、spring配置文件:applicationContext.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--jdbc资源文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置注解扫描包--> <context:component-scan base-package="com.ly.ssm"> <!--过滤掉Controller注解扫描,spring只负责业务层和dao层注解--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--配置SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--配置别名--> <property name="typeAliasesPackage" value="com.ly.ssm.domain"></property> </bean> <!--配置mappers所在的包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ly.ssm.dao"></property> </bean> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事务通知--> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <!--配置事务通知属性--> <tx:attributes> <tx:method name="find*" read-only="true" propagation="SUPPORTS"/> <tx:method name="*" propagation="REQUIRED"></tx:method> </tx:attributes> </tx:advice> <!--配置事务增强--> <aop:config> <aop:pointcut id="pc1" expression="execution(* com.ly.ssm.service.impl.*.*(..))"/> <aop:advisor advice-ref="transactionAdvice" pointcut-ref="pc1"></aop:advisor> </aop:config> </beans>
2.2.5、mapper配置文件:IAccountDao.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.ly.ssm.dao.IAccountDao"> <select id="findAll" resultType="Account"> select * from account </select> <insert id="saveAccount" parameterType="Account"> insert into account(name,money) values(#{name,jdbcType=VARCHAR},#{money,jdbcType=DECIMAL}) </insert> </mapper>
2.2.6、web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!--指定加载配置文件的位置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--解决post请求中文乱码--> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置spring监听器,默认只加载/WEB-INF/applicationContext.xml--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置springmvc前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--实例化时加载springmvc.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2.3、请求页面:index.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/2/29 Time: 21:39 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="findAll">findAll</a> <a href="saveAccount">saveAccount</a> </body> </html>
2.4、控制器:AccountController
package com.ly.ssm.controller; import com.ly.ssm.domain.Account; import com.ly.ssm.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @Controller public class AccountController { @Autowired private IAccountService accountService; @RequestMapping("/findAll") public String findAll(Model model) { System.out.println("AccountController---test"); List<Account> list = accountService.findAll(); model.addAttribute("list",list); return "success"; } @RequestMapping("/saveAccount") public String saveAccount(HttpServletResponse response) throws IOException { Account account = new Account(); account.setName("测试10"); account.setMoney(8000); accountService.saveAccount(account); //response.setCharacterEncoding("UTF-8"); //response.setContentType("text/html;charset=UTF-8"); //response.getWriter().print("保存成功!"); //转发 return "forward:findAll"; } }
2.5、响应页面:success.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/2/29 Time: 21:39 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%--引入jstl表达式--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h2>success</h2> <table> <tr> <th>id</th> <th>name</th> <th>money</th> </tr> <c:forEach items="${list}" var="item"> <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.money}</td> </tr> </c:forEach> </table> </body> </html>
2.6、实体类Account
package com.ly.ssm.domain; import java.io.Serializable; public class Account implements Serializable { private int id; private String name; private double money; public Account(){} public Account(String name,double money) { this.name = name; this.money = money; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
2.7、dao接口
package com.ly.ssm.dao; import com.ly.ssm.domain.Account; import java.util.List; public interface IAccountDao { public List<Account> findAll(); public void saveAccount(Account account); }
2.8、service接口和实现类
package com.ly.ssm.service; import com.ly.ssm.domain.Account; import java.util.List; public interface IAccountService { public List<Account> findAll(); public void saveAccount(Account account); }
package com.ly.ssm.service.impl; import com.ly.ssm.dao.IAccountDao; import com.ly.ssm.domain.Account; import com.ly.ssm.service.IAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("accountService") public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; @Override public List<Account> findAll() { System.out.println("AccountServiceImpl---findAll"); return accountDao.findAll(); } @Override public void saveAccount(Account account) { System.out.println("AccountServiceImpl---saveAccount"); accountDao.saveAccount(account); int i = 1/0; } }
3、总结
3.1、事务不生效
3.1.1、原因
3.1.1.1、Spring与SpringMVC属于父子容器关系。框架启动时先启动Spring容器,而后启动SpringMVC容器。子容器可以访问父容器中的Bean,而父容器不能访问子容器中的Bean
3.1.1.2、由于SpringMVC在扫描时扩大了扫描范围,装载了@Service标识的类的实例,从而导致Controller层在注入Service时,实际注入的时子容器中的Service实例
3.1.1.3、事务被配置在父容器中,Spring父容器在装载Service时会同时应用事务配置,而SpringMVC只是单纯加载Service的实例
3.1.2、解决方法,在给springmvc.xml配置注解扫描包增加白名单时,加上use-default-filters="false",只对配置的白名单扫描
<!-- 扫描注解白名单配置 1、若只想扫描Controller注解,仅仅增加扫描白名单没用,默认还会扫描到其它注解 2、若只想扫描白名单中的注解,需加上use-default-filters="false"配置 --> <!--配置注解扫描的包,springmvc只负责Controller注解的扫描--> <context:component-scan base-package="com.ly.ssm" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
相识是缘