SpringBoot integrates the use of mybatis and SpringMVC

SpringBoot is not a new framework. It can be considered as a streamlined version of Spring. In layman's terms, it encapsulates the usual configuration file information into a jar package to save time.

Generally, we need to copy a lot of configuration files to build a framework. After using SpringBoot, you will find it really simple.

Click to enter the project on my code cloud or directly enter https://gitee.com/it_qin/DemoSpringBoot.git

This is a MAVEN project, it is not managed by MAVEN

Search and download the jar configured in pom.xml online and add it to your project. Add the class files in my project,

Copy the configuration file to your project and it will be OK.

Project structure
Write picture description here

application.properties

spring.datasource.url=jdbc:mysql://localhost/dapeng?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#有配置文件需要扫描mybatis映射文件
#mybatis.mapper-locations=classpath:/mapper/*Mapper.xml

mybatis.type-aliases-package=com.example.myproject.domain

#config-location: classpath:mybatis/mybatis-config.xml
#springmvc视图的配置 现在以java类的形式配置了[SpringMvcConfig类]。
#spring.mvc.view.prefix=/WEB-INF/
#spring.mvc.view.suffix=.jsp

SpringMvcConfig

package com.example.myproject.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * <p>
 *     继承WebMvcConfigurerAdapter类可重写springboot中的默认配置。
 *
 * </p>[2018/2/7]
 *
 * @author HongKun.Qin
 */
@Configuration
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
    
    

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        System.out.print("spring-mvc");
        registry.jsp("/WEB-INF/", ".jsp");
    }


}

HelloWorldController

package com.example.myproject.controller;

import com.example.myproject.domain.User;
import com.example.myproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * <p>如果返回的类型不是ModelAndView,则[@RestController注解相当于@ResponseBody + @Controller合在一起的作用。]</p>[2018/2/6]
 *
 * @author HongKun.Qin
 */
@RestController
public class HelloWorldController {
    
    
    @Autowired
    private UserService userService;

    /**
     * <h4>功能:[跳转index1界面 ][2018/2/7 13:40][创建人: HongKun.Qin]</h4>
     * <h4></h4>
     *
     * @param * @param null :
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index() {

        ModelAndView mav = new ModelAndView();

        mav.setViewName("index1");

        return mav;
    }

    /**
     * <h4>功能:[ 返回json格式][2018/2/7 13:42][创建人: HongKun.Qin]</h4>
     * <h4></h4>
     *
     * @param * @param null :
     * @return
     */
    @RequestMapping("/json")
    public String indexJson() {

        List<User> users = userService.getUserList();

        users.forEach(value ->
                System.out.println(String.format("学员信息 %s,%s", value.getUser_id(), value.getUserAccount()))
        );//需要jdk1.8才可以使用这种方式。

        return "hello";
    }

    /**
     * <h4>功能:[跳转index2界面 ][2018/2/7 13:40][创建人: HongKun.Qin]</h4>
     * <h4>加这个的目的是 如果同时存在index.jsp和index.ftl会默认跳转index.ftl</h4>
     *
     * @param * @param null :
     * @return
     */
    @RequestMapping("/index2")
    public ModelAndView index2() {

        ModelAndView mav = new ModelAndView();

        mav.setViewName("index");

        return mav;
    }
}

UserDaoMapper

package com.example.myproject.dao;

import com.example.myproject.domain.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>使用的是无配置注解形式,配置文件形式在application.properties中配置扫描就可以 已经注释掉。</p>[2018/2/6]
 *
 * @author HongKun.Qin
 */
public interface UserDaoMapper {
    
    
    @Select("select * from user where userAccount = '18888320271'")
    List<User> selectUserList();
}

User

package com.example.myproject.domain;

/**
 * <p></p>[2018/2/6]
 *
 * @author HongKun.Qin
 */
public class User {
    
    
    private String user_id;
    private String userAccount;

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }

    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

}

UserService

package com.example.myproject.service;

import com.example.myproject.domain.User;

import java.util.List;

/**
 * <p></p>[2018/2/6]
 *
 * @author HongKun.Qin
 */
public interface UserService {
    
    
    List<User> getUserList();
}

UserServiceImpl

package com.example.myproject.service.impl;

import com.example.myproject.dao.UserDaoMapper;
import com.example.myproject.domain.User;
import com.example.myproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>1</p>[2018/2/6]
 *
 * @author HongKun.Qin
 */
@Service
public class UserServiceImpl implements UserService {
    
    
    @Autowired
    UserDaoMapper userDaoMapper;//使用idea打开后这会报错,不用管正常使用。

    @Override
    public List<User> getUserList() {
        return userDaoMapper.selectUserList();
    }
}

DemoApplication

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

/**
 * 需要注意的是这个类要放在所有类的上级,因为程序运行之后初始化这个类下面的所有包。
 */
@SpringBootApplication
@MapperScan("com.example.myproject.dao")//扫描dao层接口
public class DemoApplication{
    
    
    /*运行这个方法就能启动服务了。*/
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

index.ftl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>界面</title>
<#--<link rel="stylesheet" type="text/css" href="index.css" />-->
<#--<script type="text/javascript"> </script>-->
</head>
<body>
<div>
    spring-mvc和spring-boot整合测试。 ftl
</div>
<#--<script type="text/javascript"> </script>-->
</body>

</html>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    if (path.equals("/")) {
        path = "";
    }
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <%--<link rel="stylesheet" type="text/css" href="<%=path%>/.css">--%>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <%--<script type="text/javascript" ></script>--%>
    <title></title>
</head>
<body>
<h3>spring-mvc和spring-boot整合测试。 jsp</h3>
<%--<script type="text/javascript" ></script>--%>
</body>
</html>

index1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    if (path.equals("/")) {
        path = "";
    }
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <%--<link rel="stylesheet" type="text/css" href="<%=path%>/.css">--%>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <%--<script type="text/javascript" ></script>--%>
    <title></title>
</head>
<body>
    <h3>spring-mvc和spring-boot整合测试。 jsp</h3>
<%--<script type="text/javascript" ></script>--%>
</body>
</html>

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.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--spring-boot-starter :核心模块,包括自动配置支持、日志和YAML;-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--spring-boot-starter-test :测试模块,包括JUnit、Hamcrest、Mockito。-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--pom.xml中添加支持web的模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

        <!-- tomcat 的支持.[不加jsp界面无法解析]-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-tomcat</artifactId>

           <!-- <scope>provided</scope>-->

        </dependency>

        <dependency>

            <groupId>org.apache.tomcat.embed</groupId>

            <artifactId>tomcat-embed-jasper</artifactId>

           <!-- <scope>provided</scope>-->

        </dependency>
        <!-- ftl文件需要导入的jar -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

mysql run file

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `user_id` varchar(32) NOT NULL,
  `userAccount` varchar(13) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('ewkdrjde', '18888800000');
INSERT INTO `user` VALUES ('jadsfe25', '18888888888');
INSERT INTO `user` VALUES ('jserda32', '18888320271');

“`

If you don’t understand, you can comment below and everyone can make progress together.

Guess you like

Origin blog.csdn.net/Qin_HongKun/article/details/79279024