技巧 方法 配置 错误 常用工具类

本文介绍了如何处理idea下载源代码失败的问题,以及Spring MVC中的forEach与stream操作区别,同时涵盖日期格式化、参数处理、视图重定向、数据持久化、API认证、加密与安全实践等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

技巧:

idea下载源代码失败解决:http://t.csdn.cn/oexTR

当前系统时间:http://t.csdn.cn/Jfbcn

new Date ().getTime ()  毫秒值
esProduct.setCreateTime (String.valueOf (new Date ().getTime ()));

forEach和stream里面的map有点想,不过不一样,foreach里面好像有bug?里面的数据和遍历的总数不一样

forEach里面不能嵌套forEach,只能操作第一个forEach的变量

【最好还是用stream里面的map】

id使用Long类型,判断是否相等的时候,不要用 == ,要用equals ! 其他的封装类和string一样,用equals判断好点,==判断是否同一个对象

springMVC:

如果参数有**@RequestBody** 注解,意思是接收返回的json数据并转换成参数的类型,用对象封装

因为前端要发json数据,所以要使用post请求

**mvc取不到 对象里面的list:**http://t.csdn.cn/7i2Ot http://t.csdn.cn/nRRMF

想把东西放容器里,类直接加 @Component 或者 方法加 @Bean

想让类的属性和配置文件绑定,直接加 @ConfigurationProperties(prefix = “配置文件里面的前缀”)。配置文件里,直接前缀加属性名就可以配置

常用的东西可以放redis或许ThreadLocal

redirect 和forward 后面跟的是Controller的映射地址【最好写域名形式,不然它跳转的是本地服务】

spring自带 json 时间格式化: 顺便设置时区

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

直接映射路径到页面,不用在Controller写空方法

@Configuration
public class MyConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/login.html").setViewName("login");
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/reg.html").setViewName("reg");
    }
}

转发页面传递数据:Model

重定向页面传递数据:RedirectAttributes

@PostMapping("/regist")
public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){


    // 校验参数是否出错
    if(result.hasErrors()){
        Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        //model.addAttribute("model",errors);
        redirectAttributes.addFlashAttribute("model",errors);
        // 校验出错,返回注册页【这个请求是post请求,要转发的reg.html请求是get请求,不能这样用】
        //return "forward:/reg.html";
        
        // 只要是自己服务器的,就可以传值
        return "redirect:http:auth.gulimall.com/reg.html";
    }

    // 注册

    return "redirect:/login.html";
}

后端传数据给 jsp或者thymeleaf,JavaScript取值

thymeleaf可以取到下面标签的值
<input type="hidden" th:value="${category}" id="ca"/>

js中写
var ca = document.getElementById("ca").getAttribute("value");

js模板字符串

var url = `/article/publish/${ca}`;

@RequestHeader

@GetMapping("/info")
public R userInfo(@RequestHeader(Constans.TokenHead) String token){


    System.out.println ("token: "+token);


    return userService.getUserInfo(token);
}

在系统启动的时候要执行什么东西,或许可以 写在配置类的构造函数里

@Configuration
public class GulimallSeckillSentinelConfig {

    public GulimallSeckillSentinelConfig() {

        WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
            @Override
            public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
                R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMessage());
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json");
                response.getWriter().write(JSON.toJSONString(error));
            }
        });
    }
}

常用方法:

判断字符串是否为空:

StringUtils.isBlank(String str) 判断某字符串是否为空或长度为0或由空白符(whitespace) 构成

包:import org.apache.commons.lang3.StringUtils;

springboot 注解开启事务

在配置类,或者启动类加上:
@EnableTransactionManagement

在需要加事务的类上加上:
@Transactional

md5加密:

params = DigestUtils.md5Hex(params);

包:import org.apache.commons.codec.digest.DigestUtils;

MD5加密的时候可以用加密盐,别人不知道这个盐就破解不了(盐最好不是固定的)

private static final String salt = "mszlu!@#";
password = DigestUtils.md5Hex(password + salt);

使用BCrypt加密,同一个密码,生成的密文不一样,很难被破解,但是又可以进行匹配,判断密码正确

BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// 加密
String encode = passwordEncoder.encode("12345");
// 判断是否匹配
boolean matches = passwordEncoder.matches("12345", encode);

批量复制两个类的同名属性

BeanUtils.copyProperties();    // spring框架的包

常见错误:

1.加了新的文件但是没反应,把生成的target目录删除再运行就可以了

配置:

导入devtools

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

导入Thymeleaf 的名称空间

<html lang="en"> 换成 <html lang="en" xmlns:th="http://www.thymeleaf.org">

mybatis的xml名称空间

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis配置文件-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Mapper的全类名,如com.xxxx.blog.dao.mapper.ArticleMapper">
</mapper>

mysql,datasourse配置

spring.datasource.url=jdbc:mysql://localhost:3306/zxg?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

常用工具类:

oss上传图片:

阿里云:https://www.bilibili.com/video/BV1np4y1C7Yf?p=62

七牛云

0.依赖

<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>[7.7.0, 7.7.99]</version>
</dependency>


<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.72</version>
</dependency>

1.工具类

import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


@Component
public class QiniuUtils {


    // 七牛云的外链域名
    public static  final String url = "blog.xpqly.love";


    @Value("${qiniu.accessKey}")
    private  String accessKey;
    @Value("${qiniu.accessSecretKey}")
    private  String accessSecretKey;


    public  boolean upload(MultipartFile file, String fileName){


        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传【这个是七牛云的空间名称】
        String bucket = "blogfdgsfg";
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
                Response response = uploadManager.put(uploadBytes, fileName, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        return false;
    }
}

2.在application.yaml中配置密钥

qiniu:
  accessKey: e1Sdc-_sV4C8wRNtzrVCeQvbd4JoW4Ox8uuR-FVP
  accessSecretKey: 3HttKo4z7x_H-sFxmHAidUN_yaPEvRbeV2qWFPzv

3.使用:uploadController

@RestController
@RequestMapping("upload")
public class UploadController {


    @Autowired
    private QiniuUtils qiniuUtils;


    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file){
        //原始文件名称 比如 aa.png
        String originalFilename = file.getOriginalFilename();
        //唯一的文件名称
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        //上传文件 上传到哪呢? 七牛云 云服务器 按量付费 速度快 把图片发放到离用户最近的服务器上
        // 降低 我们自身应用服务器的带宽消耗


        boolean upload = qiniuUtils.upload(file, fileName);
        if (upload){
            return Result.success(QiniuUtils.url + fileName);
        }
        return Result.fail(20001,"上传失败");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沛权

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值