首页
归档
留言
友链
广告合作
壁纸
更多
美女主播
Search
1
博瑞GE车机升级/降级
5,574 阅读
2
Mac打印机设置黑白打印
4,885 阅读
3
修改elementUI中el-table树形结构图标
4,862 阅读
4
Mac客户端添加腾讯企业邮箱方法
4,645 阅读
5
intelliJ Idea 2022.2.X破解
4,316 阅读
Java
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
登录
/
注册
Search
标签搜索
Spring Boot
Java
Spring Cloud
Mac
MyBatis
WordPress
Nacos
Spring Cloud Alibaba
MacOS
Mybatis-Plus
Typecho
jQuery
Java Script
asp.net
MySQL
IntelliJ IDEA
微信小程序
Sentinel
UniApp
Oracle
Laughing
累计撰写
610
篇文章
累计收到
1,425
条评论
首页
栏目
Java
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
页面
归档
留言
友链
广告合作
壁纸
美女主播
搜索到
93
篇与
的结果
2019-07-28
Spring Boot热部署
但当服务功能一多,启动速度缓慢时,还是配置个热部署比较方便。在SpringBoot中,只需要加入一个spring-boot-devtools即可。<!-- 增加热部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>若不生效,可试着在打包工具spring-boot-maven-plugin下的configuration加入true看看,具体配置项如下:<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build>
2019年07月28日
1,413 阅读
0 评论
0 点赞
2019-07-28
Spring Boot配置跨域
同源策略很多人对跨域有一种误解,以为这是前端的事,和后端没关系,其实不是这样的,说到跨域,就不得不说说浏览器的同源策略。同源策略是由Netscape提出的一个著名的安全策略,它是浏览器最核心也最基本的安全功能,现在所有支持JavaScript的浏览器都会使用这个策略。所谓同源是指协议、域名以及端口要相同。同源策略是基于安全方面的考虑提出来的,这个策略本身没问题,但是我们在实际开发中,由于各种原因又经常有跨域的需求,传统的跨域方案是JSONP,JSONP虽然能解决跨域但是有一个很大的局限性,那就是只支持GET请求,不支持其他类型的请求,而今天我们说的CORS(跨域源资源共享)(CORS,Cross-origin resource sharing)是一个W3C标准,它是一份浏览器技术的规范,提供了Web服务从不同网域传来沙盒脚本的方法,以避开浏览器的同源策略,这是JSONP模式的现代版。在Spring框架中,对于CORS也提供了相应的解决方案,今天我们就来看看SpringBoot中如何实现CORS。前端请求<!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <script src="jquery.min.js"></script> </head> <body> <div id="myDiv"></div> <script> $(document).ready(function () { $.ajax({ url: "http://localhost:8080/CrossOrigin", type:"post", async: false, success:function(data){ $("#myDiv").html(data); } }); }); </script> </body> </html>配置后端/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class CorsController { /** * 方法配置跨域 * @return String */ @RequestMapping("/CrossOrigin") public String crossOrigin(){ return "crossOrigin"; } }打开前端页面,我们可以看一下,报错信息如下,也就是出现了跨域通过CrossOrigin配置跨域我们可以将@CrossOrigin注解到方法上,实现跨域请求,我们对后端方法改造如下:/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class CorsController { /** * 方法配置跨域 * @return String */ @RequestMapping("/CrossOrigin") @CrossOrigin(origins = "http://localhost:1234") public String crossOrigin(){ return "crossOrigin"; } }通过CorsFilter配置跨域继续后端改造修改yaml文件,增加跨域配置信息#配置跨域 cors: allowedOrigin: - http://localhost:1234 allowCredentials: - true allowMethods: - GET - POST - PUT - DELETE maxAge: 7200 path: /** 增加CrosFilter配置文件package cc.lisen.cors.config; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; 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; import java.util.List; /** * 跨域配置 * * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @Configuration @ConfigurationProperties(prefix = "cors") @Getter @Setter public class CorsFilterConfig { private boolean allowCredentials; private List<String> allowedOrigin; private List<String> allowMethods; private long maxAge; private String path; /** * 配置跨域 * * @return CorsFilter */ @Bean public CorsFilter corsFilter() { CorsConfiguration corsConfiguration = new CorsConfiguration(); this.allowedOrigin.forEach(corsConfiguration::addAllowedOrigin); this.allowMethods.forEach(corsConfiguration::addAllowedMethod); corsConfiguration.setAllowCredentials(this.allowCredentials); corsConfiguration.setMaxAge(this.maxAge); UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); urlBasedCorsConfigurationSource.registerCorsConfiguration(this.path, corsConfiguration); return new CorsFilter(urlBasedCorsConfigurationSource); } } 增加请求/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class CorsController { /** * 方法配置跨域 * @return String */ @RequestMapping("/CrossOrigin") // @CrossOrigin(origins = "http://localhost:1234") public String crossOrigin(){ return "crossOrigin"; } }再次请求,可以发现仍然能够正常访问通过WebMvcConfigurer配置跨域@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/cors/**") .allowedHeaders("*") .allowedMethods("*") .maxAge(1800) .allowedOrigins("http://localhost:8081"); } }
2019年07月28日
1,198 阅读
0 评论
0 点赞
2019-07-28
Spring Boot基于FileUpload包方式上传多个文件
添加万恶的依赖<!-- 附件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>修改配置文件,屏蔽servlet自带的附件上传#配置上传文件信息 http: multipart: # 最大支持文件大小 即单个文件大小 max-file-size: 2m # 最大支持请求大小 即一次性上传的总文件大小 max-request-size: 10m #取消Servlet自带的上传 enabled: false 增加控制器package Cc.LiSen.Controllers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * ClassName: CommonsFileUpload <br/> * Description: <br/> * date: 2019/7/28 9:28<br/> * * @since JDK 1.8 */ @RestController @ResponseBody @RequestMapping(value = "/commonsfileupload") public class CommonsFileUpload { private static final Logger logger = LoggerFactory.getLogger(CommonsFileUpload.class); @PostMapping("/upload") public String Upload(@RequestParam MultipartFile[] files, @RequestParam String name, HttpServletRequest request) throws IOException { if (files.length <= 0) { return "请先选择要上传的附件"; } for (MultipartFile file : files) { if (file.isEmpty()) { return "文件信息不能为空"; } String fileType = file.getContentType(); String fileName = file.getName(); String fileOriginalName = file.getOriginalFilename(); //String fileSavePath = request.getServletContext().getRealPath("/static/sources"); //使用jar包,放到同级目录 File rootPath = new File(ResourceUtils.getURL("classpath:").getPath()); String fileSavePath = rootPath.getAbsolutePath()+"/static/upload/"; Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); fileSavePath = fileSavePath + simpleDateFormat.format(date); fileSavePath = fileSavePath + "/" + fileOriginalName; fileSavePath.replace("/", File.separator); File saveFile = new File(fileSavePath); if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } file.transferTo(saveFile); } return "上传成功"; } }
2019年07月28日
1,061 阅读
0 评论
0 点赞
2019-07-28
Spring Boot使用J2EE上传文件
温馨提示这种方式下,其实无需任何配置。只需按正常的web开发项目集成即可添加普通web项目依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>修改配置文件(可选)配置上传文件信息 http: multipart: # 最大支持文件大小 即单个文件大小 max-file-size: 2m # 最大支持请求大小 即一次性上传的总文件大小 max-request-size: 10m 使用package Cc.LiSen.Controllers; import com.sun.jmx.snmp.agent.SnmpMibAgent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; @RestController public class J2EEFileUpload { private static final Logger logger = LoggerFactory.getLogger(J2EEFileUpload.class); @PostMapping("/upload") @ResponseBody public String UploadFile(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException { if (file.isEmpty()) { return "上传文件不能为空"; } String fileType = file.getContentType(); String fileName = file.getName(); String originalName = file.getOriginalFilename(); long fileSize = file.getSize(); logger.info("原始文件名为:" + originalName); logger.info("服务器文件名为:" + fileName); logger.info("文件大小为:" + String.valueOf(fileSize)); String fileSavePath = request.getServletContext().getRealPath("/static/upload/"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddd"); fileSavePath = fileSavePath + simpleDateFormat.format(new Date())+"//"; fileSavePath = fileSavePath.replace("//",File.separator); File saveFile = new File(fileSavePath+originalName); if(!saveFile.getParentFile().exists()){ saveFile.getParentFile().mkdirs(); } file.transferTo(saveFile); return "上传成功"; } }
2019年07月28日
1,145 阅读
0 评论
0 点赞
2019-07-27
Spring Boot集成和使用Swagger2
Swagger简洁Swagger是一款RESTful接口的文档在线自动生成、功能测试功能框架。一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务,加上swagger-ui,可以有很好的呈现。万恶的添加依赖<!--添加swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency>修改application.yml增加swagger配置属性,用于配置是否启用#配置swagger是否开启 swagger: enabled: true 增加配置文件Swagger2Config.java主要是添加注解@EnableSwagger2和定义Docket的bean类。package Cc.LiSen.Configurations; import org.springframework.beans.factory.annotation.Value; 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.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2Config { @Value(value = "${swagger.enabled}") boolean swaggerEnabled; private ApiInfo apiInfo() { return new ApiInfoBuilder().title("李森的博客") .description("李森的博客") .contact(new Contact("李森的博客", "https://lisen.cc", "lisen@lisen.cc")) .version("0.1").build(); } @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //是否开启 .enable(swaggerEnabled) .select() // 扫描的路径包 .apis(RequestHandlerSelectors.basePackage("Cc.LiSen.Api")) // 指定路径处理PathSelectors.any()代表所有的路径 .paths(PathSelectors.any()).build().pathMapping("/*"); } }修改实体类package Cc.LiSen.Pojos; import Cc.LiSen.Common.Utils.HtmlUtil; import com.fasterxml.jackson.annotation.JsonBackReference; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.extern.java.Log; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.io.Serializable; import java.util.Date; /** * ClassName: Post <br/> * Description: <br/> * date: 2019/7/23 9:25<br/> * * @since JDK 1.8 */ @Entity @Table(name = "posts") @ApiModel @Data public class Post implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") @ApiModelProperty(name = "id", dataType = "long", value = "内码", example = "1") @NotBlank(message = "内码不能为空") Long id; @Column(name = "post_author") Long postAuthor; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "post_date") Date postDate; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "post_date_gmt") Date postDateGmt; @Column(name = "post_content") String postContent; @Column(name = "post_title") String postTitle; @Column(name = "post_excerpt") String postExcerpt; @Column(name = "post_status", length = 20) String postStatus; @Column(name = "ping_status", length = 20) String pingStatus; @Column(name = "comment_status", length = 20) String commentStatus; @Column(name = "post_password", length = 255) String postPassword; @Column(name = "post_name") String postName; @Column(name = "to_ping") String toPing; @Column(name = "pinged") String pinged; @Column(name = "post_modified") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String postModified; @Column(name = "post_modified_gmt") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String postModifiedGmt; @Column(name = "post_content_filtered") String postContentFiltered; @Column(name = "post_parent") Long postParent; @Column(name = "guid") String guid; @Column(name = "menu_order") int menuOrder; @ManyToOne @JoinColumn(name = "postType") PostType postType; @Column(name = "comment_count") Long commentCount; public String getThumnailImage() { return HtmlUtil.getSingleImgStr(postContent); } @Column(insertable = false, updatable = false) String thumnailImage; } 修改控制器添加文档内容(一般上是在Controller,请求参数上进行注解。package Cc.LiSen.Api; import Cc.LiSen.Pojos.Post; import Cc.LiSen.Services.PostService; import com.sun.xml.internal.bind.v2.model.core.ID; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @ResponseBody @RestController @RequestMapping(value = "/post") @Api(tags = "文章操作Api") public class PostApi { @Autowired PostService postService; @GetMapping("/get/{id}") @ApiOperation("根据ID获取文章") @ApiImplicitParam(name = "id",value = "文章ID",required = true) public List<Post> getPost(@PathVariable long id) { if (StringUtils.isEmpty(id)) { return postService.getAllPosts(); } else { List<Post> posts = new ArrayList<>(); posts.add(postService.getPostByID(id)); return posts; } } ; } Swagger访问与使用api首页路径:http://127.0.0.1:8080/swagger-ui.html调试:点击需要访问的api列表,点击try it out!按钮,即可弹出一下页面:Swagger常用属性说明作用范围 API 使用位置对象属性 @ApiModelProperty 用在出入参数对象的字段上协议集描述 @Api 用于controller类上协议描述 @ApiOperation 用在controller的方法上Response集 @ApiResponses 用在controller的方法上Response @ApiResponse 用在 @ApiResponses里边非对象参数集 @ApiImplicitParams 用在controller的方法上非对象参数描述 @ApiImplicitParam 用在@ApiImplicitParams的方法里边描述返回对象的意义 @ApiModel 用在返回对象类上常用的注解@Api、@ApiOperation、@ApiModel、@ApiModelProperty示例中有进行标注,对于其他注解,大家可自动谷歌,毕竟常用的就这几个了。有了swagger之后,原本一些post请求需要postman这样的调试工具来进行发起,而现在直接在页面上就可以进行调试了,是不是很爽!对于服务的调用者而已,有了这份api文档也是一目了然,不需要和后端多少沟通成本,按着api说明进行前端开发即可。
2019年07月27日
1,186 阅读
0 评论
0 点赞
2019-07-26
Spring Boot过滤器Filter
单个过滤器如果只是定义一个过滤器,直接通过@Configuration注解即可。package Cc.LiSen.Configurations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; /** * ClassName: CustomFilter <br/> * Description: <br/> * date: 2019/7/25 22:04<br/> * * @since JDK 1.8 */ @WebFilter(filterName = "CustomFilter", urlPatterns = "{/*}") public class CustomFilter implements Filter { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void init(FilterConfig filterConfig) throws ServletException { logger.info("初始化过滤器CustomFilter"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { logger.info("过滤器CustomFilter开始工作,并转入下一个过滤"); chain.doFilter(request, response); logger.info("CustomFilter继续过滤"); } @Override public void destroy() { logger.info("过滤器CustomFilter销毁"); } }多个过滤器如果定义多个过滤器,需要通过FilterRegistrationBean提供setOrder方法,可以为filter设置排序值,让spring在注册web filter之前排序后再依次注册。启动类中利用@bean注册FilterRegistrationBean*温馨提示过滤器定义与上面类似,去掉@Configuration注解即可,这里不再赘述,然后修改启动类,增加以下代码package Cc.LiSen; import Cc.LiSen.Configurations.CustomFilter; import Cc.LiSen.Configurations.CustomFilterOther; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication //SpringBoot 默认从App类往下面的包扫描 //所以如果控制器、实体等类与App不在一个包,同时不在下面的包时,必须手动指定包 @EnableJpaRepositories(basePackages = {"Cc.LiSen.Repositories", "Cc.LiSen.Services"}) public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String[] args) { // System.setProperty("log.root","DEBUG,info,error"); // // System.setProperty("log.base","D:\\log4j\\base"); SpringApplication.run(App.class, args); } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new CustomFilter()); filterRegistrationBean.setOrder(10); return filterRegistrationBean; } @Bean public FilterRegistrationBean filterRegistrationBeanOther() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new CustomFilterOther()); filterRegistrationBean.setOrder(20); return filterRegistrationBean; } }
2019年07月26日
1,257 阅读
0 评论
0 点赞
2019-07-22
Spring Boot通过Redis共享Session
温馨提示以下内容基于SpringBoot 1.2.7版本<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.7.RELEASE</version> </parent>添加依赖主要是添加如下两个依赖<!-- 添加redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.8.RELEASE</version> </dependency> <!-- session依赖--> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.3.5.RELEASE</version> </dependency> 安装Redis具体操作方法请自行百度,不是本文重点配置Redis找到application.yml文件,添加如下内容#redis配置 redis: host: 我是IP port: 6379 password: 我是密码 timeout: 0 pool: max-active: 100 max-idle: 10 max-wait: 100000 database: 0 增加Redis配置类RedisConfiguration.javapackage Cc.LiSen.Configurations; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; /** * ClassName: RedisConfiguration <br/> * Description: <br/> * date: 2019/7/22 9:17<br/> * * @since JDK 1.8 */ @Configuration @EnableAutoConfiguration public class RedisConfiguration { /* @Bean @ConfigurationProperties(prefix = "spring.redis.pool") public JedisPoolConfig getJedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); return jedisPoolConfig; } @Bean @ConfigurationProperties(prefix = "spring.redis") public JedisConnectionFactory getConnectionFactory() { JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setUsePool(true); JedisPoolConfig jedisPoolConfig = getJedisPoolConfig(); factory.setPoolConfig(jedisPoolConfig); return factory; } @Bean public RedisTemplate<?,?> redisTemplate(){ JedisConnectionFactory factory=getConnectionFactory(); RedisTemplate<?,?> redisTemplate=new StringRedisTemplate(factory); return redisTemplate; } */ /** * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类 * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 使用Jackson2JsonRedisSerialize 替换默认序列化 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); // 设置value的序列化规则和 key的序列化规则 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }增加Session配置SessionConfiguration.javapackage Cc.LiSen.Configurations; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /** * ClassName: SessionConfiguration <br/> * Description: <br/> * date: 2019/7/22 10:45<br/> * * @since JDK 1.8 */ @Configuration @EnableRedisHttpSession public class SessionConfiguration { }简单测试UUID uid = (UUID) session.getAttribute("uid"); if (uid == null) { uid = UUID.randomUUID(); } session.setAttribute("uid", uid); request.getSession().setAttribute("user",JSON.toJSONString(checkUser));
2019年07月22日
1,340 阅读
0 评论
0 点赞
2019-07-21
Spring Boot使用FastJson
什么是FastJson?FastJson是阿里巴巴旗下的一个开源项目之一,顾名思义它专门用来做快速操作json的序列化与反序列化的组件。它是目前json解析最快的开源组件没有之一!在这之前JackJson是最为出名的快速操作json的工具,当然,现在也很出名。阿里巴巴的FastJson虽然速度快,但是bug也是相当多,如果是在大型系统中并且对系统安全性要求比较高,仍然建议使用Jackjson。maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency>{message type="warning" content="fastjson虽然是阿里巴巴出品的,但是最近爆出很多bug,所以大项目上还是慎重使用"/}创建配置信息类我们接下来创建一个FastJsonConfiguration配置信息类,添加@Configuration注解让SpringBoot自动加载类内的配置,有一点要注意我们继承了WebMvcConfigurerAdapter这个类,这个类是SpringBoot内部提供专门处理用户自行添加的配置,里面不仅仅包含了修改视图的过滤还有其他很多的方法,比如拦截器,过滤器,Cors配置等。方式一:fastJson视图过滤配置package cn.notemi.configuration; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; /** * Title:FastJsonConfiguration * Description:FastJson配置信息 * * @create 2017-08-08 下午 4:33 **/ @Configuration public class FastJsonConfiguration extends WebMvcConfigurerAdapter { /** * 修改自定义消息转换器 * @param converters 消息转换器列表 */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //调用父类的配置 super.configureMessageConverters(converters); //创建fastJson消息转换器 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //创建配置类 FastJsonConfig fastJsonConfig = new FastJsonConfig(); //修改配置返回内容的过滤 fastJsonConfig.setSerializerFeatures( SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty ); fastConverter.setFastJsonConfig(fastJsonConfig); //将fastjson添加到视图消息转换器列表内 converters.add(fastConverter); } }方式二:自定义FastJsonHttpMessageConverter@Configuration public class FastJsonConfig { @Bean public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() { FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); com.alibaba.fastjson.support.config.FastJsonConfig fastJsonConfig = new com.alibaba.fastjson.support.config.FastJsonConfig(); fastJsonConfig.setDateFormat("yyyy-MM-dd"); fastJsonConfig.setCharset(StandardCharsets.UTF_8); fastJsonConfig.setSerializerFeatures( // SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty ); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); // 解决中文乱码 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON); fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); return fastJsonHttpMessageConverter; } }FastJson配置实体调用setSerializerFeatures方法可以配置多个过滤方式,下面我们来介绍下常用的SerializerFeatures配置。FastJson SerializerFeaturesWriteNullListAsEmpty :List字段如果为null,输出为[],而非nullWriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非nullDisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非nullWriteMapNullValue:是否输出值为null的字段,默认为false。项目运行我们使用了过滤,SerializerFeature.WriteNullStringAsEmpty,本该显示null,显示为"",所以成功使用。
2019年07月21日
1,346 阅读
0 评论
0 点赞
2019-07-21
Spring Boot包位置设置
/* * Copyright (C) 2019 李森的博客 https://lisen.cc * 项目名称:Cc.LiSen.Idea * 文件名称:App.java * Date:19-7-19 上午1:21 * Author:lisen@lisen.cc * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package Cc.LiSen; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication //SpringBoot 默认从App类往下面的包扫描 //所以如果控制器、实体等类与App不在一个包,同时不在下面的包时,必须手动指定包 //@ComponentScan(basePackages = {"Cc.LiSen.Controllers", "Cc.LiSen.Services"}) //@EnableJpaRepositories(basePackages = {"Cc.LiSen.Repositories", "Cc.LiSen.Services"}) //@EntityScan(basePackages = {"Cc/LiSen/Pojos"}) public class App { public static void main(String[] args){ SpringApplication.run(App.class,args); } }
2019年07月21日
1,191 阅读
0 评论
0 点赞
1
...
7
8