This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

In this article, we use SSM framework (Spring + SpringMVC + MyBatis) to build a project from 0.It looks like a fairly simple demo, but it involves a lot of knowledge. We should focus on the integration between SSM frameworks. For this project, you need to have the SSM framework, jQuery, Ajax, Bootstrap, Maven, etc.

Setting up the infrastructure

Here we use IDEA for development. First we create a Maven project:Give the project a name and specify a path:Then click Finish.

After the project is created, go to the POM.xml file and add the corresponding dependencies. We need to add the following dependencies:

  • SpringMVC
  • Spring JDBC
  • Spring AOP
  • MyBatis
  • PageHelper
  • C3P0
  • The mysql driver
  • JSTL
  • Servlet-API
  • MybatisGenerator
  • Junit
<dependencies>
    <! -- SpringMVC -->
    <! -- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.7. RELEASE</version>
    </dependency>

    <! -- Spring JDBC -->
    <! -- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.7. RELEASE</version>
    </dependency>

    <! -- Spring AOP -->
    <! -- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.7. RELEASE</version>
    </dependency>

    <! -- Mybatis -->
    <! -- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.2</version>
    </dependency>

    <! Mybatis adaptor package with Spring
    <! -- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <! -- PageHelper pagination plugin -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.0.0</version>
    </dependency>

    <! -- Database connection pool -->
    <! -- https://mvnrepository.com/artifact/c3p0/c3p0 -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <! -- Database driver -->
    <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.41 was</version>
    </dependency>

    <! -- JSTL -->
    <! -- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>


    <! -- Servlet-API -->
    <! -- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <! -- MybatisGenerator -->
    <! -- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.4.0</version>
    </dependency>

    <! -- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>
Copy the code

After the dependencies are added, we need to configure the project:In the options box that pops up, drop down to find Spring and SpringMVC and check it:At this point, IDEA automatically helps us create the configuration files for Spring and SpringMVC, which are configured in web.xml:Take a look at the web.xml file:This is what IDEA helped us configure, and we made some changes to it. Normally we put the Spring configuration file in the classpath. Here we change it:Right click on the main directory to create a new folder:Select Resources from the popup option box. Note that the resources folder must have a logo in the bottom right corner, otherwise IDEA will not recognize:Now let’s move the applicationContext.xml file here:Accordingly, the web. XML file needs to be modified as follows:


      
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <! Start Spring container -->
    <! -- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <! -- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <! Springmvc's front-end controller intercepts all requests
    <! -- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <! -- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>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>

    <! Use a Rest style URI to convert a normal POST request to a specified DELETE or PUT request.
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>
</web-app>
Copy the code

In addition to configuring the Spring startup container and the front controller, there are character encoding filters and hidden method filters that are specified in the comments.

Now we need to configure SpringMVC, but before we can configure it, we need to set up the package structure by creating a new Java directory in the main directory in the same way we created the Resources directory:Then set up the package structure:

Configure dispatcher-servlet.xml:


      
<! --suppress SpringFacetInspection -->
<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">

    <! -- SpringMVC configuration file -->

    <! Configure the packets to be scanned -->
    <context:component-scan base-package="com.wwj" use-default-filters="false">
        <! To avoid duplicate scans with Spring, SpringMVC simply scans the controller.
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <! -- Configure the view parser -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <! -- Handling static resources -->
    <mvc:default-servlet-handler/>

    <! -- Basic configuration -->
    <mvc:annotation-driven >
        <! -- Message converter -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/plain; charset=UTF-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>
Copy the code

SpringMVC configuration is relatively simple, configured with a view parser and a message converter, message converter is to prevent Chinese garbled; One thing to note here is that since both Spring and SpringMVC scan our package, to prevent some packages from being scanned twice, we need to divide the two frameworks so that SpringMVC only scans the controller package and Spring scans all the packages except the controller package.

To configure the Spring configuration file (applicationContext.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: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/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <! -- Spring configuration file -->

    <! -- Configure scanned packets -->
    <context:component-scan base-package="com.wwj">
        <! To avoid repeated scanning with SpringMVC, Spring needs to scan all packages except the controller.
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <! -- Import external properties file -->
    <context:property-placeholder location="classpath:dbconfig.properties"/>

    <! -- Configure data source -->
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <! Mybatis -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <! -- Specify Mybatis global configuration file -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="dataSource" ref="pooledDataSource"/>
        <! Mybatis mapper file location -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <! Add Mybatis interface implementation to IOC container
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! -- Scan all interfaces under dao package -->
        <property name="basePackage" value="com.wwj.crud.dao"/>
    </bean>

    <! SqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>

    <! -- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="pooledDataSource"/>
    </bean>

    <! -- Configure transactions based on XML -->
    <! -- Set transaction properties -->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <! All methods are transaction methods
            <tx:method name="*"/>
            <! -- all methods starting with get are queries -->
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <! Configure pointcuts -->
        <aop:pointcut id="txPointCut" expression="execution(* com.wwj.crud.service.. * (..) )"/>
        <! -- Associate transaction attributes and pointcuts -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>
Copy the code

The content of the Spring configuration file here is the basic configuration, and the comments are clearly written.

Mybatis configuration file and mapper file location:Let’s put them all in the Resources directory.

Here is the dbconfig.properties file:

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
Copy the code

Now that Spring and SpringMVC are configured, let’s configure the Mybatis global configuration file:


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <! -- Configure global properties -->
    <settings>
        <! -- Enable hump naming rule mapping -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <! -- Set alias -->
    <typeAliases>
        <package name="com.wwj.crud.bean"/>
    </typeAliases>

    <! -- Register plugin -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

</configuration>
Copy the code

Since we integrate Mybatis with Spring, the configuration of the global configuration file is extremely simple, just enable the camel naming rule mapping and alias Settings.

Next, design the data table:

CREATE TABLE tbl_dept (
  dept_id int(11) NOT NULL AUTO_INCREMENT,
  dept_name varchar(255) NOT NULL.PRIMARY KEY (dept_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Copy the code
CREATE TABLE tbl_emp (
  emp_id int(11) NOT NULL AUTO_INCREMENT,
  emp_name varchar(255) NOT NULL,
  gender char(1) DEFAULT NULL,
  email varchar(255) DEFAULT NULL,
  d_id int(11) DEFAULT NULL.PRIMARY KEY (emp_id),
  KEY fk_emp_dept (d_id),
  CONSTRAINT fk_emp_dept FOREIGN KEY (d_id) REFERENCES tbl_dept (dept_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Copy the code

An employee table and a department table are created, where the d_id attribute of the employee table forms a foreign key constraint with the DEPt_id attribute of the department table.

For mapper file and mapper interface writing, we all handed over to MybatisGenerator.

Create the mgB. XML file under the project and configure it as follows:


      
<! DOCTYPEgeneratorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <! -- Configure database connection -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm_crud" userId="root"
                        password="123456">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <! -- Specify the location of JavaBean generation -->
        <javaModelGenerator targetPackage="com.wwj.crud.bean"
                            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <! SQL map file generated by SQL map file
        <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <! -- specify the location where the DAO interface is generated, mapper interface -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.wwj.crud.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>


        <! -- table specifies the generation strategy for each table -->
        <table tableName="tbl_emp" domainObjectName="Employee"></table>
        <table tableName="tbl_dept" domainObjectName="Department"></table>
    </context>
</generatorConfiguration>
Copy the code

If your package name is different from mine, you need to change the package name. Don’t just copy and paste the contents of the configuration file.

Then create a new test file and execute the following code:

public class MBGTest {
    public static void main(String[] args) throws Exception{
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null); }}Copy the code

After executing, all the Bean classes, Mapper interfaces, and Mapper configuration files are created automatically. We also need to modify the employeemapper.xml file because the SQL generated automatically does not have federated queries.

Page set up

Here, the basic environment is set up. Next, the page is set up. Here, we use BootStrap to quickly generate a beautiful page.After downloading, put it directly into webApp directory with jQuery:We knew that HTTP :/localhost:8080/ SSM would automatically access the index.jsp file, so we had it forwarded directly to another page:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/8/17 0017
  Time: 20:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<jsp:forward page="/emps"></jsp:forward>
<html>
<head>
</head>
<body>
</body>
</html>
Copy the code

There’s a lot of work to be done on the page, and it’s very inconvenient to talk about, so let’s skip this and start configuring Tomat.

Run the project

Click on Configuration in the upper right corner:Click the plus sign in the upper left corner of the pop-up dialog to find local Tomcat:If you haven’t configured Tomcat before, click Configure above to Configure it, and then click Fix below:Click the plus sign to select Artifact… :Select OK:Then run Tomcat directly to access the project.

summary

The purpose of this article is to integrate the SSM framework, so that we can have a clear idea to design and write a complete project, so the details of the code did not do too much explanation, the project is also used some very basic framework technology.