An example of rapid integration of SSM framework — student query

Time:2022-1-5

1、 Quick preparation

SSM framework includes spring framework, spring MVC framework and mybatis framework. I have written several articles to introduce the basis and entry procedures of these frameworks. For students who are not familiar with these three frameworks, please refer to the following articles:

Spring series of [SSH framework] (I)

Annotation management of bean in spring framework series (2)

AOP idea of spring framework series

JDBC integration of spring framework series

Transaction management of spring framework series

Introduction and examples of spring MVC framework series

Component overview and configuration details of spring MVC framework series

Basic knowledge of mybatis framework

Quick start program of mybatis framework

If you have learned the relevant knowledge of SSM framework in succession, you can ignore this part and look directly at the following content.

2、 Quick create project

Since the jar package depends on the convenience of management, we use Maven for project management and development. In this step, we use idea to quickly create a maven project. We won’t go into too much detail here about how to use idea to quickly create a maven project. You can refer to the following article:

Maven project management tool Foundation Series (I)

3、 Quickly configure jar package dependencies

After the Maven project is created, quickly open and configure itpom.xmlFile, the specific configuration is as follows:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ssm.example</groupId>
  <artifactId>SsmDemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SSMDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>

        <!--  Configuring spring MVC dependency packages -- >
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!--  Spring JDBC dependency package -- >
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!--  Spring AOP dependency package -- >
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- Mybatis dependency package -- >
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        
        <!--  Spring integrates mybatis dependency package -- >
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--  MySQL driver dependency package -- >
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        
        <!--  C3p0 data source dependency package -- >
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1</version>
        </dependency>
        
        <!--  JSTL dependency package -- >
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--  Servlet API dependency package -- >
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!--  JUnit test dependency package -- >
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
      </dependency>

  </dependencies>

    <!--  If you do not add this node, mybatis's mapper XML files will be missed -- >
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

4、 Quickly configure coding filtering and resource loading

openweb.xmlFile, quick configuration enables spring, spring MVC coding filtering and static resource loading. The specific configuration code is as follows:

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <!--  Launch spring's container -- >
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--  The front-end controller of spring MVC intercepts all requests -- >
  <servlet>
    <servlet-name>mvc-dispatcher</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>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!--  Character encoding filters must be placed before all filters -- >
  <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>
  
  <!--  Load static resources -- >
  <servlet-mapping>
      <servlet-name>default</servlet-name>
      <url-pattern>*.js</url-pattern>
  </servlet-mapping>
  
  <servlet-mapping>
      <servlet-name>default</servlet-name>
      <url-pattern>*.css</url-pattern>
  </servlet-mapping>
  
</web-app>

5、 Quickly configure spring configuration files

stayresourcesNew under folderapplicationContext.xmlFile to configure mybatis and database related information. The specific code configuration is as follows:

<?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-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    
    <!--  Load resource file -- >
    <context:property-placeholder location="classpath:db.properties"/>
    
    <!--  Configure c3p0 data source -- >
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="initialPoolSize" value="5"></property>
        <property name="maxPoolSize" value="10"></property>
    </bean>
    
    <!--  Configure mybatis sqlsessionfactory -- >
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--  Specify mybatis data source -- >
        <property name="dataSource" ref="dataSource"/>
        <!--  Specify mybatis mapper mapping file location -- >
        <property name="mapperLocations" value="classpath:com/ssm/example/dao/*.xml"/>
        <!--  Specify the location of the mybatis global configuration file -- >
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    
    <!--  Scan mapper interface of mybatis -- >
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- Scan all Dao interfaces and add them to IOC container -- >
        <property name="basePackage" value="com.ssm.example.dao"/>
    </bean>
    
    <!--  Configure transaction manager -- >
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--  Specify data source -- >
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <!--  Configure transaction enhancements -- >
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--  Configure that all methods are transaction methods -- >
            <tx:method name="*"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!--  Enable annotation based transactions -- >
    <aop:config>
        <!--  Pointcut expression -- >
        <aop:pointcut expression="execution(* com.ssm.example.service.impl.*.*(..))" id="txPoint"/>
        <!--  Configure transaction enhancements -- >
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>
</beans>

6、 Quick configuration database connection information

stayresourcesNew under folderdb.propertiesFile to configure database connection related information. The specific code configuration is as follows:

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_example?useUnicode=true&characterEncoding=UTF-8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

7、 Quick configuration database operation auxiliary information

stayresourcesNew under foldermybatis-config.xmlFile to configure relevant database operation auxiliary information. The specific code configuration is as follows:

<?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>
    <settings>
        <!--  Print SQL -- >
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
    
    <typeAliases>
        <!--  Specify a package name, and mybatis will search for the required JavaBean -- > under the package name
        <package name="com.ssm.example.entity"/>
    </typeAliases>
    
</configuration>

8、 Quickly configure spring MVC annotation scanning and view parser

stayresourcesNew under folderspringmvc.xmlFile to configure relevant database operation auxiliary information. The specific code configuration is as follows:

<?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-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    
    <!--  Enable spring MVC annotation driven -- >
    <mvc:annotation-driven />
    
    <!--  Scan business code -- >
    <context:component-scan base-package="com.ssm.example"></context:component-scan>
    
    <!--  Configure view parser -- >
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
</beans>

9、 Quick new data table

Create a new MySQL database and quickly create a new data tablessm_exampleThe specific table building codes are as follows:

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `tel` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `cla` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

Insert into ` student ` values (1, 'Kong Yiji', 'male', ' [email protected] ',' 13509856897 ',' computer class 1 ');
Insert into ` student ` values (2, 'a Qiang', 'female', ' [email protected] ',' 12345678909 ',' software engineering ');
Insert into ` student ` values (3, 'Ah Fu', 'male', ' [email protected] ',' 13657898762 ',' Mathematics');
Insert into ` student ` values (4, 'a Xia', 'female', ' [email protected] ',' 12378645987 ',' English major ');
Insert into ` student ` values (5, 'Guide', 'male', ' [email protected] ',' 13587690873 ',' miscellaneous brick handling specialty ');

SET FOREIGN_KEY_CHECKS = 1;

10、 Quickly create a new entity class

Quickly create a new entity classStudent.java, the specific code is as follows:

package com.ssm.example.entity;

public class Student {
    
    private int id;
    private String name;
    private String gender;
    private String email;
    private String tel;
    private String cla;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getCla() {
        return cla;
    }
    public void setCla(String cla) {
        this.cla = cla;
    }
    
    
}

11、 Write business code quickly

Quick newStuentController.javaControl class, the specific code is as follows:

package com.ssm.example.controller;

import java.util.List;

import com.ssm.example.entity.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;

import com.ssm.example.service.StudentService;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;
    
    /**
     *Find all students
     * @return
     */
    @RequestMapping(value="/findAll")
    public ModelAndView test(){
        List<Student> list = studentService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("list", list);
        return modelAndView;
    }
    
}

Quick newStudentService.javaThe interface code is as follows:

package com.ssm.example.service;

import java.util.List;

import com.ssm.example.entity.Student;

public interface StudentService {
    public List<Student> findAll();
}

Quick newStudentServiceImpl.javaClass implements the interface, and the specific code is as follows:

package com.ssm.example.service.impl;

import java.util.List;

import com.ssm.example.dao.StudentDAO;
import com.ssm.example.entity.Student;
import com.ssm.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDAO studentDAO;
    
    public List<Student> findAll() {
        // TODO Auto-generated method stub
        return studentDAO.findAll();
    }
    
}

Quickly create a new Dao interfaceStudentDAO.java, the specific code is as follows:

package com.ssm.example.dao;

import java.util.List;

import com.ssm.example.entity.Student;

public interface StudentDAO {
    public List<Student> findAll();
}

Quickly create a new Dao interface proxy fileStudentDAO.xml, the specific code is as follows:

<?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.ssm.example.dao.StudentDAO">

        <resultMap type="Student" id="studentMap">
            <id property="id" column="id"/>
            <result property="name" column="name"/>
            <result property="gender" column="gender"/>
            <result property="email" column="email"/>
            <result property="tel" column="tel"/>
            <result property="cla" column="cla"/>
        </resultMap>

        <select id="findAll" resultMap="studentMap">
            select * from student
        </select>

    </mapper>

12、 New access page

Quick new access pageindex.jspAnd the page uses the bootstrap framework for light rendering. The specific code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
< title > student list < / Title >
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
<br><br><br>
    <div class="container" align="center">
        <div class="row">
            <div class="col-md-12">
                <h1>An example of rapid integration of SSM framework -- student query</h1>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover" id="emps_table">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" id="check_all"/>
                            </th>
                            < th > No. < / th >
                            < th > name < / th >
                            < th > gender < / th >
                            < th > email < / th >
                            < th > contact number < / th >
                            < th > class < / th >
                            < th > operation < / th >
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach items="${list }" var="student">
                            <tr>
                                <td><input type='checkbox' class='check_item'/></td>
                                <td>${student.id }</td>
                                <td>${student.name }</td>
                                <td>${student.gender }</td>
                                <td>${student.email }</td>
                                <td>${student.tel }</td>
                                <td>${student.cla }</td>

                                <td>
                                    <button class="btn btn-primary btn-sm edit_btn">
                                        < span class = "glyphicon pencil" > Edit</span>
                                    </button>&nbsp;&nbsp;
                                    <button class="btn btn-danger btn-sm delete_btn">
                                        < span class = "glyphicon glyphicon Dash" > delete</span>
                                    </button>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
        
    </div>
</body>
</html>

13、 Test quickly

Here, the SSM framework integration program has been written. Deploy and start the Tomcat server, and then test it in the browser address bar. The results are as follows:

An example of rapid integration of SSM framework -- student query

Project source code address: click here to get the source code directly

Pay attention to WeChat official account compassblog, learn more