SSM整合笔记
整合Spring
-
编写xml配置文件,开启注解扫描(指定Controller注解不扫描)
<!--开启注解扫描,只处理service和dao,controller不需要Spring框架处理--> <context:component-scan base-package="cn.itcast"> <!--配置哪些不扫描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
-
在业务层的实现类上编写Spring注解,如:
@Service("accountService") public class AccountServiceImpl implements AccountService
-
Spring整合完成,测试一下(非必须):
@Test public void run1(){ ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); AccountService as = (AccountService) ac.getBean("accountService"); as.findAll(); }
整合SpringMVC
-
在web.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>
-
编写springmvc.xml配置文件,内容包括
1. 开启注解扫描,只扫描Controller注解 2. 配置视图解析器对象 3. 过滤静态资源 4. 开启SpringMVC注解的支持 <!--开启注解扫描,只扫描Controller注解--> <context:component-scan base-package="cn.itcast"> <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 name="suffix" value=".jsp"/> </bean> <!--过滤静态资源--> <mvc:resources mapping="/css/**" location="/css/"/> <mvc:resources mapping="/images/**" location="/images/"/> <mvc:resources mapping="/js/**" location="/js/"/> <!--开启SpringMVC注解的支持--> <mvc:annotation-driven/>
-
编写web层业务逻辑
@Controller @RequestMapping("/account") public class AccountController { @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层:查询所有账户》。。"); return "list"; } } //在index.xml中跳转进行测试:<a href="account/findAll">测试</a>
Spring和SpringMVC两者的整合
》我们知道,在web.xml中前端控制器中加载了spingmvc.xml,但是spring的配置文件还没有加载
》所以,需要在web.xml中配置Spring监听器,去加载applicationContext.xml
-
在web.xml配置文件中配置Spring的监听器:
<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件,通过context-param配置正确的路径--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
-
在web层通过依赖注入,将service层对象注入:
@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; //依赖注入 @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层:查询所有账户》。。"); //调用service层方法 accountService.findAll(); return "list"; } }
mybatis
-
使用注解编写dao层接口的sql语句
public interface AccountDao { //查询所有 @Select("select * from account") List<Account> findAll(); //保存账户信息 @Insert("insert into account (name,money) values (#{name},#{money})") void saveAccount(Account account); }
-
编写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> <!--配置环境--> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--引入映射配置文件,这里没有配置文件,使用dao类路径--> <mappers> <!--<mapper resource="xxx.xml"/> 资源配置文件--> <!--<mapper class="cn.itcast.dao.AccountDao"/> 单独指定某个类文件--> <!--使用package指定包名,包里所有的接口都会被扫描到--> <package name="cn.itcast.dao"/> </mappers> </configuration>
-
编写测试类(非必须)
public class TestMybatis { @Test public void testMybatis() throws Exception { //加载配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //创建SqlSessionFactory对象 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession对象 SqlSession sqlSession = factory.openSession(); //获取代理对象 AccountDao dao = sqlSession.getMapper(AccountDao.class); //查询所有数据 List<Account> list = dao.findAll(); for (Account account : list) { System.out.println(account); } //关闭资源 sqlSession.close(); in.close(); } }
整合mybatis
思路:现在需要将获取到的代理对象,存入容器中,在service中获取到dao层的代理对象,调用dao层代理对象的方法,如何操作呢?
答案:在业务层service的配置文件applicationContext.xml中配置
-
编写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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--开启注解扫描,只处理service和dao,controller不需要Spring框架处理--> <context:component-scan base-package="cn.itcast"> <!--配置哪些不扫描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--整合mybatis框架--> <!--配置连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!--配置SqlSessionFactory工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--配置连接池--> <property name="dataSource" ref="dataSource"/> </bean> <!--配置AccountDao接口所在的包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.itcast.dao"/> </bean> </beans>
-
此时,之前编写的SqlMapConfig.xml就没有用处了,可以删掉
-
在service层注入dao代理对象
@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); //这里没有添加事务,并不会真的保存到数据库 } }
-
整合完成,此时我们在web层可以将数据,转发到页面中去(通过Model)
@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层:查询所有账户》。。"); //调用service层方法 List<Account> list = accountService.findAll(); model.addAttribute("list",list); return "list"; } } //页面展示代码 <%@ 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> <h3>查询所有账户...</h3> <%--${list}--%> <c:forEach items="${list}" var="account"> ${account.name} </c:forEach> </body> </html>
整合mybatis框架-事务管理
-
在applicationContext.xml中配置事务管理
<!--配置Spring框架声明式事务管理--> <!--1. 配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--2. 配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!--3. 配置AOP增强--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/> </aop:config> //测试 前端页面 <h3>测试保存(事务管理)</h3> <form action="account/saveAccount" method="post"> 姓名:<input type="text" name="name"/><br/> 金额:<input type="text" name="money"/><br/> <input type="submit" value="保存"/><br/> </form> //web层 @RequestMapping("/saveAccount") public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("表现层:保存账户》。。"); //调用service层方法 accountService.saveAccount(account); response.sendRedirect(request.getContextPath()+"/account/findAll"); //重定向 return; }
网友评论