SpringMvc整合笔记

SSM整合步骤

  1. 导入依赖

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <!-- mybatis-spring:整合依赖 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.12</version>
    </dependency>
    <!-- spring-jdbc:使用的是spring-jdbc的事务 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- spring-tx:事务管理器 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.18.RELEASE</version>
    </dependency>
    
  2. 编写配置文件

    • web.xml

      <web-app>
        <display-name>Archetype Created Web Application</display-name>
        <filter>
          <filter-name>encodingFilter</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>encodingFilter</filter-name>
          <url-pattern>/*</url-pattern>
        </filter-mapping>
        <servlet>
          <servlet-name>dispatcherServlet</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mybatis.xml</param-value>
          </init-param>
        </servlet>
        <servlet-mapping>
          <servlet-name>dispatcherServlet</servlet-name>
          <url-pattern>/</url-pattern>
        </servlet-mapping>
      </web-app>
      
    • spring-mybatis.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"
             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">
      
          <!--扫描所有的包-->
          <context:component-scan base-package="com.qianfeng"></context:component-scan>
          <!--导入spring-mvc.xml-->
          <import resource="classpath:spring-mvc.xml"/>
          <!--配置druid数据源-->
          <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
              <property name="url" value="jdbc:mysql://localhost:3306/db_mybatis_test"></property>
              <property name="username" value="root"></property>
              <property name="password" value="root"></property>
          </bean>
          <!--配置sqlsessionnFactory-->
          <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="dataSource"></property>
              <!--配置mapper文件所在位置-->
              <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
              <!--单独的mybatis配置文件用来补充我mybatis没配的东西-->
              <property name="configLocation" value="classpath:mybatis-config.xml"></property>
          </bean>
          <!--mapper扫描配置器:配置dao接口所在的包,会帮助我们自动生成对应虚拟实现类,
          建立实现类与对应的mapper文件的联系-->
          <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="basePackage" value="com.qianfeng.dao"></property>
              <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
          </bean>
          <!--配置事务管理器:spring-jdbc的事务-->
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource"></property>
          </bean>
          <!--配置注解驱动式  声明事务管理-->
          <tx:annotation-driven transaction-manager="transactionManager"/>
      </beans>
      
    • spring-mvc.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: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.qianfeng.controller"></context:component-scan>
          <!--静态资源处理器;释放静态资源-->
          <mvc:default-servlet-handler/>
          <!--
              注解驱动标签:将前端请求与后端controller中的映射匹配
          -->
          <mvc:annotation-driven>
              <mvc:message-converters register-defaults="false">
                  <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                      <property name="supportedMediaTypes">
                          <list>
                              <value>application/json;charset=utf-8</value>
                              <!--为了避免低版本ie浏览器获取json数据时出现文件下载的情况-->
                              <value>text/html;charset=utf-8</value>
                          </list>
                      </property>
                      <!--解决当属性为null时,如何返回数据-->
                      <property name="features">
                          <list>
                              <value>WriteNullNumberAsZero</value>
                              <value>WriteNullStringAsEmpty</value>
                              <value>WriteNullListAsEmpty</value>
                          </list>
                      </property>
                  </bean>
              </mvc:message-converters>
          </mvc:annotation-driven>
      
      </beans>
      
    • mybatis-config,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>
          <!--打印执行的SQL语句-->
          <settings>
              <setting name="logImpl" value="STDOUT_LOGGING"/>
          </settings>
          <typeAliases>
              <!--实体类别名-->
              <package name="com.qianfeng.pojo"></package>
          </typeAliases>
      </configuration>
      
    • 测试查询所有用户

      /**
           * 查询用户列表
           */
      @RequestMapping("/list")
      @ResponseBody
      public List<User> getUserList(){
          List<User> userList = userService.getUserList();
          return userList;
      }
      
    • 添加用户

      -------------------------UserController------------------------------
      @RequestMapping("/add")
      @ResponseBody
      public String add(){
          User user = new User();
          user.setUserName("杜兰特");
          userService.addUser(user);
          return "success";
      }
      -------------------------UserServiceImpl------------------------------
      @Service
      @Transactional    //加了此注解,在同一个事务中运行功能时,如果某一个出现问题,会自动回滚
      public class UserServiceImpl implements UserService {
      
          @Resource
          private UserDao userDao;
          
          /**
           * 测试事务自动回滚
           * @param user
           */
          @Override
          public void addUser(User user) {
              //张三给李四转账1000:
              userDao.addUser(user);//张三扣1000
              int num = 1/0;
              userDao.addUser(user);//李四加1000
          }
      }
      

      添加@Transactional在增删改出错时可以自动回滚⭐⭐⭐⭐⭐⭐⭐

Thymeleaf

  1. 前言:如果你只会ajax的话,不建议你直接用html,因为ajax拿到的数据给html标签赋值的时候非常不方便。我们之前学过jsp,可以直接把后端的数据放在标签外面进行for循环、if判断等等。但是jsp有点儿老了,所以我们使用更好的thymeleaf替换jsp进行页面数据显示。

  2. thymeleaf相对jsp的优势:jsp对于前端不友好,有大量的java代码,jsp不能单独运行,必须依赖于后端服务器,前端测试也比较麻烦。所以我们使用thymeleaf,都是html页面。是一种比jsp更好的模板引擎,也是springboot官方推荐的模板引擎。

  3. 步骤

    <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>3.0.11.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4 -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>3.0.9.RELEASE</version>
    </dependency>
    
  4. spring-mvc.xml

    <!--模板解析器-->
    <bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".html"></property>
        <property name="characterEncoding" value="utf-8"></property>
        <property name="templateMode" value="HTML5"></property>
        <property name="cacheable" value="false"></property>
    </bean>
    <!--模板引擎-->
    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"></property>
    </bean>
    <!--视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="characterEncoding" value="utf-8"></property>
        <property name="templateEngine" ref="templateEngine"></property>
    </bean>
    

    这里是SSM和Thymeleaf配置的代码,不是springboot⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

  5. 测试

    @Controller
    public class ThymeleafController {
    
        /**
         * 测试thymeleaf页面传值
         */
        @RequestMapping("/test_thymeleaf")
        public String test(Model model){
            String msg = "嘻嘻";
            model.addAttribute("msg1111",msg);
            return "userlist";
        }
    }
    
    
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <!--
            th:text:值在标签内部文本显示的使用th:text赋值
        -->
        <h1 th:text="${msg1111}">哈哈</h1>
        <input  type="text" th:value="${msg1111}">
    </body>
    </html>
    
posted @ 2021-08-05 09:07  慢慢呀  阅读(46)  评论(0)    收藏  举报