[project practice] is it necessary to learn SSM integration with springboot

Time:2020-7-5

Project driven learning and practice testing knowledge

preface

At present, the technology stack used in Java back-end development is basically unified: Spring + spring MVC + mybatis, which is commonly referred to as SSM. Although the popular way is to use springboot to quickly build and configure SSM projects, it is still necessary to know how to combine the three without springboot, because springboot only helps us to do a lot of configuration, not to abandon those configurations. Therefore, knowing how to integrate native SSM can help us understand SSM better and understand spri better Benefits of ngboot! Moreover, some old projects just don’t use spring boot. If you don’t know about the integration and configuration of native SSM, it will be extremely hard to maintain the old projects.

Compared with the rapid setup of spring boot, SSM integration is cumbersome, but don’t worry. This article will demonstrate how to integrate the three, and explain the meaning of each configuration step by step. At the end of the article, the mind map and GitHub address of the project are also included,Clone down to run directly, if you want to do a complete SSM project, you can use this framework to develop directly!

integration

Project construction

Create project

Here, idea is used for project creation and Maven is used to manage dependency packages. First, we create a new project on idea, select maven, and then select web application

[project practice] is it necessary to learn SSM integration with springboot

Click next, enter groupid and artifactid, and then click Next until complete. After the project is created, the whole project structure is as follows:

[project practice] is it necessary to learn SSM integration with springboot

Configure web projects

Now don’t worry about configuring SSM. We have to configure the web project under the idea first. As you can see, after the establishment of the project, this web.xml The file says version 2.3, which is too old to do.

We hold downcatl + shift + alt + SOpen the project structure of idea, click modules on the left, click web, and then click the delete button on the right. OK. Finally, click apply to delete the default one

[project practice] is it necessary to learn SSM integration with springboot

At this point, we will find the default web.xml The file has been deleted. Then we click the Add button on the right, click web.xml Add:

[project practice] is it necessary to learn SSM integration with springboot

Here we select version 3.1, click OK in the pop-up box, and then click OK below to complete the creation:

[project practice] is it necessary to learn SSM integration with springboot

We’ll find out when we’re done web.xml The content has become 3.1.

[project practice] is it necessary to learn SSM integration with springboot

Establish project structure

Don’t worry about configuring SSM at this time. We don’t even have a basic structure in our project now. Where do you write your core code, where do you test and where do you put your resources? All these are what we need to build.

First, we create a new test folder under the SRC path, and then create a new Java and Resources folder under the Src / main path. After creating a folder, right-click the folder, drag it to the bottom, select mark directory as, and then select the corresponding directory structure.

The Java folder corresponds to sourcesroot, which represents the project source code path marked, and the code is written here.

The Resources folder corresponds to resourcesroot, which represents the resource path marked. All resources, such as configuration files, are placed here.

The test folder corresponds to testsourcesroot, which means that the test path is marked, and the test code will be placed here.

[project practice] is it necessary to learn SSM integration with springboot

After the folder is specified, we will create our code package structure under the Java folder. The package is divided into the most basic controller, service, mapper and entity. After the package is built, the directory structure is as follows:

[project practice] is it necessary to learn SSM integration with springboot

Import prerequisite dependency packages

After the basic project structure is sorted out, we will start to integrate SSM. The first thing we have to do is pom.xml Import the necessary dependency packages into the file, copy and paste them directly. Notes are made in each place

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

    <! -- unified configuration jar package version -- >
    <mysql.version>5.1.48</mysql.version>
    <spring.version>5.2.0.RELEASE</spring.version>
    <jackson.version>2.10.0</jackson.version>
</properties>

<dependencies>
    <! -- unit test, pay attention to 4.12 or above. Scope is test, which means that it is only used for testing, and does not package and release this dependency package with the version -- >
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <! -- log we use logback -- >
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
    </dependency>

    <! -- simplify the tool Lombok for getter and setter. Not required
    Note: to use Lombok, you also need to download the corresponding plug-in on idea -- >
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
        <scope>provided</scope>
    </dependency>


    <! --- database configuration
    <! -- MySQL driver dependency package, necessary to connect mysql -- >
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>

    <! -- data source depends on package, which can greatly improve the convenience and convenience. Here we use Ali's Druid data source -- >
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.12</version>
    </dependency>

    <! -- mybatis essential dependency package -- >
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>

    <! --- web related configuration
    <! -- configure JavaEE dependency package, including servlet, validation and other functions -- >
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>8.0</version>
        <scope>provided</scope>
    </dependency>

    <! -- JSTL dependency package, which is required if JSTL tags are used in JSP. Not required -- >
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <! -- the Jackson dependency package is used to convert Java objects into JSON format, which is used by spring MVC
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <! --- spring related configuration
    <! -- jar package required to configure spring JDBC container -- >
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <! -- jar packages required to configure spring IOC container -- >
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!--Spring mvc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <! -- jar packages required by AspectJ -- >
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>

    <! -- spring test dependency -- >
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>

    <! -- configure spring to integrate mybatis jar package -- >
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>
</dependencies>

Integration of spring and mybatis

Database configuration

Before we do the integration, let’s prepare the database for a complete demonstration. I use MySQL 5.7.25 here. Let’s create a new one called SSM_ Demo database, execute the statement to create a new user table and insert two test data:

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_ Increment comment 'primary key ID',
  `name` varchar(255) COLLATE utf8mb4_ Bin not null comment 'account name',
  `password` varchar(255) COLLATE utf8mb4_ Bin not null comment 'account password',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

INSERT INTO `user` VALUES (1, 'admin', '123456');
INSERT INTO `user` VALUES (2, 'rudecrab', '654321');

Then we create the entity class user corresponding to the database table in the entity package

@Data // Lombok annotation, automatically generate getter, setter, toString methods
public class User implements Serializable {
    private Long id;

    private String name;

    private String password;
}

Then we create it in the Resources folderdatabase.propertiesFile to configure the relevant information of database connection (here, it is configured according to your own database information). What to use for mybatis integration is as follows:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm_demo?characterEncoding=utf-8&useSSL=false&autoReconnect=true&rewriteBatchedStatements=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

Logback log configuration

In a real project, you should observe the log output. Let’s configure the log. Create a new one in the resources directorylogback.xmlDocuments.Note that you need to specify a package at the end, which is set according to the package name of your project structure

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <! -- define the log file output address -- >
    <property name="LOG_ERROR_HOME" value="error"/>
    <property name="LOG_INFO_HOME" value="info"/>

    <! -- specify the collection strategy of logs through the appender tag, and we will define three collection strategies: console output, general information file output, and error information file output -- >
    The <! -- name attribute specifies the appender name -- >
    The <! -- class attribute specifies the output policy. There are usually two kinds of output policies: console output and file output. File output is to persist the log -- >

    <! -- console output -- >
    <appender name="CONSOLE_LOG" class="ch.qos.logback.core.ConsoleAppender">
        <! -- use the label under this label to specify the log output format -- >
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--
            %p: Output priority: debug, info, warn, error, fatal
            %r: The number of milliseconds it took to output the log message from the start of the application to the output
            %t: Output the name of the thread that generated the log event
            %f: The class alias of the class to which the output log message belongs
            %c: The full name of the class to which the output log message belongs
            %d: Output the date or time of the log point in time. Specify the format as follows: D {yyyy MM DD HH: mm: SS}
            %l: The location of the output log event, that is, the row of the statement that outputs the log message in its category.
            %m: Outputs the message specified in the code, such as message in log (message)
            %n: Output a newline symbol
            -->
            <pattern>%red(%d{yyyy-MM-dd HH:mm:ss.SSS}) %yellow([%-5p]) %highlight([%t]) %boldMagenta([%C]) %green([%L]) %m%n</pattern>
        </encoder>
    </appender>

    <! -- General information file output -- >
    <appender name="INFO_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- specify the filtering strategy by using this tag -- >
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <! -- label specifies the type of filtering -- >
            <level>ERROR</level>
            <onMatch>DENY</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>

        <encoder>
            The log output format is specified
            <pattern>[%d{yyyy-MM-dd' 'HH:mm:ss.SSS}] [%C] [%t] [%L] [%-5p] %m%n</pattern>
        </encoder>

        The <! -- tag specifies the collection strategy, such as collecting based on time -- >
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            The <! -- tag specifies the storage address of the generated log. Through this configuration, the goal of collecting logs by category and by day has been achieved -- >
            <fileNamePattern>${LOG_INFO_HOME}//%d.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
    </appender>

    <! -- error message file output -- >
    <appender name="ERROR_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <encoder>
            <pattern>[%d{yyyy-MM-dd' 'HH:mm:ss.SSS}] [%C] [%t] [%L] [%-5p] %m%n</pattern>
        </encoder>

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_ERROR_HOME}//%d.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
    </appender>

    <! -- used to set the log printing level of a package or a specific class -- >
    <logger name="com.rudecrab.ssm.mapper" level="DEBUG"/>

    <! -- required label to specify the most basic log output level -- >
    <root level="info">
        <! -- add append -- >
        <appender-ref ref="CONSOLE_LOG"/>
        <appender-ref ref="INFO_LOG"/>
        <appender-ref ref="ERROR_LOG"/>
    </root>
</configuration>

Mybatis global settings

Now we can finally integrate spring and mybatis. Let’s create a new one in the Resources foldermybatis-config.xmlFiles are used to configure mybatis globally. Here, I am used to configuring these. I can do this according to my own requirements

<?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>
    <! -- configure global settings -- >
    <settings>
        <! -- enable logging and specify how to implement the log -- >
        <setting name="logImpl" value="SLF4J"/>

        <! -- enable primary key generation policy -- >
        <setting name="useGeneratedKeys" value="true"/>

        <! -- configure the mapping of enabling underline to hump -- >
        <setting name="mapUnderscoreToCamelCase" value="true"/>

        <! -- enable L2 cache -- >
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

Spring myabtis integrated configuration

Then build a new onespring-mybatis.xmlFile, this file is used to do integration!Note that many of the settings need to specify a package, which is set according to the package name of the project structureThe notes make it clear:

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

    <! -- read the property file. Here we read the configuration related to our database connection -- >
    <context:property-placeholder location="classpath:database.properties" file-encoding="UTF-8"/>

    <! -- configure automatic scanning. If you do not configure this, you cannot use @ Autowired to load beans -- >
    <context:component-scan base-package="com.rudecrab.ssm" use-default-filters="true">
        <! -- in this case, the annotation of controller should be excluded, and the controller should be sent to MVC for scanning, so that there will be no conflict -- >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <! -- configure data source -- >
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <! -- configure JDBC basic properties, that is, database connection related configuration -- >
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <! -- configure the connection pool settings, which should be configured according to the actual project situation, and will be constantly modified with the development of the project -- >
        <property name="initialSize" value="10"/>
        <property name="maxActive" value="100"/>
    </bean>

    <!--
    The key point here is the sqlsessionfactory of mybatis, which integrates spring and mybatis together
    If you do not configure it, your mapper interface can only be obtained through sqlsession, which is very troublesome. After configuration, you can get the mapper interface through spring IOC
    -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <! -- specify data source -- >
        <property name="dataSource" ref="dataSource"/>
        <! -- load mybatis global settings, classpath is our resource path resources -- >
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <! -- configure the mapping XML file path of mybatis -- >
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <! -- specifies the mapper interface scan package of mybatis -- >
    <! -- attention!!! If you use tk.mybatis Automatically generated mapper interface must be org.mybatis . change to tk.mybatis >
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! -- specify the sqlsessionfactory that we have just configured -- >
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <! -- specify mapper interface scan package -- >
        <property name="basePackage" value="com.rudecrab.ssm.mapper"/>
    </bean>

    <! -- configure the transaction manager. If this is not configured and the transaction scanning is not started, the exception will not trigger the rollback -- >
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <! -- also specify the data source -- >
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <! -- start scanning transactions -- >
    <tx:annotation-driven/>
</beans>

JUnit test

So far, spring and myabtis have been integrated and configured. We still have to test and see the effect. Before testing, we need to establish mapper interface file, myabtis mapping XML file, service interface and implementation class

[project practice] is it necessary to learn SSM integration with springboot

The usermapper interface is used to declare various database operation methods,@RepositoryThe annotation defines it as a bean managed by spring:

@Repository
public interface UserMapper {
    /**
     *Query all user objects from the database
     *@ return user object collection
     */
    List<User> selectAll();
}

UserMapper.xml The mapping file is used to write the SQL statement corresponding to the method to be executed

<?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.rudecrab.ssm.mapper.UserMapper">
    <! -- enable cache -- >
    <cache/>

    <! -- query all user objects from the database -- >
    <select id="selectAll" resultType="com.rudecrab.ssm.entity.User">
        select * from user
    </select>

</mapper>

The userservice interface is used to declare the business method of user

public interface UserService {
    /**
     *Query all user objects from the database
     *@ return user object collection
     */
    List<User> getAll();
}

The userserviceimpl entity class is used to implement the business logic about user,@ServiceNotes and@RepositoryAnnotations are used the same way that they are defined as beans.@TransactionalThe annotation is a declarative transaction. If the method of the business layer throws an exception, the transaction rollback will be triggered. Then use the@AutowiredThe annotation is on the private attribute, and the bean is automatically loaded. There is no need for us to manually create the usermapper

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAll() {
        return userMapper.selectAll();
    }
}

The relevant classes and files have been created. Now we create a test class, userservicetest, in the test folder,Be sure to add those two annotations to the test classOtherwise, spring related functions cannot be used normally

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void getAll() {
        System.out.println(userService.getAll());
        System.out.println(userService.getAll());
    }
}

After running, we can see the running results

[project practice] is it necessary to learn SSM integration with springboot

You can see that the results are displayed normally, and the log is also printed on the console.This means that we have completed the integration of spring and mybatis!

thinking

[project practice] is it necessary to learn SSM integration with springboot

SpringMVC

spring-mvc.xml

Next, configure spring MVC and create a new one in the resources directoryspring-mvc.xmlFile.Note that the settings need to specify a package, which is set according to the package name of the project structure

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

    <! -- configure the view parser so that the file name is returned directly from the controller -- >
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <! -- prefix -- >
        <property name="prefix" value="/WEB-INF/views/"/>
        <! -- suffix -- >
        <property name="suffix" value=".jsp"/>
    </bean>

    <! -- configure static resource filtering, otherwise static resources such as CSS cannot be accessed -- >
    <mvc:default-servlet-handler/>

    <! -- configure scanned packages -- >
    <context:component-scan base-package="com.rudecrab.ssm.controller" use-default-filters="false">
        <! -- only scan controller, it is better to write in this way in actual development. MVC here only scans controller, so there will be no conflict on IOC side, otherwise transactions will be covered and IOC side should exclude this controller -- >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <! -- enable MVC annotation -- >
    <mvc:annotation-driven/>
</beans>

web.xml

The last configuration, of course, is in the web.xml There are three main configurations:

  1. Configure spring IOC container to prepare for mybatis
  2. Configure the front controller of spring MVC
  3. Configure character encoding filter
<?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_3_1.xsd"
         version="3.1">

    <! -- 1. Configure the creation of spring IOC container. If you do not configure this, mybatis cannot be used in web applications -- >
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <! -- spring and mybatis integration profile path -- >
        <param-value>classpath:spring-mybatis.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    2. Configure the front controller of spring MVC -- >
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <! -- spring MVC integration configuration file path -- >
            <param-value>classpath:spring-mvc.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>

    <! -- 3. Configure character encoding filter -- >
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Final test

The above, all the configuration is done, so let’s run a simple web project to see if the integration is successful! Remember when we werespring-mvc.xmlThe view resolution prefix is configured in the file/WEB-INF/views/Create a new folder index.jsp Document:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    < title > Home - rudecrab < / Title > page
</head>
<body>
<% -- loop extraction of elements in userlist --% >
<c:forEach var="user" items="${userList}">
    <ul>
        <li>${user}</li>
    </ul>
</c:forEach>
</body>
</html>

Next, create a new controller class under the controller package to define the provider

@Controller
@RequestMapping(value = "user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/getList")
    public String getList(Model model) {
        //Store the data in the model object so that JSP can access the data
        model.addAttribute("userList", userService.getAll());
        //JSP return name
        return "index";
    }

    @GetMapping("/getJson")
    @ResponseBody
    public List<User> getList() {
        //If you want to separate the front end and the back end, you can add the @ ResponseBody annotation to directly return the data object, so that the front-end can render the data by getting JSON
        return userService.getAll();
    }
}

Then we start Tomcat and access the interface in the browser

[project practice] is it necessary to learn SSM integration with springboot

We can see that we have successfully accessed the data, so far SSM is fully integrated!

summary

Mind map

The overall integrated configuration idea has drawn a mind map, in which detailed notes are written on each node, which can be viewed after downloading the file. The file is placed in the last GitHub address:

[project practice] is it necessary to learn SSM integration with springboot

GitHub address

https://github.com/RudeCrab/r…

It contains the entire project, clone down and open with idea to run! At the same time, the mind map file is also attached. If it is helpful to you, please point to a star. There are other project practices in the project. I will update more project practices in the future!

Recommended Today

ASP.NET Example of core MVC getting the parameters of the request

preface An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things Accept the request and parse to get the parameters Render according to the parameters and output the response content So let’s learn […]