springboot搭建(常用)

1.引入依赖 parent

  <!--引入依赖 parent-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath />
    </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>
    <!--3.引入依赖 dependency-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
          <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--引入日志依赖 抽象层 与 实现层-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--打成war包移除tomcat-->
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>
        <!-- apache 工具类-->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!-- swagger2 配置 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.6</version>
        </dependency>
        <!--pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.12</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- 引入 redis 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--springsession-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId></dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId></dependency>
    </dependencies>

2.在yml中配置数据源和mybatis

############################################################## 配置数据源信息#############################################################spring:
datasource: # 数据源的相关配置
type: com.zaxxer.hikari.HikariDataSource # 数据源类型:HikariCP
driver-class-name: com.mysql.jdbc.Driver # mysql驱动
url: jdbc:mysql://localhost:3306/foodie-shop-dev?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
username: root
password: root
hikari:
connection-timeout: 30000 # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
minimum-idle: 5 # 最小连接数
maximum-pool-size: 20 # 最大连接数
auto-commit: true # 自动提交
idle-timeout: 600000 # 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
pool-name: DateSourceHikariCP # 连接池名字
max-lifetime: 1800000 # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
connection-test-query: SELECT 1
############################################################## mybatis 配置#############################################################mybatis:
type-aliases-package: com.imooc.pojo # 所有POJO类所在包路径
mapper-locations: classpath:mapper/*.xml # mapper映射文件
3.内置tomcat
server:
port: 8088
tomcat:
uri-encoding: UTF-8
max-http-header-size: 80KB

跨域访问

/**
 * 跨域访问控制权限交给nginx来控制
 */
@Configuration
public class CorsConfig {
    public CorsConfig() {

    }
    @Bean
    public CorsFilter corsFilter(){
        //添加配置信息
        CorsConfiguration config=new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:8080");
        config.setAllowCredentials(true);//是否允许使用cookie
        config.addAllowedMethod("*");//get post 是否允许放行
        config.addAllowedHeader("*");//设置允许的头文件
        //设置url
        UrlBasedCorsConfigurationSource urlSource =new UrlBasedCorsConfigurationSource();
        urlSource.registerCorsConfiguration("/**",config);
        //返回重新定义好的corsFilter
        return new CorsFilter(urlSource);
    }
}

BO数据验证
数据验证
1.
验证Bean:
2.

public class ValBean {
/**
* Bean Validation 中内置的 constraint
* @Null 被注释的元素必须为 null
* @NotNull 被注释的元素必须不为 null
* @AssertTrue 被注释的元素必须为 true
* @AssertFalse 被注释的元素必须为 false
* @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @Size(max=, min=) 被注释的元素的大小必须在指定的范围内
* @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
* @Past 被注释的元素必须是一个过去的日期
* @Future 被注释的元素必须是一个将来的日期
* @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
* Hibernate Validator 附加的 constraint
* @NotBlank(message =) 验证字符串非null,且长度必须大于0
* @Email 被注释的元素必须是电子邮箱地址
* @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
* @NotEmpty 被注释的字符串的必须非空
* @Range(min=,max=,message=) 被注释的元素必须在合适的范围内
*/
private Long id;

@Max(value=20, message="{val.age.message}")
private Integer age;
@NotBlank(message="{username.not.null}")
@Length(max=6, min=3, message="{username.length}")
private String username;

@NotBlank(message="{pwd.not.null}")
@Pattern(regexp="/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/", message="密码必须是6~10位数字和字母的组合")
private String password;
@Pattern(regexp="^((13[0-9])|(15[^4,\D])|(18[0,5-9]))\d{8}$", message="手机号格式不正确")
private String phone;

@Email(message="{email.format.error}")
private String email;}
1.
验证Controller:
2.
@Controller@RequestMapping(value = "/val")public class ValidateController {

@RequestMapping(value = "/val", method=RequestMethod.POST)
@ResponseBody
public LeeJSONResult val(@Valid @RequestBody ValBean bean, BindingResult result) throws Exception {
if(result.hasErrors()){
//如果没有通过,跳转提示
Map<String, String> map = getErrors(result);
return LeeJSONResult.error(map);
}else{
//继续业务逻辑
}
return LeeJSONResult.ok();
}
private Map<String, String> getErrors(BindingResult result) {
Map<String, String> map = new HashMap<String, String>();
List<FieldError> list = result.getFieldErrors();
for (FieldError error : list) {
System.out.println("error.getField():" + error.getField());
System.out.println("error.getDefaultMessage():" + error.getDefaultMessage());
map.put(error.getField(), error.getDefaultMessage());
}
return map;
}}

定义头像保存地址

//        String fileSpace = IMAGE_USER_FACE_LOCATION;
        String fileSpace = fileUploadResources.getImageUserFaceLocation();
        //在路径下增加每一个userId,用于为每一个用户上传
        String uploadPathPrefix = File.separator + userId;
        //开始文件上传
        if (file != null) {
            FileOutputStream outputStream = null;
            try {
                InputStream inputStream = file.getInputStream();
                String fileName = file.getOriginalFilename();
                if (StringUtils.isNotBlank(fileName)) {
                    //文件重命名
                    String fileNameArr[] = fileName.split("\\.");
                    //获取文件后缀名
                    String suffix = fileNameArr[fileNameArr.length - 1];
                    if(!suffix.equalsIgnoreCase("png")&&
                            !suffix.equalsIgnoreCase("jpg")&&
                            !suffix.equalsIgnoreCase("jpeg")){
                        return IMOOCJSONResult.errorMsg("上传图片格式不正确");
                    }
                    // 文件名称重组,覆盖上传
                    String newFileName = "face-" + userId + "." + suffix;
                    //上传头像最终保存的位置
                    String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
                    File outFile = new File(finalFacePath);
                    //判断上层文件夹不为空
                    if (outFile.getParent() != null) {
                        outFile.getParentFile().mkdirs();
                    }
                    //文件输出保存到目
                    outputStream = new FileOutputStream(outFile);
                    IOUtils.copy(inputStream, outputStream);
                    //用于提供给web访问的地址
                    uploadPathPrefix+=("/" +newFileName);
                } else {
                    return IMOOCJSONResult.errorMsg("文件名不能为空");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (outputStream!=null){
                    try {
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            return IMOOCJSONResult.errorMsg("上传图片不能为空");
        }
        //保存头像地址
        String imageSeverUrl=fileUploadResources.getImageSeverUrl();
        //防止浏览器缓存,加入时间戳
        String imageRealUrl=imageSeverUrl+uploadPathPrefix+"?t="+ DateUtil.getCurrentDateString();
        Users userResult=centerUserService.updateUserFace(userId,imageRealUrl);

        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(packageUserVO(userResult)), true);//设置cookie
        // 后续要改增加令牌token,会整合进redis 分布式回话

附件下载

@RestController
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    
    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件的后缀名为:" + suffixName);
            // 设置文件存储路径
            String filePath = "D://Downloads/";
            String path = filePath + fileName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }


    @GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "2019092715213111122.png";// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File("D://Downloads/2019092715213111122.png");
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值