preface

A few days ago, I had a whim to learn the source code of SpringMVC, so I decided to use IDEA to build a simple maven version of SSM case, that is, SpringMVC+Spring+MyBatis+Maven, because I created some small Spring demo before. Relevant software environment has been set up complete, thought builds an entry-level SSM project shouldn’t be hard. Who had thought the process encountered many strange questions, from the beginning to create a successful run it took me a whole afternoon (my nap ah ~ ~ ~), the last successful project long when I run out of breath, In order not to suffer from similar things in the future, I hereby write this article to record the construction process.

Software environment

Prepare the basic environment for building your project

Intellij IDEA: 2018.1.1

The JDK: 1.8

Maven: 3.6.0

Tomcat: 7.0 or above

After downloading and installing the software, you can configure JDK, Maven and Tomcat environment in idea software Settings. There are a lot of online information about this aspect, which will not be introduced in this article.

Create a project

After setting up the environment, open idea and click new-Project

Go to the Maven column and select the WebApp template because of the SpringMvc project to build

After filling in GroupId and ArtifactId, step by step next and finish

Once successfully created, you can see that the project has this directory structure

In addition to the configuration dependency pop.xml, there is also a folder SRC. The main directory of SRC provides a WebApp folder. Webapp contains a Web-INF folder that houses the front-end page files, as well as the web.xml file.

In addition to the directory structure provided by the template, in order for the project to run successfully, we need to add some folders to make the project directory structure look like this:

Database file

First, prepare the database file and initialize a record

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'user ID',
  `email` varchar(255) NOT NULL COMMENT 'User mailbox',
  `username` varchar(255) NOT NULL COMMENT 'User name',
  `role` varchar(255) NOT NULL COMMENT 'User identity',
  `mobile` varchar(50) DEFAULT ' ' COMMENT 'Mobile number',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf-8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1'.'[email protected]'.'xjt'.'root'.'15678635432');
Copy the code

The configuration file

pom.xml

<? 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 > com. XJT < / groupId > < artifactId > mvcDemo < / artifactId > <version> 1.0-snapshot </version> <packaging>war</packaging> <name>mvcDemo Maven Webapp</name> <! RELEASE</srping.version> <mybatis. Version >3.2.8</mybatis. Version > < slf4j version > 1.7.12 < / slf4j version > <log4 j. version > 1.2.17 < /logVersion 4 j. > < druid. Version > 1.0.9 < / druid version > < / properties > <! <dependencies> <! -- Unit test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <! --> <scope>test</scope> </dependency> <! Springframework </groupId> <artifactId> Spring-test </artifactId> <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${srping.version}</version> </dependency> <! -- Spring Framework package --> <! Mybatis </groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> The < version > 1.2.2 < / version > < / dependency > <! Mybatis --> <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.35 < / version > < / dependency > <! DBCP jar package; > <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> The < version > 1.4 < / version > < / dependency > <! JSTL </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> <! Alibaba </groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> </dependencies> <build> <! <plugins> <groupId>org.apache.maven.plugins</groupId> < artifactId > maven -- the compiler plugin < / artifactId > < version > 3.2 < / version > < configuration > <source> 1.8 < /source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code

Note: The following four configuration files are placed under the Resources folder

log4j.properties

# Log output level
log4j.rootLogger=debug,stdout,D,E

# set the log output console for stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
Output log to console. Default is system.out
log4j.appender.stdout.Target = System.out
# Set up to use flexible layouts
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
Define output formats flexibly
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%c (%rms)] - %m%n
Copy the code

jdbc.properties

driver=com.mysql.jdbc.Driver    
url=jdbc:mysql://localhost:3306/test? characterEncoding=utf8&useSSL=false    
The user name of the database
username=root      
# Database password, don't like me do not set
password=               
# define the initial connection number
initialSize=0    
Define the maximum number of connections
maxActive=20    
# define maximum free time
maxIdle=20    
# define minimum idle
minIdle=1    
# define the maximum wait time
maxWait=60000
Copy the code

applicationContext.xml

This is the core configuration file for Spring, including the configuration information for Spring combined with Mybatis and the data source

<? 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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <! Properties file --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/> </bean> <! -- Configure data source --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/> </bean> <! -- Mybatis and Spring integrate seamlessly without requiring mybatis configuration mapping file --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/ > <! --> <property name="typeAliasesPackage" value="com.xjt.model"/ > <! --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <! -- Mapper dynamic proxy development, scanning dao interface package --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <! SqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/ > <! <property name="basePackage" value="com.xjt.dao"/> </bean> <! -- Transaction management --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <! -- Database connection pool --> <property name="dataSource" ref="dataSource"/>
    </bean>

Copy the code

spring-mvc.xml

<? 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-3.0.xsd"> <! <context:component-scan base-package= <context:component-scan base-package="com.xjt"/ > <! -- Enable SpringMVC annotation mode --> < MVC :annotation-driven/> <! -- Static resource default servlet configuration --> < MVC :default-servlet-handler/> <! Configure the path to return to the view and identify the suffix as JSP file --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
Copy the code

web.xml

This file is not in the Resources, but in the Web-INF folder of webApp. It contains the following contents:

<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"> <display-name>mvcDemo</display-name> <! <welcome-file-list> <welcome-file>index.jsp</ welcome-file-list> <! Register ServletContext listener, create container object, And place the ApplicationContext object in the Application domain --> < Listener > <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <! <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <! <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> <! <servlet> <servlet-name> Springmvc </ servletname > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! / web-inf /<servlet-name>-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>
Copy the code

Run the project

With the above configuration files in place, we can actually try to start the project by commenting out the applicationContext.xml content before starting the project and then creating the runtime environment.

Click on Edit Configurations in the upper right corner of the idea…

Select Tomcat server-local,

Edit the project startup information, including the project name, JDK version, Tomcat, and port

Select Deployment, add Atifact, and select the second option, otherwise Tomcat runs with an error

After saving the file, start the project and enter http://localhost:8080 in the browser. The following information is displayed:

This is the contents of the index.jsp file, and since index.jsp is the launch page, the contents of the launch page are returned when the project starts

<html> <body> <h2>Hello World! </h2> </body> </html>Copy the code

Write the code

If the project can run, it shows that the configuration of our front-end controller is successful. The next step is to test whether the database can be accessed. First, create and code the basic class files.

Entity class: user.java

package com.xjt.model;

public class User {
    private long id;
    private String email;
    private String mobile;
    private String username;
    private String role;

    public long getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) { this.role = role; }}Copy the code

Dao file: IUserDao

package com.xjt.dao;

import com.xjt.model.User;

public interface IUserDao {

    User selectUser(long id);
}
Copy the code

Mapper file: userdao.xml

Located under the Resources-Mapper folder

<? 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"> <! -- set to provide SQL statement configuration for IUserDao interface methods --> < namespace="com.xjt.dao.IUserDao">

    <select id="selectUser" resultType="User" parameterType="long">
        SELECT * FROM user WHERE id = #{id}
    </select>

</mapper>
Copy the code

Service Interface: IUserService

package com.xjt.service;

import com.xjt.model.User;

public interface IUserService {

    public User selectUser(long userId);
}
Copy the code

UserServiceImpl

package com.xjt.service.impl;

import com.xjt.dao.IUserDao;
import com.xjt.model.User;
import com.xjt.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userService")
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserDao userDao;

    public User selectUser(long userId) {
        returnuserDao.selectUser(userId); }}Copy the code

Controller file: UserController

package com.xjt.controller;

import com.xjt.model.User;
import com.xjt.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/select")
    public ModelAndView selectUser() throws Exception {
        ModelAndView mv = new ModelAndView();
        User user = userService.selectUser(1);
        mv.addObject("user", user);
        mv.setViewName("user");
        returnmv; }}Copy the code

UserController defines a method, selectUser, that reads User information with id 1 and returns user.jsp from/User /select. User.jsp is located in the JSP folder of web-INF as follows:

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>user</title>
</head>
<body>
    id:${requestScope.user.id}<br/>
    email:${requestScope.user.email}<br/>
    username:${requestScope.user.username}<br/>
    role:${requestScope.user.role}<br/>
    mobile:${requestScope.user.mobile}<br/>
</body>
</html>
Copy the code

All writing is completed, cancel the applicationContext. Annotation symbols of the XML file, then open a project, after the success in the browser to enter http://localhost:8080/user/select

We successfully accessed the contents of the database.

At this point, the CONSTRUCTION of the SSM project is completed, in order to facilitate everyone to learn, I put the source code on github, there is a need for students to download, address: github.com/Taoxj/mvcDe…