搭建 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 文件



    UTF-8
    UTF-8
    
    1.8


    org.springframework.boot
    spring-boot-starter-web



    org.projectlombok
    lombok
    1.18.10



    org.springframework.boot
    spring-boot-devtools
    true
    true



    org.quartz-scheduler
    quartz
    2.2.1
    
        
            slf4j-api
            org.slf4j
        
    



    org.springframework
    spring-context-support



    junit
    junit
    4.12



    mysql
    mysql-connector-java
    5.1.39



    org.springframework.boot
    spring-boot-starter-websocket
    1.3.5.RELEASE



    org.apache.tomcat.embed
    tomcat-embed-jasper
    provided



    javax.servlet
    jstl



    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2





com.github.xiaoymin
knife4j-spring-boot-starter
2.0.4



    org.apache.httpcomponents
    httpcore
    4.4.5



    com.fasterxml.jackson.jaxrs
    jackson-jaxrs-json-provider
    2.3.1



    org.springframework.boot
    spring-boot-starter-freemarker



    org.springframework.boot
    spring-boot-configuration-processor
    true



    com.baomidou
    mybatis-plus-boot-starter
    3.5.1

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 [email protected]
 */
public class R extends HashMap {
   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 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

          
          
  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="主键属性名";

你可能感兴趣的:(SpringBoot,Java,intellij-idea,java,springboot)