从零开始使用spring boot搭建前后端分离框架(一、WEB框架的搭建)

时间:2020-03-26
本文章向大家介绍从零开始使用spring boot搭建前后端分离框架(一、WEB框架的搭建),主要包括从零开始使用spring boot搭建前后端分离框架(一、WEB框架的搭建)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

公司一个新项目,不想使用之前的老框架,准备搭建一个新的,记录下以便后续回顾!

话不多说,开始第一步!使用idea创建new project创建一个项目

 

设置包名

 

 

设置依赖项目:如果是web项目就选web,不是可以省略,这里我们使用jdbc做连接池,使用mybatis做持久层框架

 

 

设置项目名称:

 

 

 finish!

 

 

项目创建好了,接下来进行第二步

配置端口,数据库以及mybatis配置文件application.properties:

# 端口
server.port=9090
# 管理端点,上下文路径
server.servlet.context-path=/fzf
# 会话超时(秒)
server.servlet.session.timeout=10000

#数据库配置
spring.datasource.url=jdbc:mysql://rm-bp14to8mn841swfk6so.mysql.rds.aliyuncs.com:3306/fzf?Unicode\=true&characterEncoding\=utf-8&ssl=true&ssl\=true
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456



#配置Controller层返回JSP
#配置 前后缀
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

#扫描实体类位置
mybatis.typeAliasesPackage=com.fzf.web.model
#扫描mybatis的xml文件
mybatis.mapperLocations=classpath:mapper/*.xml 

# 定义静态资源文件位置
spring.resources.static-locations=classpath:/META-INF/resource/, classpath:/resource/, classpath:/static/
##表示访问该路径时代表请求静态资源,用户可以直接访问该请求路径中的静态资源
spring.mvc.static-path-pattern=/static/**


#打印sql日志 , 使用mybatis自带的方法,会将sql的返回结果也打印出来
#mybatis.configuration.log-impl= org.apache.ibatis.logging.stdout.StdOutImpl

 配置pom.xml文件中的dependencies依赖项和plugins代码生成器generator

<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.fzf</groupId>
<artifactId>web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>web</name>
<description>Pure back-end interface -Spring boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>


<!--mysql连接驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.5</version>
</dependency>

<!-- json -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!--pagehelper 分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>

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

<configuration>
<executable>true</executable>
</configuration>
</plugin>

<!--要打包了这个生成代码要禁止掉,本地开发开启-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<!--配置这个依赖主要是为了等下在配置mybatis-generator.xml的时候可以不用配置classPathEntry这样的一个属性,避免代码的耦合度太高-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!--允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 自动生成的配置 -->
<configurationFile>src/main/resources/generator/mybatis-generator.xml</configurationFile>
</configuration>
</plugin>
</plugins>
</build>

</project>

 配置maven:

 第三步使用拦截器打印请求入参,和跨域问题:

首先配置拦截器:

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CommonInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

  拦截请求,配置跨域和打印请求

package com.fzf.web.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 配置公共拦截器,将每次请求的入参打印在日志上
 * 基于shiro允许跨域
 */
public class CommonInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);
    /**
     * 配置公共request路径basePath
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //允许跨域,不能放在postHandle内
        response.setHeader("Access-Control-Allow-Origin", "*");
        if (request.getMethod().equals("OPTIONS")) {
            response.addHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
        }

        /**
        * 对来自后台的请求统一进行日志处理
        */
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        Map<String, String[]> map=request.getParameterMap();
        System.out.println("---------------------------------------------------------------------------------------------------");
        logger.info("url--"+url);
        logger.info("method--"+method);
        logger.info("request-params--");
        map.forEach((k,v) ->{
            logger.info("    " + k+": "+v[0]);
        });
        System.out.println("---------------------------------------------------------------------------------------------------");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

 第四步创建mybatis-generator.xml配置文件:并生成表中数据:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--加载配置文件,为下面读取数据库信息准备-->
    <properties resource="application.properties"/>

    <!-- targetRuntime = MyBatis3 会生成 Selective结尾的方法, MyBatis3Simple 不会生成-->
    <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat">

        <!-- 阻止生成自动注释 -->
        <commentGenerator>
            <property name="javaFileEncodings" value="UTF-8"/>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库链接地址账号密码,这里由于我使用的是根据开发和生产分离的配置文件,所以这里直接写上了-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://rm-bp14to8mn841swfk6so.mysql.rds.aliyuncs.com:3306/fzf?useUnicode=true&characterEncoding=utf-8"
                        userId="root"
                        password="123456>
        </jdbcConnection>

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

        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.fzf.web.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--生成Dao类存放位置-->
        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.fzf.web.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--生成对应表及类名 去掉Mybatis Generator生成的一堆 example-->
        <table tableName="t_student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>

    </context>
</generatorConfiguration>

 之前在pom.xml文件中配置了pulgs,在这个地方会有下面的依赖,双击mybatis-generator:generate执行,就可以了

 

 

 

 

 

 现在实体和mapper文件生成了,开始书写service和controller层

 

@Service
@Transactional
public class StudentService {
    @Resource
    private StudentMapper studentMapper;

    /**
     * @param userId
     * @return
     */
    public Student getEntity(int userId) {
        return studentMapper.selectByPrimaryKey(userId);
    }

}

  

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

    @Resource
    private StudentService studentService;

    /**
     * 用户信息
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("info")
    public ResponseVO info(@RequestParam(value = "userId") int userId){
        return new ResponseVO(studentService.getEntity(userId));

    }
}

在启动项目之前,配置扫描mapper,

@SpringBootApplication
@MapperScan("com.fzf.web.mapper")//扫描mapper
public class WebApplication {

    public static void main(String[] args) {
            SpringApplication.run(WebApplication.class, args);
    }

}

  

debug启动项目:

 

 

 等待启动成功之后: 

 

 

 在浏览器中访问链接:

http://localhost:9090/fzf/user/info?userId=1

链接为IP + 端口号 +项目路径 + controller映射路径

 

 

 

 

 结果: 

 

 

 控制台:

 

$flag 上一页 下一页