Java框架-SpringMVC统一异常处理、ssm框架整合

1. SpringMVC中异常处理

1.1 各层处理异常原则即实现方法

1.1.1 各层处理异常原则

dao:不处理,抛异常;

service:不处理,抛异常;

controller/servlet:必须处理,否则错误信息将直接在浏览器显示给用户看。

1.1.2 异常处理实现方法

  • 方法1:控制层的方法中写try…catch。异常处理信息一多,控制层方法就会十分冗余,而且每个控制器都有可能有异常,即每个控制器都要写;
  • 方法2:使用异常过滤器,拦截所有请求。在过滤器中对异常进行处理;
  • 方法3:使用框架自带的异常处理机制。

1.2 异常处理

  • 使用异常处理器统一对dao、service、controller的异常进行处理
  • SpringMVC提供了HandlerExceptionResolver异常处理器接口

1.3 SpringMVC异常处理实现

1.3.1 环境准备

1.3.1.1 创建项目、添加依赖

<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.0modelVersion>

    <groupId>com.azuregroupId>
    <artifactId>day57projects_SpringMVC_ssmartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.0version>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        
    dependencies>
project>
1.3.1.2 springMVC.xml配置

<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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="com.azure">context:component-scan>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/">property>
        <property name="suffix" value=".jsp">property>
    bean>
    
    <mvc:annotation-driven>mvc:annotation-driven>
    
    <mvc:resources mapping="/pages/**" location="/pages/">mvc:resources>
    <mvc:resources mapping="/js/**" location="/pages/">mvc:resources>

beans>
1.3.1.3 web.xml配置

<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_2_5.xsd"
   version="2.5">

   
   <servlet>
      <servlet-name>dispatcherServletservlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
      
      <init-param>
         <param-name>contextConfigLocationparam-name>
         <param-value>classpath:springMVC.xmlparam-value>
      init-param>
      <load-on-startup>1load-on-startup>
   servlet>
   
   <servlet-mapping>
      <servlet-name>dispatcherServletservlet-name>
      <url-pattern>/url-pattern>
   servlet-mapping>
web-app>

1.3.2 控制类模拟异常

@Controller
public class ExpController {

    /**
     * 模拟异常
     */
    @RequestMapping("/save")
    public String save(){
        int i = 1/0;
        return "success";
    }
}

1.3.3 使用方法1手动捕获异常

1.3.3.1 error.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    error


出错啦~系统繁忙~

1.3.3.2 控制类调整
@Controller
public class ExpController {

    /**
     * 模拟异常
     */
    @RequestMapping("/save")
    public String save(ModelMap modelMap){
        try {
            int i = 1/0;
        } catch (Exception e) {
            e.printStackTrace();
            //将异常信息发送给error.jsp页面,error页面获取并显示错误信息
            modelMap.addAttribute("errorMsg","出错啦~系统繁忙~");
            return "error";
        }
        return "success";
    }
}
1.3.3.3 总结
  • 每个请求方法都要写异常代码,都要手动捕获异常处理,效率低。

1.3.4 使用方法3自定义异常处理器

  • 使用SpringMVC提供的异常处理接口(HandlerExceptionResolver)实现类
1.3.4.1 设置自定义异常处理器
public class CustomerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //1.打印异常信息
        e.printStackTrace();
        //2.保存异常信息并跳转到错误页面
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg", "出错啦~系统繁忙~");
        mv.setViewName("error");
        return mv;
    }
}
1.3.4.2 springMVC.xml配置异常处理器
  • 除了在springMVC.xml配置,也可以在自定义异常处理器类上使用@Component注解创建对象

<bean class="com.azure._01exception.CustomerExceptionResolver">
1.3.4.3 测试控制类
@Controller
public class HERController {
    /**
     * 模拟异常
     */
    @RequestMapping("/saved")
    public String saved(ModelMap modelMap) {
        int i = 1 / 0;
        return "success";
    }
}

2. SpringMVC中的拦截器

2.1 拦截器的作用

  • SpringMVC的处理器拦截类似于 的处理器拦截类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。
  • 拦截器链:多个拦截器按一定的顺序连接成链,访问被拦截方法或字段时,按定义的顺序调用拦截器

2.1.1 拦截器与过滤器的异同

相同点:

  1. 都可以对请求进行拦截:过滤器拦截所有请求、拦截器只拦截控制器请求;
  2. 请求处理前可以做一些前期操作,在请求处理完毕后,也可以做后续的操作。

区别:

  1. 过滤器是servlet规范中的一部分,任何java web工程都可以使用;而拦截器只能在SpringMVC框架的工程内使用。
  2. 过滤器可以通过在url-pattern属性中配置/*实现拦截所有访问请求;而拦截器只会拦截访问控制器方法的请求,不会对网页资源(html、jsp等)进行拦截。
  3. 过滤器应用范围更广,拦截器只应用在SpringMVC项目。

2.2 自定义拦截器使用

2.2.1 编写控制器

@Controller
public class HIDemoController {
    //构造函数
    public HIDemo1Controller(){
        System.out.println("1.实例UserController");
    }

    @RequestMapping("/interceptor")
    public ModelAndView testInterceptor(){  //存入数据并跳转页面
        System.out.println("4.执行控制器的testInterceptor方法");
        ModelAndView mv = new ModelAndView();
        mv.addObject("username", "JoJo");
        mv.setViewName("success");
        return mv;
    }
}

2.2.2 编写拦截器类实现HandlerInterceptor接口

  • 除了在springMVC.xml配置,也可以在自定义异常处理器类上使用@Component注解创建对象
public class HandlerInterceptor1 implements HandlerInterceptor {

    //构造函数
    public HandlerInterceptor1(){
        System.out.println("2.实例拦截器1号");
    }

    /**
     * 编写请求拦截方法,包含业务逻辑控制校验代码
     *  返回值为true:放行,进入拦截器链的下一个拦截器,如果是最后一个,则执行控制器的方法
     *  返回值为false:不放行,请求不被处理
     */

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("3.拦截器1号的preHandle方法已执行");
        return true;
    }

    /**
     * 编写响应拦截方法,在请求处理完返回响应前调用
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("5.拦截器1号的postHandle方法已执行");
    }

    /**
     * 编辑资源清理方法,在preHandle返回true就会被调用
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("6.拦截器1号的afterCompletion方法已执行");
    }
}

2.2.3 springMVC.xml配置拦截器


<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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="com.azure">context:component-scan>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/">property>
        <property name="suffix" value=".jsp">property>
    bean>
    
    <mvc:annotation-driven>mvc:annotation-driven>

    

    

    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            
            <bean class="com.azure._02Interceptor.HandlerInterceptor1">bean>
        mvc:interceptor>
    mvc:interceptors>
beans>
  • 注意,如果拦截器使用@Component注解,那么在springMVC.xml中就不用,而是使用

2.3 多拦截器使用

2.3.1 新增一个拦截器2

@Component
public class HandlerInterceptor2 implements HandlerInterceptor {

    //构造函数
    public HandlerInterceptor2(){
        System.out.println("实例拦截器2号");
    }

    /**
     * 编写请求拦截方法,包含业务逻辑控制校验代码
     *  返回值为true:放行,进入拦截器链的下一个拦截器,如果是最后一个,则执行控制器的方法
     *  返回值为false:不放行,请求不被处理
     */

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器2号的preHandle方法已执行");
        return true;
    }

    /**
     * 编写响应拦截方法,在请求处理完返回响应前调用
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器2号的postHandle方法已执行");
    }

    /**
     * 编辑资源清理方法,在preHandle返回true就会被调用
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器2号的afterCompletion方法已执行");
    }
}

2.3.2 springMVC.xml配置拦截器2


<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        
        <bean class="com.azure._02Interceptor.HandlerInterceptor1">bean>
    mvc:interceptor>
    
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <ref bean="handlerInterceptor2">ref>
    mvc:interceptor>
mvc:interceptors>

2.3.3 运行结果

2.3.3.1 服务器启动

在这里插入图片描述

2.3.3.2 请求访问

Java框架-SpringMVC统一异常处理、ssm框架整合_第1张图片

3. SSM整合(重点*3)

3.1 整合原则

  • xml和注解组合使用

  • 配置方式的选择:

    1. Spring:自己编写的类使用注解,jar包的类用xml,事务用xml;
    2. SpringMVC:控制器配置用注解,使用xml有:扫描包、视图解析器开启、注解支持开启、静态资源不过滤等;
    3. mybatis:SqlMapConfig.xml整合到spring配置文件中,接口映射使用注解配置
  • Spring整合Mybatis关键点:把Mybatis的SqlSessionFactory对象的创建交给Spring管理。

3.2 整合步骤

  1. 构建单独Spring环境
  2. 构建单独SpringMVC环境
  3. Spring与SpringMVC整合
  4. 构建单独Mybatis环境
  5. Spring整合Mybatis
  6. ssm 整合,页面,测试
  • 为确保整合成功,每步都会单独测试检查是否有误

3.3 构建Spring环境

3.3.1 创建项目,添加依赖



<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.0modelVersion>
    <groupId>com.azuregroupId>
    <artifactId>day57projects_SSMartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>warpackaging>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.8.9version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.1version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.30version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.10version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.5version>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.0version>
        dependency>
        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
    dependencies>
project>

3.3.2 spring配置文件

  • 创建applicationContext.xml文件

<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"
       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">

    
    <context:component-scan base-package="com.azure.service">context:component-scan>

beans>

3.3.3 创建实体类

public class Account {
    private int accountId;
    private int uid;
    private double money;
    ...
}

3.3.4 service层

3.3.4.1 service层接口
public interface IAccountService {
    /*实现查询功能*/
    List<Account> findAll();
}
3.3.4.2 service接口实现类
@Service
public class AccountServiceImpl implements IAccountService {
    @Override
    public List<Account> findAll() {
        System.out.println("测试。。。调用service的findAll查询全部账户");
        return null;
    }
}

3.3.5 测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")   //指定容器类
public class TestDemo01 {
    //注入service
    @Autowired
    private IAccountService accountService;

    @Test
    public void find(){
        accountService.findAll();
    }
}

3.4 构建单独SpringMVC环境

3.4.1 配置web.xml


<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_2_5.xsd"
   version="2.5">

   
   <servlet>
      <servlet-name>DispatcherServletservlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
      
      <init-param>
         <param-name>contextConfigLocationparam-name>
         <param-value>classpath:springMVC.xmlparam-value>
      init-param>
      <load-on-startup>1load-on-startup>
   servlet>
   
   <servlet-mapping>
      <servlet-name>DispatcherServletservlet-name>
      <url-pattern>/url-pattern>
   servlet-mapping>

web-app>

3.4.2 配置springMVC.xml


<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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="com.azure.controller"/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/">property>
        <property name="suffix" value=".jsp">property>
    bean>
    
    <mvc:annotation-driven>mvc:annotation-driven>

beans>

3.4.3 控制类

@Controller
public class AccountController {

    @RequestMapping("/findAll")
    public ModelAndView findAll(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("name", "JoJo");
        mv.setViewName("success");
        return mv;
    }
}

3.4.4 测试页面

  • 增加success.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    success


success~~


3.5 Spring整合SpringMVC

  • 思路:
    • 1、SpringMVC负责controller层,需要注入service
    • 2、在web.xml中加载applicationContext.xml配置

3.5.1 控制器类注入service

@Controller
@RequestMapping("/account")     //设置第一级目录,方便区分findAll方法
public class AccountController {

    //注入service
    @Autowired
    private IAccountService accountService;

    @RequestMapping("/findAll")
    public ModelAndView findAll(HttpServletRequest request) {
        List<Account> list = accountService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.addObject("list", list);
        mv.setViewName("success");
        return mv;
    }
}

3.5.2 在web.xml配置ServletContext的监听器加载applicationContext.xml

  • 服务器启动的时候会创建ServletContext,通过监听ServletContext,在创建ServletContext时加载配置,就能实现服务器启动后加载配置。

<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

<context-param>
   <param-name>contextConfigLocationparam-name>
   <param-value>classpath:applicationContext.xmlparam-value>
context-param>

3.6 配置单独mybatis环境

3.6.1 配置sqlMapConfig.xml



<configuration>
    
    <properties resource="jdbc.properties"/>
    
    <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>
        <package name="com.azure.dao">package>
    mappers>
configuration>

3.6.2 dao层

public interface IAccountDao {
    /**
     * 查询功能
     */
    @Select("select * from account")    //使用注解方式实现查询
    List<Account> findAll();
}

3.6.3 测试类

public class TestDemo02 {

    @Test
    public void findAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(is);
        SqlSession session = factory.openSession();
        //创建Dao实现类
        IAccountDao accountDao = session.getMapper(IAccountDao.class);
        List<Account> list = accountDao.findAll();
        System.out.println(list);
        session.close();
        is.close();
    }
}

3.7 Spring整合mybatis

思路:

  1. 将SqlMapConfig.xml整合到applicationContext.xml中,包括
    • 加载数据库配置文件
    • 配置数据库连接池
  2. 增加Spring声明式事务;
  3. 将SqlSessionFactoryBean交由Spring创建,配置SqlSessionFactoryBean
  4. 开启dao接口扫描
  5. service注入dao

3.7.1 applicationContext.xml整合SqlMapConfig.xml


<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/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">

    
    <context:component-scan base-package="com.azure.service">context:component-scan>

    
    <context:property-placeholder location="classpath:jdbc.properties"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>

    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.azure.dao"/>
    bean>

    
    
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>
    
    <tx:advice id="txadvice" transaction-manager="txManager">
        
        <tx:attributes>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        
        <aop:pointcut id="pt" expression="execution(* com.azure.service.*.*(..))">aop:pointcut>
    aop:config>

beans>

3.7.2 service注入dao

@Service
public class AccountServiceImpl implements IAccountService {
    //注入Dao
    @Autowired
    private IAccountDao accountDao;
    
    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}

3.7.3 测试

分两部分:

  1. 测试service在整合后是否有误;
  2. 从controller开始走完整的流程,看最终页面是否正常返回数据
3.7.3.1 service测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")   //指定容器类
public class TestDemo03 {
    //注入service
    @Autowired
    private IAccountService accountService;

    @Test
    public void find(){
        List<Account> accounts = accountService.findAll();
        System.out.println(accounts);
    }
}
3.7.3.2 启动服务器测试
  • 配置返回的页面,将获取的结果打印

success.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    success


查询所有账户

success~~

<%--遍历结果获取每个元素并打印--%> <%--varStatus相当于遍历的i--%>
序号 账号编号 用户编号 账户余额
${num.count} ${account.accountId} ${account.uid} ${account.money}

你可能感兴趣的:(spring)