搭建 SpringBoot + MyBatis-Plus + jsp 项目

记录一下自己搭建 SpringBoot + MyBatis-Plus + jsp 项目

application.yml配置

# 配置端口号
server:
  port: 8888
# 配置数据源
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&useSSL=true&autoReconnect=true&failOverReadOnly=false&characterEncoding=UTF-8
    password: admin
    username: root
  mvc:
    # 配置静态资源
    static-path-pattern: /static/**
    view:
      # 配置视图前缀
      prefix: /WEB-INF/
      # 配置jsp后缀
      suffix: .jsp
    pathmatch:
      matching-strategy: ant_path_matcher
​
# MyBatis-Plus 配置
mybatis-plus:
  # 配置别名
  type-aliases-package: 实体类包路径
  configuration:
    # 完整SQL日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
# 配置日志级别
loging:
  level:
    mapper接口路径: debug

pom.xml 文件

<!--配置字符集-->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!--jdk版本-->
    <java.version>1.8</java.version>
</properties>
​
<!-- Spring Boot SpringMVC 框架 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>
<!-- 热部署 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
    <scope>true</scope>
</dependency>
<!-- pom 文件 Spring Quartz 依赖 -->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
    <exclusions>
        <exclusion>
            <artifactId>slf4j-api</artifactId>
            <groupId>org.slf4j</groupId>
        </exclusion>
    </exclusions>
</dependency>
<!-- 该依赖必加, 里面有 sping 对 schedule 的支持 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>
<!-- Junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<!-- MySQL 连接驱动依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>
<!--websocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>1.3.5.RELEASE</version>
</dependency>
<!-- SpringBoot 支持 JSP 的依赖 -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<!-- JSP 页面使用 JSTL 标签 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<!--swagger2-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- 引入swagger-bootstrap-ui包 /doc.html-->
<!-- <dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.1</version>
</dependency> -->
<!--整合Knife4j Vue皮肤/doc.html-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
<!--HttpStatus  依赖-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.5</version>
</dependency>
<!--fastjson-->
<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.3.1</version>
</dependency>
<!-- Spring Boot Freemarker 模板 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--configuration 注解依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<!--Mybatis-Plus依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

config配置

MyFilter 解决跨域

package com.wx.config;
​
/**
 * @author iuxin
 * @date create in 18:33 2022/3/31
 * @apiNote
 */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
​
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
​
@Component
@WebFilter(urlPatterns = "/*",filterName = "myFilter")
public class MyFilter implements Filter {
​
    Logger loger = LoggerFactory.getLogger(MyFilter.class);
​
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
​
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
​
        HttpServletResponse response = (HttpServletResponse) sResponse;
​
        response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600"); //设置过期时间
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");
        chain.doFilter(sRequest, sResponse);
    }
    @Override
    public void destroy() {
    }
}

Swagger2Config 配置swagger2

package com.wx.config;
​
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
​
/**
 * @author iuxin
 * @date create in 16:22 2022/4/8
 * @apiNote
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
/**
 * 需要扫描的 Controller 的包路径
 */
     .select().apis(RequestHandlerSelectors.basePackage("需要扫描的controller"))
     .paths(PathSelectors.any())
     .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
        .title("用户管理系统")
        .description("用户管理系统\n")
        .termsOfServiceUrl("http://blog.csdn.net/saytime")
        .version("1.0")
        .build();
    }
}

MybatisPlusConfig 配置MyBatis-Plus

package com.wx.config;
​
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
​
/**
 * @author iuxin
 * @date create in 10:04 2022/4/12
 * @apiNote
 */
@Configuration
@MapperScan("需要扫描的mapper接口包")
public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置
     MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移
     除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new
                PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

MvcStaticMappingConfig 置静态资源路径的映射

package com.wx.config;
​
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
​
/**
 * @Description: 使用了@EnableMvc以后,导致静态资源路径无法访问
 * 重新配置加上静态资源路径的映射
 * @CreateDate: 2020/7/3 11:04
 */
@Configuration
public class MvcStaticMappingConfig implements WebMvcConfigurer {
    /**
     * 设置静态资源路径的映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 解决静态资源无法访问
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
// 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html", "doc.html",
                "document.html").addResourceLocations("classpath:/META-INF/resources/");
// 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

工具类 R

/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
​
package com.wx.util;
​
import org.apache.http.HttpStatus;
​
import java.util.HashMap;
import java.util.Map;
​
/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class R extends HashMap<String, Object> {
   private static final long serialVersionUID = 1L;
   
   public R() {
      put("code", 0);
      put("msg", "success");
   }
   
   public static R error() {
      return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
   }
   
   public static R error(String msg) {
      return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
   }
   
   public static R error(int code, String msg) {
      R r = new R();
      r.put("code", code);
      r.put("msg", msg);
      return r;
   }
​
   public static R ok(String msg) {
      R r = new R();
      r.put("msg", msg);
      return r;
   }
   
   public static R ok(Map<String, Object> map) {
      R r = new R();
      r.putAll(map);
      return r;
   }
   
   public static R ok() {
      return new R();
   }
​
   @Override
   public R put(String key, Object value) {
      super.put(key, value);
      return this;
   }
}

各项配置

  1. 启动类上加上注解,用来扫描mapper

    @MapperScan("mapper接口包路径")

    resources 文件夹下引入layui

  2. main包下创建webapp文件夹

    1. webapp文件夹下创建WEB-INF文件夹

      1. WEB-INF文件夹下创建 index.jsp文件

        1. jsp文件中引入layui

          <link rel="stylesheet" charset="UTF-8" href="static/layui/css/layui.css">
          <script src="static/layui/layui.js" type="text/javascript" charset="UTF-8"></script>
  3. IndexController 中配置 返回jsp页面的视图

    1. @ApiOperation(value = "首页")
      @GetMapping("/index")
      public ModelAndView index(){
          return new ModelAndView("index");
      }

实体类

@Data
@NoArgsConstructor // 无参构造器
@AllArgsConstructor // 有参构造器
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

ServiceImpl事务

@Transactional(rollbackFor = Exception.class)
throw new RuntimeException("抛出异常");

controller

// controller类上
@Api(value = "xxx接口", tags = {"xx操作接口"})
// 方法上
 @ApiOperation(value = "查询所有的xxx")

RESTful

1.HTTP动作
	GET---(select):查一项或多项
	GET/xxxID---获取一项
	POST---即添加数据
	PUT---更新整个对象
	DELETE---删除资源
	PATCH---更新个别
	HEAD---获取一个资源的元数据
 // 获取参数形参注解
@RequestParam("page") 
// GetMapping传参
@GetMapping("/表名s/{属性名}")
形参(@PathVariable("属性名")) // 类似于@Param

mappper.xml

// 返回主键
useGeneratedKeys="true" keyProperty="主键属性名";
  • 1
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页
评论

打赏作者

梦逝忘尘

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值