当前位置: 首页 > news >正文

通用代码自用

多文件上传

public int save(Role role, @RequestParam("nfile") MultipartFile nfile, HttpServletRequest request) {System.out.println(nfile.getOriginalFilename());String path = request.getSession().getServletContext().getRealPath("/upload");File file = new File(path);if (!file.exists()) {file.mkdir();}String filename = System.currentTimeMillis() + nfile.getOriginalFilename();try {nfile.transferTo(new File(file, filename));} catch (IOException e) {e.printStackTrace();}return roleService.save(role);}

分页

package com.zb.util;import java.util.List;public class PageUtil<T> {/*当前页*/private Integer currentPage = 1;/*每页的条数*/private Integer pageSize = 2;//总记录数private Integer totalCount;//总页数private Integer totalPageCount;// 分页数据private List<T> data;public Integer getCurrentPage() {return currentPage;}public void setCurrentPage(Integer currentPage) {this.currentPage = currentPage;}public Integer getPageSize() {return pageSize;}public void setPageSize(Integer pageSize) {this.pageSize = pageSize;}public Integer getTotalCount() {return totalCount;}public void setTotalCount(Integer totalCount) {this.totalCount = totalCount;}public Integer getTotalPageCount() {totalPageCount = totalCount % pageSize == 0? totalCount / pageSize : totalCount / pageSize + 1;return totalPageCount;}public void setTotalPageCount(Integer totalPageCount) {this.totalPageCount = totalPageCount;}public List<T> getData() {return data;}public void setData(List<T> data) {this.data = data;}
}

跨域配置

package com.zb.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter() {// 1. 创建CORS配置对象CorsConfiguration config = new CorsConfiguration();// 允许的源(生产环境建议指定具体域名,而非*)config.addAllowedOriginPattern("*");// 允许携带凭证(cookie等)config.setAllowCredentials(true);// 允许的HTTP方法config.addAllowedMethod("*");// 允许的请求头config.addAllowedHeader("*");// 暴露的响应头(前端可以获取的额外响应头)config.addExposedHeader("token");// 预检请求的缓存时间(秒)config.setMaxAge(3600L);// 2. 创建URL匹配源UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();// 对所有路径应用CORS配置source.registerCorsConfiguration("/**", config);// 3. 创建并返回CORS过滤器return new CorsFilter(source);}
}

数据库连接

    url: jdbc:mysql://127.0.0.1:3306/《数据库》?useUnicode=true&autoReconnect=true&autoReconnectForPools=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai

Redis使用FastJson序列化配置

package com.zb.config;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;import java.nio.charset.Charset;/*** Redis使用FastJson序列化** @author sg*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");private Class<T> clazz;static {ParserConfig.getGlobalInstance().setAutoTypeSupport(true);}public FastJsonRedisSerializer(Class<T> clazz) {super();this.clazz = clazz;}@Overridepublic byte[] serialize(T t) throws SerializationException {if (t == null) {return new byte[0];}return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);}@Overridepublic T deserialize(byte[] bytes) throws SerializationException {if (bytes == null || bytes.length <= 0) {return null;}String str = new String(bytes, DEFAULT_CHARSET);return JSON.parseObject(str, clazz);}protected JavaType getJavaType(Class<?> clazz) {return TypeFactory.defaultInstance().constructType(clazz);}
}

Redis配置

package com.zb.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);// 使用StringRedisSerializer来序列化和反序列化redis的key值template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer);// Hash的key也采用StringRedisSerializer的序列化方式template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer);template.afterPropertiesSet();return template;}
}

http://www.lryc.cn/news/610192.html

相关文章:

  • [硬件电路-156]:什么是电信号? 电信号的本质:电信号是随时间变化的电压或电流。本质是电子运动表征信息,兼具能量传输与信息编码传递功能。
  • 开源网页生态掘金:从Bootstrap二次开发到行业专属组件库的技术变现
  • 多线程(一)
  • 【Spring AI快速上手 (二)】Advisor实现对话上下文管理
  • 【计算机网络 | 第2篇】计算机网络概述(下)
  • 如何使用 DBeaver 连接 MySQL 数据库
  • 移动端 WebView 视频无法播放怎么办 媒体控件错误排查与修复指南
  • SAP-ABAP:ABAP Open SQL 深度解析:核心特性、性能优化与实践指南
  • 深入剖析Java Stream API性能优化实践指南
  • Mybatis 简单练习,自定义sql关联查询
  • 卸油管链接检测误检率↓76%:陌讯多模态融合算法实战解析
  • Dbeaver数据库的安装和使用(保姆级别)
  • 基于FAISS和Ollama的法律智能对话系统开发实录-【大模型应用班-第5课 RAG技术与应用学习笔记】
  • Ubuntu系统VScode实现opencv(c++)图像一维直方图
  • 机器学习【六】readom forest
  • 微服务配置管理:Spring Cloud Alibaba Nacos 实践
  • 电子电气架构 ---智能电动汽车嵌入式软件开发过程中的block点
  • Nginx服务做负载均衡网关
  • 36.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--缓存Token
  • FPGA学习笔记——简单的乒乓缓存(RAM)
  • 飞算JavaAI需求转SpringBoot项目沉浸式体验
  • android内存作假通杀补丁(4GB作假8GB)
  • labview连接PLC的三种方式
  • 设计模式(一)——抽象工厂模式
  • ES集群规划与调优
  • 进程间通信:管道与共享内存
  • 移动前后端全栈项目
  • 读写分离有那些坑?
  • 16.8 华为昇腾CANN架构深度实战:3大核心引擎解析与性能优化216%秘籍
  • 手搓TCP服务器实现基础IO