Step 1: Create a New MAVEN project

Step 2: Build the overall structure of the project

Project structure analysis :(similar to three-tier architecture)

  1. .Controller layer: The control layer that handles page requests
  2. Interceptor: interceptor
  3. Mapper: background persistence layer (equivalent to Dao layer in three-tier architecture)
  4. Pojo: Entity class
  5. Service: business access layer
  6. Resource: stores SSM configuration files for easy management
  7. Webapp-static: Store static files, JS, CSS, images, etc
  8. Web-inf-page: Stores JSP pages
  9. Test-java: junit unit tests

Step 3: Configure the maven: pom.xml file

<?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>cn.testssm</groupId>
    <artifactId>TestSSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>TestSSM Maven Webapp</name>
    <url>http://www.example.com</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <!-- 设置项目编码编码 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!--版本控制-->
        <!-- spring版本号 -->
        <spring.version>5.0.2.RELEASE</spring.version>
        <!-- mybatis版本号 -->
        <mybatis.version>3.4.5</mybatis.version>
        <!--日志记录-->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <!--mysql版本号-->
        <mysql.version>5.1.6</mysql.version>
    </properties>
    <!--导入项目jar包-->
    <dependencies>
        <!-- spring -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--junitb版本必须>=4.1.2-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- junit单元测试,test:只有在test环境下使用,compile全局使用-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- mysql连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- servlet,jap支持 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <!--jstl标签库-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- log日志记录 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
        <!-- mybatis持久层-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!--c3p0连接池-->
        <!--c3p0有自动回收空闲连接功能-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <!--文件上传-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!--alibaba的fastjson解析数据-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>TestSSM</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <!--防止静态文件不编译-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                    <include>**/*.html</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>
Copy the code

Step 4: Write four configuration files

A. ApplicationContext. XML

<? The 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/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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <! - loading configuration file *. The properties - > < context: the property - placeholder location = "classpath: jdbcConfig. Properties" / > <! - the dataSource configuration database - > < bean id = "dataSource" class = "boPooledDataSource com.mchange.v2.c3p0.Com" > <! <property name="driverClass" value="${jdbc.driver}"/> <! - load database password - > < property name = "jdbcUrl" value = "${. JDBC url}" / > <! - load database connection - > < property name = "user" value = "${JDBC. Username}" / > <! <property name="password" value="${jdbc.password}"/> </bean> <! - configuration sqlsessioFactory - > < bean id = "sqlSessionFactoryBean" class = "org. Mybatis. Spring. SqlSessionFactoryBean" > <! /> < dataSource name="dataSource" /> <! <property name="configLocation" value="classpath:mybatis. XML "/> <property name="mapperLocations" value="classpath:cn/test/mapper/*Mapper.xml"/> </bean> <! Configuration, scan package load mapper proxy object - > < bean class = "org. Mybatis. Spring. Mapper. MapperScannerConfigurer" > <! - scan mapper path - > < property name = "basePackage" value = "cn. Test. Mapper" / > < property name = "sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/> </bean> <! <context:component-scan base-package="cn.test.service"/> <! Configure Spring declarative transaction management --> <! - configuration transaction manager - > < bean id = "transactionManager" class = ". Org. Springframework. JDBC datasource. DataSourceTransactionManager "> <property name="dataSource" ref="dataSource"></property> </bean> <! --> <tx:advice ID ="txAdvice" transaction-manager="transactionManager"> < TX: Attributes > <! Read -only="true"/> <! Transaction isolation level, default default--> <tx:method name="*" Isolation =" default "/> </tx: Attributes > </tx:advice> <! <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.test.service.impl.*.*(..)) )"></aop:advisor> </aop:config> </beans>Copy the code

2: mybatis. XML

<? The 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> <! -- Enable level 2 cache --> < Settings > <! Setting name="cacheEnabled" value="true"/> <! <setting name="lazyLoadingEnabled" value="true"/> </ Settings > <typeAliases> <! <package name="cn.test.pojo"/> </typeAliases> </configuration>Copy the code

Three: spring MVC – XML

<? The 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="cn.test.controller"/> <! < MVC :resources location="/static/" mapping="/static/**"></ MVC :resources> <! -- Enable SpringMVC annotation support --> < MVC :annotation-driven></ MVC :annotation-driven>< MVC :annotation-driven><! < MVC :message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/plain; charset=UTF-8"/> </bean> <! - configuration Fastjson support - > < bean class = "com. Alibaba. Fastjson. Support. Spring. FastJsonHttpMessageConverter" > < property name="supportedMediaTypes"> <list> <value>text/html; charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <mvc:default-servlet-handler/> <! -- Interceptor, < MVC :interceptors> < MVC :interceptor> < MVC :mapping path="/sys/**"/> <bean class="cn.test.interceptor.SysInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>Copy the code

Four: web. XML

<? The XML version = "1.0" encoding = "utf-8"? > < web - app version = "3.0" XMLNS = "http://java.sun.com/xml/ns/javaee" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>Archetype Created Web Application</display-name> <! -- Chinese garbled characters, CharacterEncodingFilter --> <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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! Context-param <param-name>contextConfigLocation</param-name> <! - classpath file -- > < param - value > classpath: the applicationcontext.xml < / param - value > < / context - param > <! -- Configure spring listeners to load only applicationContext in the WEB-INF directory by default. XML file - > < listener > < listener - class > org. Springframework. Web. Context. ContextLoaderListener < / listener - class > < / listener > <! <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! -- Load SpringMVx. XML file --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc. XML </param-value>  </init-param> <! <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/WEB-INF/pages/login.jsp</welcome-file> </welcome-file-list> </web-app>Copy the code

Step 5: jdbcconfig.properties

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm? useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=rootCopy the code

Step 6: log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=info, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout Log4j. Appender. CONSOLE. Layout. ConversionPattern = % d {ISO8601} [% 15.15 t] % % - 6 r - 5 p % 30.30 x % m \ % n c # LOGFILE is set to be  a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\nCopy the code

Step 7: Write Junit unit tests

/ * * * test class * / @ RunWith SpringJUnit4ClassRunner. Class @ ContextConfiguration (locations = "classpath:applicationContext.xml") public class TestSSM { @Resource private ApplicationContext ac; @Test public void testUserLogin() { UserService userService = (UserService) ac.getBean("userService", UserService.class); User user = new User(); user.setUserName("admin"); user.setUserPassword("admin"); Integer result = userService.userLogin(user); System.out.println(result); System.out.println(" send Monkey King "); }}Copy the code

Test framework integration

Ok, the framework is basically completed, the test interface created below, to see whether the framework can run normally.

Step 1: Write the User entity class

package cn.test.pojo; import java.io.Serializable; public class User implements Serializable { private Integer id; private String userName; private String userPassword; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } @Override public String toString() { return "User{" + "id=" + id + ", userName='" + userName + '\'' + ", userPassword='" + userPassword + '\'' + '}'; }}Copy the code

Step 2: Write a Persistence layer (Mapper)

Since we are just learning SSM, we put the XML file and interface in the same package.

  1. UserMapper.java

    “`java package cn.test.mapper;

    import cn.test.pojo.User;

    public interface UserMapper {

    / * *

    • The user login
    • @param user
    • @return

    */ public Integer userLogin(User user);

}

2. UserMapper.xml ```xml <? The 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="cn.test.mapper.UserMapper"> <select id="userLogin" resultType="Integer" parameterType="user"> SELECT COUNT(1)  FROM user WHERE userName = #{userName} and userPassword = #{userPassword} </select> </mapper>Copy the code

Step 3: Write a Service layer

UserService.java

“`java package cn.test.service;

import cn.test.pojo.User;

public interface UserService {

public Integer userLogin(User user);
Copy the code

}

2. UserServiceImpl.java ```java package cn.test.service.impl; import cn.test.mapper.UserMapper; import cn.test.pojo.User; import cn.test.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service("userService") public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public Integer userLogin(User user) { return userMapper.userLogin(user); }}Copy the code

Step 4: Write the Controller

package cn.test.controller; import cn.test.pojo.User; import cn.test.service.UserService; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/userController") public class UserController { @Resource private UserService userService; @RequestMapping("/userLogin") public String userLogin(User user) { System.out.println(user); Integer result = userService.userLogin(user); return ""; } @RequestMapping("/testAjax") @ResponseBody public String testAjax(User user) { System.out.println(user); Map<String, User> map = new HashMap<String, User>(); map.put("data", user); return JSONArray.toJSONString(map); }}Copy the code

Step 5: JSP page

<%-- Created by IntelliJ IDEA. User: Dell Date: 2020/8/8 Time: 21:23 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html; charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <form Action ="userController/userLogin" method="post"> <div> <p> Test login </p> <p> Account *</p> <p><input type="text" name="userName" Required placeholder=" please input account "/></p> <div ID ="login_password"> <p>< P ><input type="text" name="userPassword" Required placeholder=" submit" name="login" value=" login" /></p> </div> </form> <button Type ="button" value=" BTN "id=" BTN "> </button> <script src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script> <script> $(function () { $("#btn").click(function () { $.ajax({ url: "userController/testAjax", type: "POST", data: {userName: Parse (res) {var data = json.parse (res); alert(res); alert(data); for (var key in data) { alert(data[key].userName); } } }) }) }) </script> </body> </html>Copy the code

Start the server, type http://localhost:8080/index.jsp in the browser address

Integration of success

The following is a list of possible solutions to novice problems:

  1. Junit unit test: Can not find Class: cn.testssm.test solution: Because the development tool used idea, originally when building the Java name changed to test, changed to Java

2. I was using the Spring version at 5.0.2, and Spring 5 began requiring junit unit test versions to be >=4.1.2

3. Error creating bean with the name ‘org. Springframework. Web. Servlet. MVC) method. The anRequestMappingHandlerAda

IsELIgnored = “false”

<%@ page contentType="text/html; charset=UTF-8" language="java" isELIgnored="false" %>Copy the code

5. Console output Chinese garble:

-Dfile.encoding=utf-8
Copy the code

Solution:

end~