Spring 整合 SpringMVC 的框架
目的:在controller中能成功的调用service对象中的方法。
第一步:配置监听器实现启动服务创建容器
在web.xml添加监听器:
<!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。 该监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 手动指定 spring 配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
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> <!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。 该监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 手动指定 spring 配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 --> <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> <!-- 启动服务器,创建该servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--解决中文乱码的过滤器--> <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> </web-app>
第二步:在controller中注入service对象,调用service对象的方法进行测试
package com.keafmd.controller; import com.keafmd.domain.Account; import com.keafmd.service.AccountService; 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Keafmd * * @ClassName: AccountController * @Description: 账户控制器 web * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:19 */ @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; /** * 查询所有 * @return */ @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层,查询所有账户信息。。。"); //调用service的方法 accountService.findAll(); return "list"; } }
运行结果:
控制台输出:
表现层,查询所有账户信息。。。 业务层,查询所有。。。
保证 MyBatis 框架在 web 工程中独立运行
第一步:在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件
SqlMapConfig.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> <!-- 配置连接数据库的信息 --> <properties resource="jdbcConfig.properties"></properties> <!-- 配置mybatis的环境 --> <environments default="mysql"> <environment id="mysql"> <!-- 配置事务管理 --> <transactionManager type="JDBC"></transactionManager> <dataSource type="pooled"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 指定映射文件位置 --> <mappers> <!--<mapper class="com.keafmd.dao.IAccountDao"/> <mapper class="com.keafmd.dao.IUserDao"/>--> <package name="com.keafmd.dao"/> </mappers> </configuration>
jdbcConfig.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.username=root jdbc.password=root
第二步:在AccountDao接口的方法上添加注解,编写SQL语句
package com.keafmd.dao; import com.keafmd.domain.Account; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; /** * Keafmd * * @ClassName: AccountDao * @Description: 账户dao接口 * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:05 */ public interface AccountDao { //查询所有账户 @Select("select * from account") public List<Account> findAll(); //保存账户 @Insert("insert into account(name,money) values(#{name},#{money})") public void saveAccount(Account account); }
第三步:编写测试的方法
TestMybatis:
package com.keafmd.test; import com.keafmd.dao.AccountDao; import com.keafmd.domain.Account; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.List; /** * Keafmd * * @ClassName: TestMybatis * @Description: 测试Mybatis * @author: 牛哄哄的柯南 * @date: 2021-02-18 16:37 */ public class TestMybatis { private InputStream in; private SqlSessionFactory factory; private SqlSession session; private AccountDao accountDao; @Before public void init() throws Exception{ //加载配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //创建SqlSessionFactory对象 factory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession对象 session = factory.openSession(); //获取到代理对象 accountDao = session.getMapper(AccountDao.class); } @After public void destory() throws Exception{ session.commit(); session.close(); in.close(); } /** * 查询所有 */ @Test public void run1(){ List<Account> accounts = accountDao.findAll(); for (Account account : accounts) { System.out.println(account); } } /** * 测试保存 */ @Test public void saveAccount(){ Account account = new Account(); account.setName("毛利小五郎"); account.setMoney(800.00); // account.setMoney(800d); accountDao.saveAccount(account); } }
运行run1():
Account{id=1, name='keafmd', money=9000.0} Account{id=2, name='小兰', money=8000.0} Account{id=3, name='新一', money=8000.0} Account{id=4, name='毛利小五郎', money=800.0} Account{id=5, name='怪盗基德', money=660.0} Account{id=6, name='某某', money=290.0} Process finished with exit code 0
Spring 整合 MyBatis 框架
整合思路:把 mybatis 配置文件(SqlMapConfig.xml)中内容配置到 spring 配置文件中同时,把 mybatis 配置文件的内容清掉。
第一步:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
把以下内容添加到applicationContext.xml配置文件中:
<!--Spring整合Mybatisl框架--> <!-- 配置C3P0的连接池对象 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql:///ssm"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置SqlSession的工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置扫描dao的包 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.keafmd.dao"/> </bean> <!--SqlMapConfig.xml和jdbcConfig.properties可以删除了-->
SqlMapConfig.xml和jdbcConfig.properties可以删除了。
第二步:在applicationContext.xml配置文件中配置 spring 的事务
把以下内容添加到applicationContext.xml配置文件中:
<!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置AOP增强 --> <aop:config> <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.keafmd.service.impl.*.*(..))"/>--> <!-- 配置切入点表达式 --> <aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/> <!-- 建立通知和切入点表达式的关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config>
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"> <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架 去管理 --> <context:component-scan base-package="com.keafmd"> <!-- 配置要忽略的注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--Spring整合Mybatisl框架--> <!-- 配置C3P0的连接池对象 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql:///ssm"/> <property name="user" value="root"/> <property name="password" value="18044229"/> </bean> <!-- 配置SqlSession的工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置扫描dao的包 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.keafmd.dao"/> </bean> <!--SqlMapConfig.xml和jdbcConfig.properties可以删除了--> <!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置AOP增强 --> <aop:config> <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.keafmd.service.impl.*.*(..))"/>--> <!-- 配置切入点表达式 --> <aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/> <!-- 建立通知和切入点表达式的关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config> </beans>
第三步:在AccountDao接口中添加@Repository注解
AccountDao:
package com.keafmd.dao; import com.keafmd.domain.Account; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; /** * Keafmd * * @ClassName: AccountDao * @Description: 账户dao接口 * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:05 */ @Repository public interface AccountDao { //查询所有账户 @Select("select * from account") public List<Account> findAll(); //保存账户 @Insert("insert into account(name,money) values(#{name},#{money})") public void saveAccount(Account account); }
第四步:在service中注入dao对象
AccountServiceImpl:
package com.keafmd.service.impl; import com.keafmd.dao.AccountDao; import com.keafmd.domain.Account; import com.keafmd.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Keafmd * * @ClassName: AccountServiceImpl * @Description: 账户的业务层实现类 * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:16 */ @Service("accountService") public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { System.out.println("业务层,查询所有。。。"); return accountDao.findAll(); } @Override public void saveAccount(Account account) { System.out.println("业务层,保存账户。。。"); accountDao.saveAccount(account); } }
第五步:修改 AccountController 代码
package com.keafmd.controller; import com.keafmd.domain.Account; import com.keafmd.service.AccountService; 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Keafmd * * @ClassName: AccountController * @Description: 账户控制器 web * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:19 */ @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; /** * 查询所有 * @param model * @return */ @RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层,查询所有账户信息。。。"); //调用service的方法 List<Account> list = accountService.findAll(); model.addAttribute("list",list); return "list"; } /** * 保存 * @param account * @param request * @param response * @throws IOException */ @RequestMapping("/save") public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { accountService.saveAccount(account); response.sendRedirect(request.getContextPath()+"/account/findAll"); return; } }
第五步:修改 list.jsp 代码,实现显示账户信息
<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/2/18 Time: 15:50 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h1>查询所有的账户</h1> <%--${list}--%> <c:forEach items="${list}" var="account"> ${account.name} ${account.money} </c:forEach> </body> </html>
第六步:测试查询
第七步:测试保存
修改index.jsp代码,添加测试保存的代码:
<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/2/17 Time: 23:20 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="account/findAll">测试查询</a> <h1>测试保存</h1> <form action="account/save" method="post"> 姓名:<input type="text" name="name" /><br/> 金额:<input type="text" name="money" /><br/> <input type="submit" value="保存"> </form> </body> </html>
修改 AccountController 代码,添加save方法:
package com.keafmd.controller; import com.keafmd.domain.Account; import com.keafmd.service.AccountService; 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Keafmd * * @ClassName: AccountController * @Description: 账户控制器 web * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:19 */ @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; /** * 查询所有 * @param model * @return */ @RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层,查询所有账户信息。。。"); //调用service的方法 List<Account> list = accountService.findAll(); model.addAttribute("list",list); return "list"; } /** * 保存 * @param account * @param request * @param response * @throws IOException */ @RequestMapping("/save") public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { accountService.saveAccount(account); response.sendRedirect(request.getContextPath()+"/account/findAll"); return; } }
测试结果:
以上就是SSM整合案例(超详细)的全部内容。