A person’s life, usually to their own efforts, even if copied the life of others, there are always some things, can not be copied. Don’t worry too much about other people’s life, live your own life is fundamental. To understand the life conditions of many people in the world, we can learn from them and find a suitable model for ourselves. – xiao colchicine

Before the start of…

The theme of this chapter is the entry point, and we slowly expand and deepen at a point. The reason why we do not talk about new things at the beginning is that past experience is equally important. It is because of past experience that newer and better ideas emerge, and new ideas help us improve. Also, with comparison, we can more intuitively feel whether the new scheme is faster and better, and which advantages and disadvantages have obvious changes. Simple does not mean easy, only hands-on practice, to truly understand.

Therefore, this chapter is to review how to use Spring MVC to build a commonly used Maven-based Web project, and finally integrate Mybatis to display data using MySQL database, while MySQL, I use docker image installation, not direct installation.

For Windows, boot2Docker is used, download address, version: 1.8.0 (this version is the last version, and the project will be migrated to Docker ToolBox later. For ToolBox, I have downloaded the latest attempt of 1.11.2, but I cannot start the virtual machine.

Docker is used for Ubuntu 16.04

Environment version

Tomcat: 6.0.33 tomcat: 6.0.33 tomcat: 6.0.33 tomcat: 6.0.33 tomcat: 6.0.33 tomcat: 6.0.33 5.5.45 Spring MVC: 4.2.6.RELEASE MyBatis: 3.2.5 MyBatis - Spring: 1.2.2 tomcat-jdbc: 7.0.52 mysql-connector- Java: 5.1.39Copy the code

Docker running mysql

Docker pull mysql:5.5.45 docker run -d -p 3306:3306 mysql:5.5.45 -e MYSQL_ROOT_PASSWORD=123456Copy the code

Setting up a Maven project

Package name: com. HJF. Boot. Demo. Boot_mybatis_mvcCopy the code

New pom. XML

    <packaging>war</packaging>

    <properties>
        <jdbc.driver.version>5.1. 39</jdbc.driver.version>
        <tomcat-jdbc.version>7.052.</tomcat-jdbc.version>
        <mybatis.version>3.2. 5</mybatis.version>
        <mybatis-spring.version>1.22.</mybatis-spring.version> </properties> <dependencies> <! -- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <! -- mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <! -- connection pool --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>${tomcat-jdbc.version}</version> <scope>runtime</scope> </dependency> <! -- jdbc driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${jdbc.driver.version}</version> <scope>runtime</scope> </dependency> </dependencies> <build> <pluginManagement> <plugins> <! -- Compiler plugin, Plugins </groupId> <artifactId> Maven-compiler-plugin </artifactId> <version>3.51.</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <showWarnings>true</showWarnings> </configuration> </plugin> <! -- War package plugin, Plugins </groupId> <artifactId> Maven-war-plugin </artifactId> <version>2.6</version>
                <configuration>
                    <warName>mickjoust</warName>
                </configuration>
            </plugin>
        </plugins>
        </pluginManagement>
    </build>
Copy the code

Change to a Web project

Adding Web Support

First, create webApp folder IDEA under SRC /main/ and click File – >Project Structure – >Modules – > Boot-Mybatis – MVC to add web Project support, as shown in the figure:

Add Spring context support

Add applicationContext. XML and application.properties files under SRC /main/resources and MVC Severlet configuration file under web-INF/spring-mvc. XML

// applicationContext.xml

<! Auto-register bean using annotation -->
    <context:component-scan base-package="com.hjf.boot.demo.boot_mybatis_mvc">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
    <! --<aop:aspectj-autoproxy proxy-target-class="true" />-->

    <! Properties properties file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="fileEncoding" value="UTF-8" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="locations">
            <list>
                <value>classpath:/config/app.properties</value>
            </list>
        </property>
    </bean>

    <! Identify specific beans separately -->
    <import resource="classpath:/spring/app-config.xml" />

    <! -- MyBatis configuration -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <! -- Automatically scan entity directory, save manual Configuration in configuration. XML -->
        <property name="typeAliasesPackage" value="com.hjf.boot.demo.boot_mybatis_mvc.domain" />
        <! -- Explicitly specify Mapper file location -->
        <property name="mapperLocations" value="classpath:/mybatis/*Mapper.xml" />
    </bean>
    <! BasePackage (@mapper);
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hjf.boot.demo.boot_mybatis_mvc" />
        <property name="annotationClass" value="com.hjf.boot.demo.boot_mybatis_mvc.dao.Mapper"/>
    </bean>// There are many profile configurations.Copy the code
// application.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=UTF-8
jdbc.username=test
jdbc.password=123456
jdbc.pool.maxIdle=2
jdbc.pool.maxActive=5
Copy the code
// spring-mvc.xml<! --> < AOP: aspectJ-autoproxy proxy-target-class="true" />

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true"> <! - will set the default encoding to utf-8 StringHttpMessageConverter8 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/> </bean> <! - will Jackson2HttpMessageConverter output is set to the default formattrue -->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <! -- Velocity configuration --> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="/WEB-INF/views/" />
        <property name="velocityProperties">
            <props>
                <prop key="input.encoding">UTF-8</prop>
                <prop key="output.encoding">UTF-8</prop>
                <prop key="contentType">text/html; charset=UTF-8</prop> </props> </property> </bean> <! -- Velocity view parser --> <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="contentType" value="text/html; charset=UTF-8" />
        <property name="prefix" value="" />
        <property name="suffix" value=".vm" />
        <property name="order" value="0" />
        <property name="dateToolAttribute" value="dateTool" />
        <property name="numberToolAttribute" value="numberTool" />
        <property name="requestContextAttribute" value="rc" />
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSpringMacroHelpers" value="true"/ > <! --<property name="layoutUrl" value="/page/index.vm"/>--> </bean> <! -- Container DefaultServletHandler handles all static content and urls without RequestMapping --> < MVC:default-servlet-handler /> <! Static resource configuration --> < MVC: Resources location="/static/" mapping="/static/**" cache-period="864000"/ > <! -- bean --> <bean id="loginInterceptor" class="com.hjf.boot.demo.boot_mybatis_mvc.interceptor.LoginInterceptor"/ > <! < MVC :interceptors> < MVC :interceptor> < MVC :mapping path="/ * *" />
            <mvc:exclude-mapping path="/favicon.ico" />
            <mvc:exclude-mapping path="/WEB-INF/views/error/**" />
            <ref bean="loginInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>
Copy the code

Also click File – >Project Structure – >Modules – > boot-Mybatis – MVC to add spring support, as shown in the picture:

After adding spring support, the velocity configuration will be used in this section. This article focuses on the configuration of Spring MVC and MyBatis.

Creating a static folder

Create a static folder in SRC /main/webapp/WEB-INF/ and copy the bootstrap and jquery folders.

The test model

public class Info {

    private Long id;
    private String name;
    private Integer age;

    // omit the get and set methods
}
Copy the code

Custom annotation @mapper

Mapper: Mybatis 3.4.0: @mapper: Mybatis 3.4.0: Mybatis 3.4.0

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Component
public @interface Mapper {
    String value(a) default "";
}
Copy the code

mybatis dao

@Mapper
public interface ShowDao {

    List<Info> findByAge(Integer age);
}
Copy the code

xml mapper

Using XML, under the SRC/main/resources/new mybatis/ShowDaoMapper XML file

<! -- Namespace must point to Dao interface
<mapper namespace="com.hjf.boot.demo.boot_mybatis_mvc.dao.ShowDao">

    <select id="findByAge" parameterType="int" resultType="Info">
        SELECT
        id,
        name,
        age
        FROM info
        WHERE age = #{age}
    </select>

</mapper>
Copy the code

Insert data using SQL

SQL > insert test into mysql;

CREATE TABLE `info` (
`id`  bigint NOT NULL AUTO_INCREMENT ,
`name`  varchar(255) NULL ,
`age`  int NULL ,
PRIMARY KEY (`id`)
);

INSERT INTO info (name,age) VALUES ('mick'.'20');
INSERT INTO info (name,age) VALUES ('mick1'.'20');
INSERT INTO info (name,age) VALUES ('mickjoust1'.'21');
INSERT INTO info (name,age) VALUES ('joust'.'22');
Copy the code

Start the

Check the homepage: http://localhost:8080 to check the database data: http://localhost:8080/show

summary

This chapter is too long to configure things, and some code is omitted in the article. The detailed code can be viewed in the example. Today, configuring Spring MVC is still a lot of work, with various configurations and associations. However, the pointcut is very necessary. After you use Spring Boot, you will know the advantages and benefits of simplification. The key points of this chapter are: Spring MVC servlet configuration, Spring Context configuration, Spring MVC maven dependency, summary found that build a project, if you are not familiar with it. It will take a lot of time, even if there is ready-made, I suggest you start more, their own operation, will experience the taste. This is the end of this chapter, as for the principle of architecture, I personally prefer to go into the last in-depth discussion, the previous chapters will be actual combat, first action again.


Example address: boot-mybatis- MVC


page 160 of 366 in chapter 2016