SpringMVC第三天

该文档是:SpringMVC框架学习...

博客连接:https://www.loveuluo.cn

日期:2021-01-09

1. 搭建整合环境

1.1 整合的思路

整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式

(1)先搭建整合的环境

(2)先把Spring的配置搭建完成

(3)再使用Spring整合SpringMVC框架

(4)最后使用Spring整合MyBatis框架

01

1.2 创建数据库和表结构

image-20210110121632772

sql语句:

create database ssm;
use ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);

1.3 引入依赖

pom.xml:

<groupId>com.Luo</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</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>
  <!-- spring -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.8</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <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.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
    <scope>compile</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>
  <!-- log start -->
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <!-- log end -->
  <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>
    <type>jar</type>
    <scope>compile</scope>
  </dependency>
</dependencies>
<build>
  <finalName>ssm</finalName>
  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
          <showWarnings>true</showWarnings>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>

1.4 搭建三层架构

(1)Account实体类:

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;
}

(2)AccountDao接口:

public interface AccountDao {
    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAll();

    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
}

(3)AccountService和实现类:

接口:

public interface AccountService {
    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAll();

    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
}

实现类:

public class AccountServiceImpl implements AccountService {
    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户...");
        return null;
    }

    @Override
    public void saveAccount(Account account) {

    }
}

(4)AccountController控制器:

public class AccountController {
}

(5)最终视图:

image-20210109192332284

2. Spring框架代码的编写

做整合,得先保证每个框架都能单独使用,我们的方向是用spring去整合其它框架,先把spring框架的环境搭建完成,再整合别的框架。

搭建和测试Spring的开发环境:

(1)在resources目录下创建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,controller交给SpringMVC框架去处理-->
        <context:component-scan base-package="com.Luo">
            <!--配置哪些注解不扫描-->
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
        </context:component-scan>
    
</beans>

(2)在AccountService实现类上加上注解:

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户...");
        return null;
    }

    @Override
    public void saveAccount(Account account) {

    }
}

(3)在test包下创建TestSpring测试一下:

public class testSpring {
    @Test
    public void run1(){
        //加载配置文件
        ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //获取对象
        AccountService service = context.getBean("accountService", AccountService.class);
        //调用方法
        service.findAll();
    }
}

查询结果:

image-20210109195144447

3. Spring整合SpringMVC框架

3.1 搭建和测试SpringMVC的开发环境

(1)在web.xml中配置DispatcherServlet前端控制器和解决中文乱码的过滤器:

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--配置前端控制器-->
  <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>

(2)创建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">

    <!--开启注解扫描,只扫描Controller注解-->
    <context:component-scan base-package="com.Luo">
        <!--配置只扫描这些注解-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

    <!--配置视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- JSP文件所在的目录 -->
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <!-- 文件的后缀名 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 设置静态资源不过滤 -->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!-- 开启对SpringMVC注解的支持 -->
    <mvc:annotation-driven />

</beans>

(3)编写AccountController类:

@Controller
@RequestMapping("account")
public class AccountController {

    @RequestMapping("findAll")
    public String findAll(){
        System.out.println("表现层:查询所有账户信息...");
        return "list";
    }
}

(4)测试SpringMVC的框架搭建是否成功:

发起请求的jsp页面:

<body>
    <a href="account/findAll">查询所有</a>
</body>

跳转的list.jsp页面:

<body>
    <h3>查询所有账户信息成功</h3>
</body>

测试结果:

image-20210109201055237

image-20210109201448332

3.2 Spring整合SpringMVC的框架

(1)分析如何让spring配置文件被加载:

image-20210109233420455

(2)在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(该监听器默认只能加载WEB-INF目录下的applicationContext.xml的配置文件,可以设置配置文件路径):

<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
<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>

(3)监听器设置好后,启动服务器的时候就可以把spring的配置文件给加载,springmvc也加载了,等于service和Controller两个类全部都放到容器中了。这样就可以依赖注入了,Controller类:

@Controller
@RequestMapping("account")
public class AccountController {

    @Autowired
    private AccountService service;

    @RequestMapping("findAll")
    public String findAll(){
        System.out.println("表现层:查询所有账户信息...");
        service.findAll();
        return "list";
    }
}

输出结果:

image-20210109235041741

4. Spring整合MyBatis框架

3.1 搭建和测试MyBatis的环境

(1)在resources目录下配置mybatis核心配置文件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:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 使用的是注解 -->
    <mappers>
        <!-- <mapper class="com.Luo.dao.AccountDao"/> -->
        <!-- 该包下所有的dao接口都可以使用 -->
        <package name="com.Luo.dao"/>
    </mappers>
</configuration>

(2)编写UserDao接口:

public interface AccountDao {
    /**
     * 查询所有账户
     * @return
     */
    @Select("SELECT * FROM account")
    List<Account> findAll();

    /**
     * 保存账户
     * @param account
     */
    @Insert("INSERT INTO account(name,money) VALUES(#{name},#{money})")
    void saveAccount(Account account);
}

(3)测试一下Mybatis框架单独是否可用:

public class TestMyBatis {
    @Test
    public void run1() throws IOException {
        // 加载配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        // 创建SqlSession对象
        SqlSession sqlSession = build.openSession();
        // 获取到代理对象
        AccountDao dao = sqlSession.getMapper(AccountDao.class);
        // 查询所有数据
        List<Account> accounts = dao.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
        // 关闭资源
        sqlSession.close();
        resourceAsStream.close();
    }
}

测试结果:

image-20210110121653257

3.2 Spring整合MyBatis框架

(1)目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中,mybatis核心配置文件SqlMapConfig.xml可以删除了:

SqlSession全部由IOC容器来帮你创建。有工厂可以帮你创建SqlSession,有SqlSession可以帮你创建代理对象,可以把代理对象存到IOC容器中去,可以进行依赖注入了!

<?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,controller交给SpringMVC框架去处理-->
        <context:component-scan base-package="com.Luo">
            <!--配置哪些注解不扫描-->
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
        </context:component-scan>

        <!--Spring整合mybatis框架-->
        <!--配置连接池-->
        <bean id="dateSource" 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="123456"/>
        </bean>

        <!--配置SqlSessionFactory工厂-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!--根据连接池就能创建出SqlSessionFactory工厂-->
            <property name="dataSource" ref="dateSource"></property>
        </bean>

        <!--配置AccountDao接口所在包-->
        <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.Luo.dao"></property>
        </bean>
</beans>

(2)在AccountDao接口上加上注解:

@Repository
public interface AccountDao {
    /**
     * 查询所有账户
     * @return
     */
    @Select("SELECT * FROM account")
    List<Account> findAll();

    /**
     * 保存账户
     * @param account
     */
    @Insert("INSERT INTO account(name,money) VALUES(#{name},#{money})")
    void saveAccount(Account account);
}

(3)修改AccountServiceImpl类:

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao dao;

    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户...");
        return dao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层:保存用户...");
        dao.saveAccount(account);
    }
}

3.3 测试查询所有功能

(1)AccountController类:

@Controller
@RequestMapping("account")
public class AccountController {

    @Autowired
    private AccountService service;

    @RequestMapping("findAll")
    public String findAll(Model model){
        System.out.println("表现层:查询所有账户信息...");
        //用service查询所有
        List<Account> accounts = service.findAll();
        //把查出来的集合放到requset域中
        model.addAttribute("accounts",accounts);
        //根据视图解析器转发到list.jsp页面
        return "list";
    }
}

(2)发起请求的jsp页面:

<body>
    <a href="account/findAll">查询所有</a>
</body>

(3)要跳转的jsp页面:

<body>
<h3>查询所有账户信息成功</h3>
    <%--items相当于要遍历的,var代表里边的每个属性--%>
    <c:forEach items="${accounts}" var="account">
        ${account.id}
        ${account.name}
        ${account.money}
    </c:forEach>
</body>

页面结果:

image-20210110131436677

3.4 测试保存功能(配置Spring的声明式事务管理)

(1)在applicationContext.xml中配置声明式事务管理:

<!--配置Spring框架声明式事务管理-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dateSource"></property>
</bean>

<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
     <tx:attributes>
         <!--find打头的:方法都设为只读-->
        <tx:method name="find*" read-only="true"/>
         <!--除了find打头:可以设置属性例如隔离级别等等-->
        <tx:method name="*" isolation="DEFAULT"/>
    </tx:attributes>
</tx:advice>

<!--配置aop增强-->
<aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.Luo.service.impl.*ServiceImpl.*(..))"/>
</aop:config>

(2)AccountController类:

@RequestMapping("save")
public void save(Account account, HttpServletResponse response, HttpServletRequest request) throws IOException {
    System.out.println("表现层:查询所有账户信息...");
    //用service保存用户
    service.saveAccount(account);
    //重定向到 查询所有
    response.sendRedirect(request.getContextPath()+"/account/findAll");
    //防止代码再执行下去
    return;
}

(3)jsp页面:

<form action="account/save" method="post">
    用户名:<input type="text" name="name">
    金额:<input type="text" name="money">
    <input type="submit" value="提交">
</form>

执行结果:

image-20210110142525643

image-20210110142538646

最后修改:2021 年 01 月 21 日 04 : 36 PM
如果觉得我的文章对你有用,请随意赞赏