SpringMVC study notes -08 SSM framework integrated development

        SSM is to integrate SpringMVC+Spring+MyBatis for development. The most important thing is to integrate MyBatis into Spring, because SpringMVC is actually a part of Spring. There are two integration methods, one is based on XML configuration files, and the other is based on annotations.

Combine the integration thinking:

        After the SSM framework is built, the entire project will be executed according to the following structure:

        The core of SSM is the management of two containers. SpringMVC manages Controller, and Spring container manages Service and Dao (and possibly tool classes, etc.). The so-called integration is to specify which objects are managed by which container. In addition, since the Controller is responsible for invoking the Service, this involves cross-container access issues. Fortunately, Spring itself does this function to allow the SpringMVC container to access the objects in the Spring container.

0. Create a new database table

create table t_stu(
    id int(10) primary key auto_increment,
    name varchar(20),
    age int(10)
)charset = utf8;

1. Create a new webapp project

2. Add dependencies

        Springmvc, Spring, MyBatis, jackson (objects converted to json format), MySql driver (connect to database), druid (connection pool), jsp, servlet dependency

<?xml version="1.0" encoding="UTF-8"?>

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

  <groupId>org.example</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>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <!--jsp依赖-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
      <scope>provided</scope>
    </dependency>
    <!--springmvc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--spring依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--spring-jdbc对事务的支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!--jackson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <!--mybatis-spring依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.14</version>
    </dependency>
    <!--druid-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.16</version>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>

    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

3. web.xml

1) Register DispathcherServlet , which is used to   1. Create a SpringMVC container at the same time, and further create a Controller object 2. Used to receive requests

2) Register the Spring listener ContextLoaderListener , which is used to  create Spring container objects to create Service and Dao objects

3) Register a character set filter to solve the problem of garbled Chinese characters in post requests

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  
  <!--注册DispatcherServlet,配置Tomcat启动后就创建-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--注册spring监听器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--注册字符集过滤器,解决post请求乱码的问题-->
  <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>
    <init-param>
      <param-name>forceRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

4. Configuration file

        Springmvc, Spring, MyBatis, database connection configuration files

Springmvc

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

    <!--声明组件扫描器-->
    <context:component-scan base-package="com.zzt.vo"/>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--配置注解驱动 1.响应ajax请求,返回json 2.解决静态资源访问冲突-->
    <mvc:annotation-driven/>

    <!--静态资源处理 方式2-->
    <mvc:resources mapping="/static/**" location="/static/" />

</beans>

mybatis

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

    <!--给实体类别名-->
    <typeAliases>
        <package name="com.zzt.vo"/>
    </typeAliases>

</configuration>

spring

<?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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!--配置Service层的扫描器-->
    <context:component-scan base-package="com.zzt.service"/>

    <!--加载数据库连接信息文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <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>

    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定使用的连接池-->
        <property name="dataSource" ref="dataSource"/>
        <!--关联Mybatis-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>

    <!--Mapper扫描器,扫描Mapper接口,并自动构建对象,注册到Spring容器中,Bean id为mapperd类名,首字母小写-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定sqlsessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--配置要扫描的包-->
        <property name="basePackage" value="com.zzt.dao"/>
    </bean>

</beans>

Database connection profile

jdbc.url = jdbc:mysql://localhost:3306/study_mybatis?serverTimezone=GMT%2B8
jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.username = ****
jdbc.password = ****

5. Create Entity Class

package com.zzt.vo;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

6. Dao interface and xml configuration [the same name is required when the package is imported]

[Note]: @Autowried annotation can be injected without the set method

package com.zzt.dao;

import com.zzt.vo.Student;

import java.util.List;

public interface StudentDao {
    int insertStudent(Student student);
    List<Student> queryStudents();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zzt.dao.StudentDao">

    <cache/>

    <insert id="insertStudent" parameterType="Student">
        insert into t_stu(name,age) values (#{name},#{age});
    </insert>

    <select id="queryStudents" resultType="Student">
        select id,name,age from t_stu
    </select>

</mapper>

7. Business logic

package com.zzt.service;

import com.zzt.vo.Student;

import java.util.List;

public interface StudentService {
    public int addStudent(Student student);
    public List<Student> queryStudents();
}
package com.zzt.service.Impl;

import com.zzt.dao.StudentDao;
import com.zzt.service.StudentService;
import com.zzt.vo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    @Override
    public int addStudent(Student student) {
        return studentDao.insertStudent(student);
    }

    @Override
    public List<Student> queryStudents() {
        return studentDao.queryStudents();
    }
}

8. Controller

package com.zzt.controller;

import com.zzt.service.StudentService;
import com.zzt.vo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/addStudent")
    public ModelAndView addStudent(Student student){
        ModelAndView modelAndView = new ModelAndView();

        String msg = "";
        int num = studentService.addStudent(student);
        if( num > 0 ){
            msg = "学生" + student.getName() + "注册成功";
        }
        modelAndView.addObject("msg",msg);
        modelAndView.setViewName("result");
        
        return modelAndView;
    }

}

9. Front page

/index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+ "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<html>
<head>
    <title>SSM框架实例</title>
    <base href="<%=basePath%>" />
</head>
<body>
    <div align="center">
        <img src="static/images/ssm.jpg">
        <table>
            <tr>
                <td><a href="registerStudent.jsp">注册学生</a></td>
            </tr>
            <tr>
                <td><a href="queryStudents.jsp">查询学生</a></td>
            </tr>
        </table>
    </div>
</body>
</html>

/registerStudent.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+ "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<html>
<head>
    <title>学生注册</title>
    <base href="<%=basePath%>" />
</head>
<body>
    <div align="center">
        <form action="student/addStudent" method="post">
            姓名:<input type="text" name="name">
            <br>
            年龄:<input type="text" name="age">
            <br>
            <input type="submit" name="注册">
        </form>
    </div>
</body>
</html>

/WEB-INF/view/result.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    注册结果:${pageContext.request.getAttribute("msg")}
</body>
</html>

10. Implementation results

11. Perform process analysis

        In this project we built, the execution process is:

12. Complete functions-query students

        Since only the data needs to be transferred, we use Ajax to transfer; add a button to initiate the query Ajax request in the query page to avoid the need for global refresh for re-query. In order to use Ajax, we need to introduce jquery.

    // 使用ajax
    @RequestMapping("/queryStudents")
    @ResponseBody
    public List<Student> queryStudents(){
        System.out.println("进入查询方法");
        List<Student> students = studentService.queryStudents();
        for (Student student : students) {
            System.out.println(student);
        }
        return students;
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme()+ "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>" />
    <script type="text/javascript" src="static/js/jquery-3.5.1.js"></script>
    <script type="text/javascript">
        $(function () {
            // 当当前页面的的DOM对象加载完成后,执行loadStudents函数
            loadStudents();
            // 使用id选择器
            $("#btnLoader").click(function () {
                loadStudents();
            })
        })

        function loadStudents() {
            $.ajax({
                url:"student/queryStudents",
                type:"get",
                dataType:"json",
                success:function (receive) {
                    // 清除已有的数据
                    $("#info").html("")

                    $.each(receive,function (i,student) {
                        $("#info").append("<tr>")
                            .append("<td>" + student.id + "</td>")
                            .append("<td>" + student.name + "</td>")
                            .append("<td>" + student.age + "</td>")
                            .append("</tr>")
                    })
                }
            })
        }
    </script>
</head>
<body>
    <div align="center">
        <table>
            <thead>
                <td>学号</td>
                <td>姓名</td>
                <td>年龄</td>
            </thead>
            <tbody id="info">

            </tbody>
        </table>
        <input type="button" id="btnLoader" value="查询">
    </div>
</body>
</html>

 

 

Guess you like

Origin blog.csdn.net/qq_39304630/article/details/112984326