diff --git a/pom.xml b/pom.xml index 5047f1badf804bfbef0c4c419006dfde0a441837..509edc70076dc9ef9e6217ea4595e1f6b793c4a0 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ com.javaee news-system 0.0.1-SNAPSHOT - war + jar news-system Demo project for Spring Boot @@ -57,6 +57,38 @@ 0.9.1 + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.apache.commons + commons-pool2 + + + + + org.springframework.boot + spring-boot-devtools + true + + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + + org.hibernate + hibernate-validator + 6.2.0.CR1 + + com.baomidou @@ -69,10 +101,10 @@ 2.3.31 - javax.xml.bind - jaxb-api - 2.3.1 + org.projectlombok + lombok + diff --git a/src/main/java/com/javaee/newssystem/NewsSystemApplication.java b/src/main/java/com/javaee/newssystem/NewsSystemApplication.java index 8475e4b536eb29328cec20c624e9f3807979a700..34b71df2860f04de615e6b7767dde4b3805dd904 100644 --- a/src/main/java/com/javaee/newssystem/NewsSystemApplication.java +++ b/src/main/java/com/javaee/newssystem/NewsSystemApplication.java @@ -2,7 +2,10 @@ package com.javaee.newssystem; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.scheduling.annotation.EnableScheduling; +@EnableScheduling @SpringBootApplication public class NewsSystemApplication { diff --git a/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java b/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java index 6d9aaa9200625dc601e1814306d756240d72a4b5..03f0c36813e6fe223d567a7329d72912ce36dd35 100644 --- a/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java +++ b/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java @@ -2,10 +2,15 @@ package com.javaee.newssystem.config; import com.javaee.newssystem.interceptor.AdminInterceptor; import com.javaee.newssystem.interceptor.LoginInterceptor; +import com.javaee.newssystem.mapper.JacksonObjectMapper; import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import java.util.List; + @Configuration public class AdminWebConfig implements WebMvcConfigurer { @@ -14,11 +19,19 @@ public class AdminWebConfig implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { // 添加登录验证的拦截器 registry.addInterceptor(new LoginInterceptor()) - .addPathPatterns("/**") + .addPathPatterns("/user/**","/admin/**","/comment/**","/news/**","/team/**") .excludePathPatterns("/user/login","/admin/login","/user/register"); // 添加管理员身份验证的拦截器 registry.addInterceptor(new AdminInterceptor()) .excludePathPatterns("/admin/login") .addPathPatterns("/admin/**"); } + +// 添加消息转换器 + @Override + public void extendMessageConverters(List> converters) { + MappingJackson2HttpMessageConverter httpMessageConverter = new MappingJackson2HttpMessageConverter(); + httpMessageConverter.setObjectMapper(new JacksonObjectMapper()); + converters.add(0,httpMessageConverter); + } } diff --git a/src/main/java/com/javaee/newssystem/config/CacheConfig.java b/src/main/java/com/javaee/newssystem/config/CacheConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..743c12b545d46032556b9d4fcb7a9001ef7643af --- /dev/null +++ b/src/main/java/com/javaee/newssystem/config/CacheConfig.java @@ -0,0 +1,40 @@ +package com.javaee.newssystem.config; + +import com.javaee.newssystem.entity.User; +import com.javaee.newssystem.vo.UserRespVo; +import org.springframework.cache.CacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; + + +import java.time.Duration; + +@Configuration +public class CacheConfig { + + private Long expirationTime = 60L * 60L * 24L; + + @Bean(name = "cacheManager") + @Primary + public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { + RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + //设置过期时间 + .entryTtl(Duration.ofSeconds(expirationTime)) + //禁止缓存null对象 + .disableCachingNullValues() + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<>(User.class))); + + return RedisCacheManager.builder(redisConnectionFactory) + .cacheDefaults(cacheConfiguration) + .build(); + } +} diff --git a/src/main/java/com/javaee/newssystem/config/RedisConfig.java b/src/main/java/com/javaee/newssystem/config/RedisConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..fd53b63fc3324c7c584f19d821f96040c1ca7fdc --- /dev/null +++ b/src/main/java/com/javaee/newssystem/config/RedisConfig.java @@ -0,0 +1,57 @@ +package com.javaee.newssystem.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; +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.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + + + +/** + * @author qjj + * @date 2022/9/6 + * @describe + */ + + +@Configuration +public class RedisConfig { + + @Bean("redisTemplate") + @SuppressWarnings("all") + //改成String,Object类型 + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(factory); + + //Json序列化配置 + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); +// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + //String 的序列化 + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + + //key采用string的序列化方式 + template.setKeySerializer(stringRedisSerializer); + //value的序列化方式采用jackson + template.setValueSerializer(jackson2JsonRedisSerializer); + //hash的key也采用String的序列化方式 + template.setHashKeySerializer(stringRedisSerializer); + //hash的value序列化方式采用jackson + template.setHashValueSerializer(jackson2JsonRedisSerializer); + template.afterPropertiesSet(); + + return template; + } +} + diff --git a/src/main/java/com/javaee/newssystem/controller/AdminController.java b/src/main/java/com/javaee/newssystem/controller/AdminController.java index 35867cdbb7284432f47e2cd0e7c1d602f896eb85..af7b64404439291b34d004186a37f5c57be82881 100644 --- a/src/main/java/com/javaee/newssystem/controller/AdminController.java +++ b/src/main/java/com/javaee/newssystem/controller/AdminController.java @@ -6,13 +6,26 @@ import com.javaee.newssystem.entity.*; import com.javaee.newssystem.service.INewsService; import com.javaee.newssystem.service.impl.*; import com.javaee.newssystem.utils.JwtUtil; +import com.javaee.newssystem.vo.AdminVo; +import com.javaee.newssystem.vo.NewsVo; +import com.javaee.newssystem.vo.UserRespVo; +import com.javaee.newssystem.vo.UserVo; import com.mysql.cj.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ScanOptions; import org.springframework.web.bind.annotation.*; import org.springframework.stereotype.Controller; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; import java.util.List; +import java.util.Map; +import java.util.function.Consumer; /** *

@@ -36,20 +49,24 @@ public class AdminController { TeamServiceImpl teamService; @Autowired CommentServiceImpl commentService; + @Autowired + RedisServiceImpl redisService; // 管理员登录 @RequestMapping(value = "/login",method = RequestMethod.POST) - public Msg Login(String userName, String password){ + public Msg Login(@RequestBody AdminVo vo){ + String userName = vo.getUserName(); + String password = vo.getPassword(); if(StringUtils.isNullOrEmpty(userName)&&StringUtils.isNullOrEmpty(password)){ return Msg.fail("登录失败,缺少参数"); } else { - Admin admin = adminService.Login(userName, password); - if (admin!=null){ + AdminVo adminVo = adminService.Login(userName, password); + if (adminVo!=null){ Msg msg = Msg.success("登录成功"); - msg.add("data",admin); + msg.add("data",adminVo); // 生成token - msg.add("token", JwtUtil.getToken(admin.getAdminId(),"管理员")); + msg.add("token", JwtUtil.getToken(adminVo.getAdminId(),"管理员")); return msg; } else @@ -62,7 +79,7 @@ public class AdminController { @RequestMapping(value = "/userlist",method = RequestMethod.GET) public Msg getUserList(Integer current,Integer size){ if(current!=null&&size!=null){ - Page page = userService.adminGetUserList(current, size); + Page page = userService.adminGetUserList(current, size); Msg msg = Msg.success("获取成功"); msg.add("data",page); return msg; @@ -73,7 +90,7 @@ public class AdminController { // 管理员注销用户账号 @RequestMapping(value = "/logout",method = RequestMethod.POST) - public Msg logoutUser(Long userId){ + public Msg logoutUser(@RequestBody Long userId){ if(userId!=null){ Boolean b = userService.adminLogoutUser(userId); return b?Msg.success("注销用户成功"):Msg.fail("此用户不存在或已被注销"); @@ -83,9 +100,9 @@ public class AdminController { // 管理员恢复用户账号 @RequestMapping(value = "/unlogout",method = RequestMethod.POST) - public Msg unlogoutUser(Long userId){ - if(userId!=null){ - Boolean b = userService.adminUnlogoutUser(userId); + public Msg unlogoutUser(@RequestBody UserVo vo){ + if(vo.getUserId()!=null){ + Boolean b = userService.adminUnlogoutUser(vo.getUserId()); if(b) return Msg.success("恢复用户账号成功"); else @@ -96,9 +113,9 @@ public class AdminController { // 管理员修改消息状态为通过 @RequestMapping(value = "/status/pass",method = RequestMethod.POST) - public Msg pass(Long newsId){ - if(newsId!=null){ - Boolean b = newsService.PassNews(newsId); + public Msg pass(@RequestBody NewsVo vo){ + if(vo.getNewsId()!=null){ + Boolean b = newsService.PassNews(vo.getNewsId()); return b?Msg.success("修改为通过成功"):Msg.fail("修改为通过失败"); } return Msg.fail("缺少参数"); @@ -106,9 +123,9 @@ public class AdminController { // 管理员修改消息状态为未通过 @RequestMapping(value = "/status/unpass",method = RequestMethod.POST) - public Msg unpass(Long newsId){ - if(newsId!=null){ - Boolean b = newsService.UnPassNews(newsId); + public Msg unpass(@RequestBody NewsVo vo){ + if(vo.getNewsId()!=null){ + Boolean b = newsService.UnPassNews(vo.getNewsId()); return b?Msg.success("修改为未通过成功"):Msg.fail("修改为未通过失败"); } return Msg.fail("缺少参数"); @@ -118,7 +135,7 @@ public class AdminController { @RequestMapping(value = "/status/pass",method = RequestMethod.GET) public Msg getPassedNews(Integer current,Integer size){ if(current!=null&&size!=null){ - Page page = newsService.GetPassList(current, size); + Page page = newsService.GetPassList(current, size,null); return Msg.success("获取成功").add("data",page); } return Msg.fail("缺少参数"); @@ -128,7 +145,7 @@ public class AdminController { @RequestMapping(value = "/status/list",method = RequestMethod.GET) public Msg getNewsList(Integer current,Integer size){ if(current!=null&&size!=null){ - Page Page = newsService.GetUnReviewed(current, size); + Page Page = newsService.GetUnReviewed(current,size); return Msg.success("获取成功").add("data",Page); } return Msg.fail("缺少参数"); @@ -138,26 +155,18 @@ public class AdminController { @RequestMapping(value = "/status/unpass",method = RequestMethod.GET) public Msg getUnpassNews(Integer current,Integer size){ if(current!=null&&size!=null){ - Page page = newsService.GetUnPassList(current, size); + Page page = newsService.GetUnPassList(current, size); return Msg.success("获取成功").add("data",page); } return Msg.fail("缺少参数"); } -// 管理员删除消息 -// @RequestMapping(value = "/delete/list",method = RequestMethod.POST) -// public Msg deleteNews(Long newsId){ -// if(newsId!=null){ -// return Msg.success("参数接收到了,但是接口开发中。。。。"); -// } -// return Msg.fail("缺少参数"); -// } // 管理员获取用户已保存的消息 @GetMapping("/save") public Msg SaveNews(Long userId,Integer current,Integer size){ if(current!=null && size!=null){ - Page page=newsService.GetSaveNews(userId,current,size); + Page page=newsService.GetSaveNews(userId,current,size); Msg msg=Msg.success("获取成功"); msg.add("data",page); return msg; @@ -179,4 +188,18 @@ public class AdminController { } return Msg.fail("参数缺失"); } + +// 管理员获取一周的新增新闻数 + @GetMapping("/getNewsNumber") + public Msg getNewsNumber(){ + Double[] number = redisService.getNewsNumber(); + return Msg.success("成功").add("data",number); + } + +// 管理员获取月活跃人数 + @GetMapping("/getUserNumber") + public Msg getUserNumber(){ + Integer number = redisService.getUserNumber(); + return Msg.success("获取成功").add("data",number); + } } diff --git a/src/main/java/com/javaee/newssystem/controller/CommentController.java b/src/main/java/com/javaee/newssystem/controller/CommentController.java index ac20d3a01676e282b83d86a8b1b6fea17656161b..d22c3d804cc67a9011890377a73b2d67c8bea6d3 100644 --- a/src/main/java/com/javaee/newssystem/controller/CommentController.java +++ b/src/main/java/com/javaee/newssystem/controller/CommentController.java @@ -4,6 +4,8 @@ package com.javaee.newssystem.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.javaee.newssystem.entity.*; import com.javaee.newssystem.service.impl.CommentServiceImpl; +import com.javaee.newssystem.vo.CommentVo; +import com.javaee.newssystem.vo.CommentWithUserVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -26,9 +28,9 @@ public class CommentController { //发表一级评论 @PostMapping("/first") - public Msg createComment(Comment comment){ + public Msg createComment(@RequestBody Comment comment){ if(comment!=null){ - comment=commentService.createComment(comment); + commentService.createComment(comment); if (comment.getCommentId() != null){ Msg msg = Msg.success("评论成功"); return msg; @@ -40,9 +42,9 @@ public class CommentController { //发表二级评论 @PostMapping("/second") - public Msg createSecondComment(Comment comment){ + public Msg createSecondComment(@RequestBody Comment comment){ if(comment!=null){ - comment=commentService.createComment(comment); + commentService.createComment(comment); if (comment.getCommentId() != null){ Msg msg = Msg.success("评论成功"); return msg; @@ -54,9 +56,9 @@ public class CommentController { //点赞评论 @PostMapping("/like") - public Msg createLike(Long userId,Long commentId){ - if(userId!=null && commentId != null){ - Boolean b = commentService.createLike(userId,commentId); + public Msg createLike(@RequestBody CommentWithUserVo vo){ + if(vo.getUserId()!=null && vo.getCommentId() != null){ + Boolean b = commentService.createLike(vo.getUserId(),vo.getCommentId()); return b?Msg.success("点赞成功"):Msg.fail("点赞失败"); } return Msg.fail("缺少参数"); @@ -64,9 +66,9 @@ public class CommentController { //取消点赞 @PostMapping("/unlike") - public Msg deleteLike(Long userId,Long commentId){ - if(userId!=null && commentId != null){ - Boolean b = commentService.deleteLike(userId,commentId); + public Msg deleteLike(@RequestBody CommentWithUserVo vo){ + if(vo.getUserId()!=null && vo.getCommentId() != null){ + Boolean b = commentService.deleteLike(vo.getUserId(),vo.getCommentId()); return b?Msg.success("取消成功"):Msg.fail("取消失败"); } return Msg.fail("缺少参数"); @@ -74,9 +76,9 @@ public class CommentController { //删除评论 @PostMapping("/delete") - public Msg deleteComment(Long commentId){ - if(commentId != null){ - Boolean b = commentService.deleteComment(commentId); + public Msg deleteComment(@RequestBody CommentWithUserVo vo){ + if(vo.getCommentId() != null){ + Boolean b = commentService.deleteComment(vo.getCommentId()); return b?Msg.success("删除评论成功"):Msg.fail("删除评论失败"); } return Msg.fail("缺少参数"); @@ -84,9 +86,9 @@ public class CommentController { //获取一级评论 @GetMapping(value = "/firstList") - public Msg getFirstList(Long newsId,Integer current,Integer size){ + public Msg getFirstList(Long newsId,Integer current,Integer size,@RequestHeader("token") String token){ if(current!=null && size!=null && newsId != null){ - Page page=commentService.GetFirstCommentList(newsId,current,size); + Page page=commentService.GetFirstCommentList(newsId,current,size,token); Msg msg=Msg.success("获取成功"); msg.add("data",page); return msg; @@ -96,9 +98,9 @@ public class CommentController { //获取二级评论 @GetMapping(value = "/secondList") - public Msg getSecondList(Long commentId,Integer current,Integer size){ + public Msg getSecondList(Long commentId,Integer current,Integer size,@RequestHeader("token") String token){ if(current!=null && size!=null && commentId !=null){ - Page page=commentService.GetSecondCommentList(commentId,current,size); + Page page=commentService.GetSecondCommentList(commentId,current,size,token); Msg msg=Msg.success("获取成功"); msg.add("data",page); return msg; @@ -110,7 +112,7 @@ public class CommentController { @GetMapping(value = "/myself") public Msg getMyselfComment(Long userId,Integer current,Integer size){ if(current!=null && size!=null){ - Page page=commentService.GetMyselfList(userId,current,size); + Page page=commentService.GetMyselfList(userId,current,size); Msg msg=Msg.success("获取成功"); msg.add("data",page); return msg; @@ -121,7 +123,7 @@ public class CommentController { @GetMapping("/like") public Msg getLikeComment(Long userId,Integer current,Integer size){ if(userId!=null&¤t!=null&&size!=null){ - Page page = commentService.getLikeComment(userId, current, size); + Page page = commentService.getLikeComment(userId, current, size); Msg msg = Msg.success("查询成功"); msg.add("data",page); return msg; diff --git a/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java new file mode 100644 index 0000000000000000000000000000000000000000..fabebdd5bd930892bf09c60c27e5db8353119506 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java @@ -0,0 +1,49 @@ +package com.javaee.newssystem.controller; +import com.javaee.newssystem.entity.Msg; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.BindException; +import org.springframework.validation.BindingResult; +import org.springframework.validation.ObjectError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@RestControllerAdvice(basePackages = "com.javaee.newssystem.controller") +public class ExceptionControllerAdvice { + + @ExceptionHandler(BindException.class) + public Msg handleVaildException(BindException e){ +// List errorList = e.getAllErrors(); +// List messageStr = new ArrayList<>(); +// for (ObjectError item:errorList) { +// log.error("数据校验出现问题:{},异常类型:{}",item.getDefaultMessage(),item.getObjectName()); +// //获取错误信息 +// String message = item.getDefaultMessage(); +// //获取错误的属性名字 +// String field = item.getObjectName(); +// messageStr.add(field+":"+message); +// } + log.error("数据校验出现问题{},异样类型:{}",e.getMessage(),e.getClass()); + BindingResult bindingResult = e.getBindingResult(); + Map errorMap = new HashMap<>(); + List errorList = new ArrayList<>(); + bindingResult.getFieldErrors().forEach(fieldError -> { + errorList.add(fieldError.getDefaultMessage()); + errorMap.put(fieldError.getField(),fieldError.getDefaultMessage()); + }); + return Msg.fail(String.join(";",errorList),400); + } + + + @ExceptionHandler(value = Throwable.class) + public Msg handleException(Throwable throwable){ + log.error("错误",throwable); + return Msg.fail("系统内部异常"); + } +} diff --git a/src/main/java/com/javaee/newssystem/controller/NewsController.java b/src/main/java/com/javaee/newssystem/controller/NewsController.java index 34a30f9ded78d55b6cf26fb0824f90c078b036e0..7c85b7fc235d4695f7d794c53dfabeb282a90423 100644 --- a/src/main/java/com/javaee/newssystem/controller/NewsController.java +++ b/src/main/java/com/javaee/newssystem/controller/NewsController.java @@ -2,13 +2,21 @@ package com.javaee.newssystem.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.javaee.newssystem.entity.HotWord; import com.javaee.newssystem.entity.Msg; import com.javaee.newssystem.entity.News; import com.javaee.newssystem.service.impl.NewsServiceImpl; +import com.javaee.newssystem.service.impl.RedisServiceImpl; import com.javaee.newssystem.utils.CheckClassUtil; +import com.javaee.newssystem.vo.NewsVo; +import com.javaee.newssystem.vo.NewsWithUserVo; +import com.mysql.cj.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +import javax.validation.Valid; +import java.util.List; + /** *

* 前端控制器 @@ -24,16 +32,16 @@ public class NewsController { @Autowired NewsServiceImpl newsService; + @Autowired + RedisServiceImpl redisService; //创建消息 @PostMapping(value = "/upload") - public Msg CreateNews(News news){ + public Msg CreateNews(@RequestBody @Valid News news,@RequestHeader("token") String token){ if(CheckClassUtil.checkNews(news)){ - newsService.CreateNews(news); + NewsVo newsVo = newsService.CreateNews(news,token); if(news.getNewsId()!=null){ - Msg msg=Msg.success("创建成功"); - msg.add("data",news); - return msg; + return Msg.success("创建成功").add("data",newsVo); } } return Msg.fail("缺少参数"); @@ -41,13 +49,11 @@ public class NewsController { //保存消息 @PostMapping(value = "/save") - public Msg SaveNews(News news){ + public Msg SaveNews(@RequestBody @Valid News news,@RequestHeader("token") String token){ if(CheckClassUtil.checkNews(news)){ - newsService.SaveNews(news); + NewsVo newsVo = newsService.SaveNews(news,token); if(news.getNewsId()!=null){ - Msg msg=Msg.success("创建成功"); - msg.add("data",news); - return msg; + return Msg.success("创建成功").add("data",newsVo); } } return Msg.fail("缺少参数"); @@ -57,147 +63,115 @@ public class NewsController { @GetMapping(value = "/focuslist") public Msg GetFocusList(Long userId,Integer current,Integer size){ if(userId!=null && current!=null && size!=null){ - Page page=newsService.GetFocusList(userId,current,size); - Msg msg=Msg.success("获取成功"); - msg.add("data",page); - return msg; + Page page=newsService.GetFocusList(userId,current,size); + return Msg.success("获取成功").add("data",page); } return Msg.fail("缺少参数"); } //获取公共消息 @GetMapping(value = "/public") - public Msg getPublicList(Integer current,Integer size){ + public Msg getPublicList(Integer current,Integer size,@RequestHeader("token") String token){ if(current!=null && size!=null){ - Page page=newsService.GetPublicList(current,size); - Msg msg=Msg.success("获取成功"); - msg.add("data",page); - return msg; + Page page=newsService.GetPublicList(current,size,token); + return Msg.success("获取成功").add("data",page); } return Msg.fail("缺少参数"); } //获取团队消息 @GetMapping(value = "/team") - public Msg getTeamnews(Long teamId,Integer current,Integer size){ + public Msg getTeamnews(Long teamId,Integer current,Integer size,@RequestHeader("token") String token){ if(current!=null && size!=null){ - Page page=newsService.GetTeamList(teamId,current,size); - Msg msg=Msg.success("获取成功"); - msg.add("data",page); - return msg; + Page page=newsService.GetTeamList(teamId,current,size,token); + return Msg.success("获取成功").add("data",page); } return Msg.fail("缺少参数"); } //获取自己发布的消息 @GetMapping(value = "/myself") - public Msg getMyselfnews(Long userId,Integer current,Integer size){ + public Msg getMyselfnews(Long userId,Integer current,Integer size,@RequestHeader("token") String token){ if(current!=null && size!=null){ - Page page=newsService.GetMyselfList(userId,current,size); - Msg msg=Msg.success("获取成功"); - msg.add("data",page); - return msg; + Page page=newsService.GetMyselfList(userId,current,size,token); + return Msg.success("获取成功").add("data",page); } return Msg.fail("缺少参数"); } //修改新闻内容 @PostMapping(value = "/update") - public Msg updateNews(News news){ + public Msg updateNews(@RequestBody News news,@RequestHeader("token") String token){ if(news!=null){ - news=newsService.updateInfo(news); - Msg msg=Msg.success("更改信息成功"); - msg.add("data",news); - return msg; + NewsVo newsVo = newsService.updateInfo(news,token); + return Msg.success("更改信息成功").add("data",newsVo); } return Msg.fail("缺少参数"); } //删除新闻内容 @PostMapping("/delete") - public Msg deleteTeam(Long newsId){ - if(newsId!=null){ - Boolean b = newsService.deleteNews(newsId); - if(b){ - Msg msg = Msg.success("删除成功"); - return msg; - } + public Msg deleteTeam(@RequestBody NewsVo vo){ + if(vo.getNewsId()!=null){ + Boolean b = newsService.deleteNews(vo.getNewsId()); + return b?Msg.success("删除成功"):Msg.fail("删除失败"); } return Msg.fail("缺少参数"); } //获取消息的关注人数 @GetMapping("focus/user") - public Msg FocusNews(Long newsId){ + public Msg FocusNewsUserNumber(Long newsId){ if(newsId!=null){ Integer focusnum=newsService.GetFocusNews(newsId); - Msg msg=Msg.success("查询成功"); - msg.add("total",focusnum); - return msg; + return Msg.success("查询成功").add("data",focusnum); } return Msg.fail("缺少参数"); } -// //获取已通过消息 -// @GetMapping("/pass") -// public Msg PassNews(Integer current,Integer size){ -// if(current!=null && size!=null){ -// Page page=newsService.GetPassList(current,size); -// Msg msg=Msg.success("获取成功"); -// msg.add("data",page); -// return msg; -// } -// return Msg.fail("缺少参数"); -// } -// -// //获取未通过消息 -// @GetMapping("/unpass") -// public Msg UnPassNews(Integer current,Integer size){ -// if(current!=null && size!=null){ -// Page page=newsService.GetUnPassList(current,size); -// Msg msg=Msg.success("获取成功"); -// msg.add("data",page); -// return msg; -// } -// return Msg.fail("缺少参数"); -// } -// -// //获取未审核 -// @GetMapping("/unreviewed") -// public Msg UnReviewedNews(Integer current,Integer size){ -// if(current!=null && size!=null){ -// Page page=newsService.GetUnReviewed(current,size); -// Msg msg=Msg.success("获取成功"); -// msg.add("data",page); -// return msg; -// } -// return Msg.fail("缺少参数"); -// } -// -// //获取用户已保存 -// @GetMapping("/save") -// public Msg SaveNews(Long userId,Integer current,Integer size){ -// if(current!=null && size!=null){ -// Page page=newsService.GetSaveNews(userId,current,size); -// Msg msg=Msg.success("获取成功"); -// msg.add("data",page); -// return msg; -// } -// return Msg.fail("缺少参数"); -// } -// -// //管理员审核新闻 -// @PostMapping("/pass") -// public Msg PassNews(Long newsId){ -// if(newsId!=null){ -// Boolean b = newsService.PassNews(newsId); -// if(b){ -// Msg msg = Msg.success("审核成功"); -// return msg; -// } -// else{ -// return Msg.fail("状态码错误"); -// } -// } -// return Msg.fail("缺少参数"); -// } + //关注消息 + @PostMapping("focus") + public Msg FocusNews(@RequestBody NewsWithUserVo vo){ + if(vo!=null&&vo.getNewsId()!=null&&vo.getUserId()!=null){ + Boolean b=newsService.UserFocusNews(vo.getNewsId(),vo.getUserId()); + return b?Msg.success("关注成功"):Msg.fail("已关注,无需再次关注"); + } + return Msg.fail("缺少参数"); + } + + //取消关注消息 + @PostMapping("focus/cancel") + public Msg cancelFocusNews(@RequestBody NewsWithUserVo vo){ + if(vo!=null&&vo.getNewsId()!=null&&vo.getUserId()!=null){ + Boolean b=newsService.UserCancelFocusNews(vo.getNewsId(),vo.getUserId()); + return b?Msg.success("取消关注成功"):Msg.fail("已经取消关注,无法取消"); + } + return Msg.fail("缺少参数"); + } + +// 根据关键词查找消息 + @GetMapping("search") + public Msg searchNews(String key,Integer current,Integer size,@RequestHeader("token") String token){ + if(!StringUtils.isNullOrEmpty(key)){ + Page page = newsService.searchNews(key,current,size,token); + return Msg.success("获取成功").add("data",page); + } + return Msg.fail("缺少参数"); + } + +// 获取热搜 + @GetMapping("/topsearch") + public Msg getTopsearch(Integer number){ + List hotWords = redisService.getHotKey(number); + return Msg.success("获取成功").add("data",hotWords); + } + +// 根据类型获取消息 + @GetMapping("/category/list") + public Msg getNewsListBycategory(String key,Integer current,Integer size){ + if(!StringUtils.isNullOrEmpty(key)){ + Page page = newsService.getNewsListBycategory(key,current,size); + return Msg.success("获取成功").add("data",page); + } + return Msg.fail("缺少参数"); + } } diff --git a/src/main/java/com/javaee/newssystem/controller/RedisController.java b/src/main/java/com/javaee/newssystem/controller/RedisController.java new file mode 100644 index 0000000000000000000000000000000000000000..7fd1ad709053801a2f130f8517c6d9adfb543b67 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/controller/RedisController.java @@ -0,0 +1,15 @@ +package com.javaee.newssystem.controller; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RedisController { + + @Autowired + RedisTemplate redisTemplate; + + +} diff --git a/src/main/java/com/javaee/newssystem/controller/TeamController.java b/src/main/java/com/javaee/newssystem/controller/TeamController.java index 6ae9072a6992502c0cd600556e1a0f647dc814eb..aa1649187fc24c979b94f1d0486bc852f7dda142 100644 --- a/src/main/java/com/javaee/newssystem/controller/TeamController.java +++ b/src/main/java/com/javaee/newssystem/controller/TeamController.java @@ -6,13 +6,13 @@ import com.javaee.newssystem.entity.Msg; import com.javaee.newssystem.entity.Team; import com.javaee.newssystem.service.impl.TeamServiceImpl; import com.javaee.newssystem.utils.CheckClassUtil; +import com.javaee.newssystem.vo.TeamVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; -import org.springframework.stereotype.Controller; import org.springframework.web.multipart.MultipartFile; -import java.util.List; +import javax.validation.Valid; /** *

@@ -31,9 +31,9 @@ public class TeamController { // 创建团队 @PostMapping("/create") - public Msg createTeam(Team team, @RequestPart("headImg")MultipartFile headImg){ + public Msg createTeam(@RequestBody @Valid Team team){ if(CheckClassUtil.checkTeam(team)){ - team = teamService.createTeam(team,headImg); + team = teamService.createTeam(team); if(team.getTeamId()!=null){ Msg msg = Msg.success("创建成功"); msg.add("data",team); @@ -60,9 +60,9 @@ public class TeamController { // 更新团队信息 @PostMapping("/update/info") - public Msg updateInfo(Team team, @RequestPart("headImg")MultipartFile headImg){ + public Msg updateInfo(@RequestBody @Valid Team team){ if(team!=null&&team.getTeamId()!=null){ - team = teamService.updateInfo(team,headImg); + team = teamService.updateInfo(team); Msg msg = Msg.success("更改信息成功"); msg.add("data",team); return msg; @@ -72,9 +72,9 @@ public class TeamController { // 解散团队 @PostMapping("/delete") - public Msg deleteTeam(Long teamId){ - if(teamId!=null){ - Boolean b = teamService.deleteTeam(teamId); + public Msg deleteTeam(@RequestBody TeamVo vo){ + if(vo.getTeamId()!=null){ + Boolean b = teamService.deleteTeam(vo.getTeamId()); return b?Msg.success("解散成功"):Msg.fail("解散失败"); } return Msg.fail("缺少参数"); @@ -82,9 +82,9 @@ public class TeamController { // 置顶消息 @PostMapping("/first") - public Msg firstNews(Long teamId,Long newsId){ - if(teamId!=null&&newsId!=null){ - Team team = teamService.firstNews(teamId,newsId); + public Msg firstNews(@RequestBody TeamVo vo){ + if(vo.getTeamId()!=null&&vo.getNewsId()!=null){ + Team team = teamService.firstNews(vo.getTeamId(),vo.getNewsId()); if(team!=null){ Msg msg = Msg.success("置顶消息成功"); msg.add("data",team); @@ -96,9 +96,9 @@ public class TeamController { // 邀请用户 @PostMapping("/invite") - public Msg inviteUser(Long teamId,Long userId){ - if(teamId!=null&&userId!=null){ - Boolean b = teamService.invite(teamId,userId); + public Msg inviteUser(@RequestBody TeamVo vo){ + if(vo.getTeamId()!=null&&vo.getUserId()!=null){ + Boolean b = teamService.invite(vo.getTeamId(),vo.getUserId()); if (b){ return Msg.success("邀请成功"); } @@ -110,9 +110,9 @@ public class TeamController { // 踢出用户 @PostMapping("/deleteMember") - public Msg deleteUser(Long teamId,Long userId){ - if(teamId!=null&&userId!=null){ - Boolean b = teamService.deleteUser(teamId,userId); + public Msg deleteUser(@RequestBody TeamVo vo){ + if(vo.getTeamId()!=null&&vo.getUserId()!=null){ + Boolean b = teamService.deleteUser(vo.getTeamId(),vo.getUserId()); if(b){ return Msg.success("踢出成功"); } @@ -124,9 +124,9 @@ public class TeamController { // 转换管理权 @PostMapping("/change/leader") - public Msg changeLeader(Long teamId,Long userId){ - if(teamId!=null&&userId!=null){ - Boolean b = teamService.changeLeader(teamId,userId); + public Msg changeLeader(@RequestBody TeamVo vo){ + if(vo.getTeamId()!=null&&vo.getUserId()!=null){ + Boolean b = teamService.changeLeader(vo.getTeamId(),vo.getUserId()); return b?Msg.success("转让成功"):Msg.fail("转让失败"); } return Msg.fail("缺少参数"); @@ -150,9 +150,9 @@ public class TeamController { // 成员退出团队 @PostMapping("/member/delete") - public Msg memberDelete(Long userId,Long teamId){ - if(userId!=null&&teamId!=null){ - Boolean b = teamService.memberDelete(userId,teamId); + public Msg memberDelete(@RequestBody TeamVo vo){ + if(vo.getUserId()!=null&&vo.getTeamId()!=null){ + Boolean b = teamService.memberDelete(vo.getUserId(),vo.getTeamId()); if(b) return Msg.success("退出成功"); else diff --git a/src/main/java/com/javaee/newssystem/controller/UploadController.java b/src/main/java/com/javaee/newssystem/controller/UploadController.java new file mode 100644 index 0000000000000000000000000000000000000000..a374db1d185eb1c790085936f90e1b6e7d695292 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/controller/UploadController.java @@ -0,0 +1,24 @@ +package com.javaee.newssystem.controller; + +import com.javaee.newssystem.entity.Msg; +import com.javaee.newssystem.service.impl.UploadServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +public class UploadController { + + @Autowired + UploadServiceImpl uploadService; + + @PostMapping("/upload") + public Msg upload( @RequestPart(value = "headImg") MultipartFile headImg){ + String name = uploadService.upload(headImg); + if(name!=null) + return Msg.success("上传成功").add("data",name); + return Msg.fail("上传失败"); + } +} diff --git a/src/main/java/com/javaee/newssystem/controller/UserController.java b/src/main/java/com/javaee/newssystem/controller/UserController.java index 928984a3445999488ecbea45448b6dcb8f893649..de3ffad48759a9c19ba5bd32cac8fba3c2bff674 100644 --- a/src/main/java/com/javaee/newssystem/controller/UserController.java +++ b/src/main/java/com/javaee/newssystem/controller/UserController.java @@ -7,16 +7,18 @@ import com.javaee.newssystem.entity.User; import com.javaee.newssystem.service.impl.UserServiceImpl; import com.javaee.newssystem.utils.CheckClassUtil; import com.javaee.newssystem.utils.JwtUtil; +import com.javaee.newssystem.vo.UserRespVo; +import com.javaee.newssystem.vo.UserVo; import com.mysql.cj.util.StringUtils; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletRequest; -import java.util.Date; -import java.util.Enumeration; +import javax.validation.Valid; import java.util.List; +import java.util.Map; /** *

@@ -35,18 +37,23 @@ public class UserController { // 用户登录 @RequestMapping(value = "/login",method = RequestMethod.POST) - public Msg Login(String userName,String userPassword){ + public Msg Login(@RequestBody UserVo userVo){ + String userName = userVo.getUserName(); + String userPassword = userVo.getUserPassword(); if(StringUtils.isNullOrEmpty(userName)||StringUtils.isNullOrEmpty(userPassword)){ return Msg.fail("登录失败,缺少参数"); } else { - User user = userService.Login(userName, userPassword); - if (user!=null){ - Msg msg = Msg.success("登录成功"); - msg.add("data",user); + Long userId = userService.Login(userName, userPassword); + if (userId!=null){ + UserRespVo vo = userService.getUserInfo(userId); + if(vo!=null){ + Msg msg = Msg.success("登录成功").add("data",vo); // 生成token - msg.add("token", JwtUtil.getToken(user.getUserId(),"用户")); - return msg; + msg.add("token", JwtUtil.getToken(vo.getUserId(),"用户")); + return msg; + } + return Msg.fail("登录成功,但服务器内部出现错误"); } else return Msg.fail("账号或密码错误"); @@ -55,54 +62,51 @@ public class UserController { // 用户注册 @RequestMapping(value = "/register",method = RequestMethod.POST) - public Msg Register(User user){ + public Msg Register(@RequestBody @Valid User user){ if (CheckClassUtil.checkUser(user)){ - userService.Register(user); - if(user.getUserId()!=null){ - Msg msg = Msg.success("注册成功"); - user.setUserPassword(null); - msg.add("data",user); - return msg; - } - else - return Msg.fail("用户名已存在"); + Boolean b = userService.Register(user); + return b?Msg.success("注册成功"):Msg.fail("用户已存在"); } return Msg.fail("注册失败,缺少参数"); } // 用户修改信息 @RequestMapping(value = "/update/info",method = RequestMethod.POST) - public Msg updateInfo(User user,@RequestPart("headImg") MultipartFile headImg){ + public Msg updateInfo(@RequestBody @Valid User user){ if(user.getUserId()!=null){ - user = userService.updateInfo(user, headImg); - if(user!=null){ - Msg msg = Msg.success("修改成功"); - user.setUserPassword(null); - msg.add("data",user); - return msg; + UserRespVo vo = userService.updateInfo(user); + if(vo!=null){ + return Msg.success("修改成功").add("data",vo); } else - Msg.fail("修改失败"); + return Msg.fail("修改失败"); } return Msg.fail("修改失败,缺少用户id"); } // 用户获取个人信息(通过token) @GetMapping("/info") - public Msg userInfo(HttpServletRequest request){ - String token = request.getHeader("token"); - User user = userService.getUserInfo(token); - if(user!=null){ - return Msg.success("获取成功").add("data",user); - } - else { - return Msg.fail("不存在此用户"); + public Msg userInfo(@RequestHeader("token") String token){ + Map map = JwtUtil.parse(token); + if((Boolean) map.get("status")){ + Long id = (Long) map.get("id"); + UserRespVo vo = userService.getUserInfo(id); + if(vo!=null){ + return Msg.success("获取成功").add("data",vo); + } + else { + return Msg.fail("不存在此用户"); + } } + return Msg.fail("token失效,请重新登录"); } // 用户修改密码 @PostMapping("/update/password") - public Msg updatePassword(Long userId,String oldPassword,String newPassword){ + public Msg updatePassword(@RequestBody UserVo userVo){ + Long userId = userVo.getUserId(); + String oldPassword = userVo.getOldPassword(); + String newPassword = userVo.getNewPassword(); if(userId!=null&&CheckClassUtil.checkStringList(oldPassword,newPassword)){ Boolean b = userService.updatePassword(userId,oldPassword,newPassword); return b?Msg.success("修改密码成功"):Msg.fail("密码错误"); @@ -112,15 +116,10 @@ public class UserController { // 用户注销账号 @RequestMapping(value = "logout",method = RequestMethod.POST) - public Msg Logout(Long userId){ - if(userId!=null){ - Boolean b = userService.Logout(userId); - if(b){ - return Msg.success("注销成功"); - } - else { - return Msg.fail("该用户已被注销"); - } + public Msg Logout(@RequestBody UserVo vo){ + if(vo.getUserId()!=null){ + Boolean b = userService.Logout(vo.getUserId()); + return b?Msg.success("注销成功"):Msg.fail("该用户已被注销"); } return Msg.fail("缺少参数"); } @@ -129,40 +128,32 @@ public class UserController { @RequestMapping(value = "/focus",method = RequestMethod.GET) public Msg getFocusUser(Long userId,Integer current,Integer size){ if(userId!=null&¤t!=null&&size!=null){ - Page page = userService.getFocusUser(userId, current, size); - Msg msg = Msg.success("查询成功"); - msg.add("data",page); - return msg; + Page page = userService.getFocusUser(userId, current, size); + return Msg.success("查询成功").add("data",page); } return Msg.fail("缺少参数"); } // 添加关注用户 @RequestMapping(value = "/focus",method = RequestMethod.POST) - public Msg addFocusUser(Long userId,Long focusedUserId){ + public Msg addFocusUser(@RequestBody UserVo userVo){ + Long userId = userVo.getUserId(); + Long focusedUserId = userVo.getFocusedUserId(); if(userId!=null&&focusedUserId!=null){ Boolean b = userService.addFocusUser(userId, focusedUserId); - if(b){ - return Msg.success("添加关注成功"); - } - else { - return Msg.fail("添加关注失败"); - } + return b?Msg.success("取消关注成功"):Msg.fail("该用户已被关注"); } return Msg.fail("缺少参数"); } // 取消关注用户 @RequestMapping(value = "/unfocus",method = RequestMethod.POST) - public Msg unfocus(Long userId,Long focusedUserId){ + public Msg unfocus(@RequestBody UserVo userVo){ + Long userId = userVo.getUserId(); + Long focusedUserId = userVo.getFocusedUserId(); if(userId!=null&&focusedUserId!=null){ Boolean b = userService.unFocus(userId, focusedUserId); - if(b){ - return Msg.success("取消关注成功"); - } - else { - return Msg.fail("该用户未被关注"); - } + return b?Msg.success("取消关注成功"):Msg.fail("该用户未被关注"); } return Msg.fail("缺少参数"); } @@ -171,13 +162,11 @@ public class UserController { @RequestMapping(value = "/search",method = RequestMethod.GET) public Msg search(String userName){ if(!StringUtils.isNullOrEmpty(userName)){ - List userList = userService.search(userName); - if (!userList.isEmpty()){ - Msg msg = Msg.success("查找成功"); - msg.add("data",userList); - return msg; + List voList = userService.search(userName); + if (!voList.isEmpty()){ + return Msg.success("查找成功").add("data",voList); } - else return Msg.fail("不存在此人"); + else return Msg.fail("查无此人"); } return Msg.fail("缺少参数"); } diff --git a/src/main/java/com/javaee/newssystem/entity/HotWord.java b/src/main/java/com/javaee/newssystem/entity/HotWord.java new file mode 100644 index 0000000000000000000000000000000000000000..0367a315676f6635984688b83f45aa0aa147b2ad --- /dev/null +++ b/src/main/java/com/javaee/newssystem/entity/HotWord.java @@ -0,0 +1,18 @@ +package com.javaee.newssystem.entity; + + +import lombok.Data; + +@Data +public class HotWord { + + String hotWord; + Integer num; + + + + public HotWord(String hotWord, Integer num) { + this.hotWord = hotWord; + this.num = num; + } +} diff --git a/src/main/java/com/javaee/newssystem/entity/Msg.java b/src/main/java/com/javaee/newssystem/entity/Msg.java index 0f38a69df1bd35fb22eaf80710f77b56b106f676..403ca026e52229799d68722c651ee618d0f7070f 100644 --- a/src/main/java/com/javaee/newssystem/entity/Msg.java +++ b/src/main/java/com/javaee/newssystem/entity/Msg.java @@ -1,5 +1,7 @@ package com.javaee.newssystem.entity; + + import java.util.HashMap; import java.util.Map; @@ -7,25 +9,31 @@ public class Msg { private String msg; // 200:成功,0:失败 private Integer status; - private Map data = new HashMap<>(); + private Map data; public Msg add(String key,Object value){ + if(data==null){ + data = new HashMap<>(); + } data.put(key,value); return this; } public static Msg success(String msg){ - Msg msgClass = new Msg(); - msgClass.setMsg(msg); - msgClass.setStatus(200); - return msgClass; + return new Msg(msg,200); } public static Msg fail(String msg){ - Msg msgClass = new Msg(); - msgClass.setMsg(msg); - msgClass.setStatus(0); - return msgClass; + return new Msg(msg,0); + } + + public static Msg fail(String msg,Integer status){ + return new Msg(msg,status); + } + + private Msg(String msg, Integer status ) { + this.msg = msg; + this.status = status; } private void setMsg(String msg) { diff --git a/src/main/java/com/javaee/newssystem/entity/News.java b/src/main/java/com/javaee/newssystem/entity/News.java index 96503ca9773a07f721c11e90e1226ff45898155b..f58627483eaab7f7f3596f318979ae3c13621fb9 100644 --- a/src/main/java/com/javaee/newssystem/entity/News.java +++ b/src/main/java/com/javaee/newssystem/entity/News.java @@ -1,8 +1,10 @@ package com.javaee.newssystem.entity; + import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; +import javax.validation.constraints.Pattern; import java.io.Serializable; import java.util.Date; @@ -37,6 +39,7 @@ public class News implements Serializable { /** * 新闻标题 */ + @Pattern(regexp = "^.{3,100}$",message = "标题长度必须在3-100之间") private String title; /** @@ -65,13 +68,7 @@ public class News implements Serializable { @TableLogic private Integer status; - public Long getNewsId() { - return newsId; - } - public void setNewsId(Long newsId) { - this.newsId = newsId; - } public Long getUserId() { return userId; } @@ -79,6 +76,15 @@ public class News implements Serializable { public void setUserId(Long userId) { this.userId = userId; } + + public Long getNewsId() { + return newsId; + } + + public void setNewsId(Long newsId) { + this.newsId = newsId; + } + public String getCategory() { return category; } @@ -132,15 +138,15 @@ public class News implements Serializable { @Override public String toString() { return "News{" + - "newsId=" + newsId + - ", userId=" + userId + - ", category=" + category + - ", title=" + title + - ", content=" + content + - ", createTime=" + createTime + - ", belongTeamId=" + belongTeamId + - ", state=" + state + - ", status=" + status + - "}"; + "newsId=" + newsId + + ", userId=" + userId + + ", category='" + category + '\'' + + ", title='" + title + '\'' + + ", content='" + content + '\'' + + ", createTime=" + createTime + + ", belongTeamId=" + belongTeamId + + ", state='" + state + '\'' + + ", status=" + status + + '}'; } } diff --git a/src/main/java/com/javaee/newssystem/entity/Team.java b/src/main/java/com/javaee/newssystem/entity/Team.java index 80ab34c75592610cadaf7b02a500651f1f840c0e..b271d396f9d098b281a0e28a005b7f8d09b290b4 100644 --- a/src/main/java/com/javaee/newssystem/entity/Team.java +++ b/src/main/java/com/javaee/newssystem/entity/Team.java @@ -3,6 +3,7 @@ package com.javaee.newssystem.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; +import javax.validation.constraints.Pattern; import java.io.Serializable; import java.util.Date; @@ -27,6 +28,7 @@ public class Team implements Serializable { /** * 团队名字 */ + @Pattern(regexp = "^.{3,20}$",message = "团队名字长度必须在3-20之间") private String teamName; /** diff --git a/src/main/java/com/javaee/newssystem/entity/User.java b/src/main/java/com/javaee/newssystem/entity/User.java index 4aab674a64f4debabe18637dfecf55e401019a28..6ba96c220b52ba5403038a222458c5f80d7eafcc 100644 --- a/src/main/java/com/javaee/newssystem/entity/User.java +++ b/src/main/java/com/javaee/newssystem/entity/User.java @@ -3,6 +3,8 @@ package com.javaee.newssystem.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; import java.io.Serializable; import java.util.Date; @@ -14,6 +16,7 @@ import java.util.Date; * @author qjj * @since 2022-11-28 */ + public class User implements Serializable { private static final long serialVersionUID = 1L; @@ -27,21 +30,25 @@ public class User implements Serializable { /** * 用户名 */ + @Pattern(regexp = "^.{3,20}$",message = "用户名长度必须在3-20之间") private String userName; /** * 密码 */ + @Pattern(regexp = "^[a-zA-Z]\\w{5,17}$",message = "密码必须以字母开头,长度在6~18之间,只能包含字母、数字和下划线") private String userPassword; /** * 手机号 */ + @Pattern(regexp = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$",message = "手机号格式不对") private String userPhone; /** * 邮箱,对照着用户id,登录使用 */ + @Pattern(regexp = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$",message = "邮箱格式不对") private String userEmail; /** diff --git a/src/main/java/com/javaee/newssystem/interceptor/LoginInterceptor.java b/src/main/java/com/javaee/newssystem/interceptor/LoginInterceptor.java index 8728c71b59813253ea7d79738decbfc525a21e09..d61832b69d24f57952286bae98689cfd51e37cea 100644 --- a/src/main/java/com/javaee/newssystem/interceptor/LoginInterceptor.java +++ b/src/main/java/com/javaee/newssystem/interceptor/LoginInterceptor.java @@ -26,7 +26,7 @@ public class LoginInterceptor implements HandlerInterceptor { } else { mapjson.put("code","402"); - mapjson.put("msg","登录过期"); + mapjson.put("msg","登录过期,请重新登录"); } } else { diff --git a/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java b/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java index adb9316639397b1c344eddd55a4c85a109187ad4..adad32c58200b8e7ef9e922265f94ad798d90bc3 100644 --- a/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java +++ b/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java @@ -2,8 +2,10 @@ package com.javaee.newssystem.mapper; import com.javaee.newssystem.entity.Comment; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Insert; import org.springframework.stereotype.Repository; +import java.util.Date; import java.util.List; @Repository @@ -17,4 +19,5 @@ public interface CommentMapper extends BaseMapper { List selectLikeByUserId(Long userId); + Integer isExist(Long userId, Long commentId); } diff --git a/src/main/java/com/javaee/newssystem/mapper/JacksonObjectMapper.java b/src/main/java/com/javaee/newssystem/mapper/JacksonObjectMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..eb2949d775b0faf08f1c657eee41d226c1a0682d --- /dev/null +++ b/src/main/java/com/javaee/newssystem/mapper/JacksonObjectMapper.java @@ -0,0 +1,23 @@ +package com.javaee.newssystem.mapper; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; + +public class JacksonObjectMapper extends ObjectMapper { + + public JacksonObjectMapper(){ + super(); +// 收到未知属性时不报异常 + this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); + +// 反序列化时,属性不存在的兼容处理 + this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + SimpleModule simpleModule = new SimpleModule() + .addSerializer(Long.class, ToStringSerializer.instance) + .addSerializer(long.class, ToStringSerializer.instance); +// 注册 + this.registerModule(simpleModule); + } +} diff --git a/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java b/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java index c26a376d7c3c9f64ac3ade7056c97c8de54f24d0..2811c0e6152754057b23b5a2532cc6b356476508 100644 --- a/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java +++ b/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java @@ -1,6 +1,5 @@ package com.javaee.newssystem.mapper; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.javaee.newssystem.entity.News; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.springframework.stereotype.Repository; @@ -20,4 +19,11 @@ public interface NewsMapper extends BaseMapper { List getFocusListByid(Long userId); Integer getFocusNewsListByid(Long newsId); + + Integer insertToFocusWithNews(Long newsId, Long userId); + + Integer deleteFromFocusWithNews(Long newsId, Long userId); + + + Integer isExist(Long newsId, Long userId); } diff --git a/src/main/java/com/javaee/newssystem/mapper/UserMapper.java b/src/main/java/com/javaee/newssystem/mapper/UserMapper.java index 167551334c9a0876758ad43afb565acd445460f0..4a6df551431dbd2802d1df4f9c23f0f6a5e74c8b 100644 --- a/src/main/java/com/javaee/newssystem/mapper/UserMapper.java +++ b/src/main/java/com/javaee/newssystem/mapper/UserMapper.java @@ -1,10 +1,12 @@ package com.javaee.newssystem.mapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.javaee.newssystem.entity.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.springframework.stereotype.Repository; import java.util.List; +import java.util.Map; /** *

@@ -21,7 +23,12 @@ public interface UserMapper extends BaseMapper { Integer insertFocus(Long userId,Long focusedUserId); - Integer delete(Long userId,Long focusedUserId); + Integer deleteFromFocusAndUser(Long userId,Long focusedUserId); Integer changeStatus(Long userId); + + Integer isExist(Long userId,Long newsId); + + Integer isExistInFocusUser(Long userId,Long focusedUserId); + } diff --git a/src/main/java/com/javaee/newssystem/mybatisgener.java b/src/main/java/com/javaee/newssystem/mybatisgener.java deleted file mode 100644 index ebd640e5a1d3f6de8a0512e2e7315c2fbc810f2f..0000000000000000000000000000000000000000 --- a/src/main/java/com/javaee/newssystem/mybatisgener.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.javaee.newssystem; - -import com.baomidou.mybatisplus.generator.FastAutoGenerator; -import com.baomidou.mybatisplus.generator.config.OutputFile; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; - -import java.util.Collections; -//代码生成器,不要运行! -public class mybatisgener { - - public static void main(String[] args) { - FastAutoGenerator.create("jdbc:mysql://124.70.20.202:3306/javaee?serverTimezone=GMT","root","QQqq814287041") - .globalConfig(builder -> { - builder.author("qjj") - .fileOverride() - .outputDir("D:\\ProgramFiles\\IdeaProjects\\news-system\\src\\main\\java"); - }) - .packageConfig(builder -> { - builder.parent("com.javaee") - .moduleName("newssystem") - .pathInfo(Collections.singletonMap(OutputFile.mapperXml,"D:\\ProgramFiles\\IdeaProjects\\news-system\\src\\main\\resources\\mapper")); - }) - .strategyConfig(builder -> { - builder.addInclude("admin","comment","news","team","user"); - }) - .templateEngine(new FreemarkerTemplateEngine()) - .execute(); - } -} diff --git a/src/main/java/com/javaee/newssystem/service/IAdminService.java b/src/main/java/com/javaee/newssystem/service/IAdminService.java index 36426d5dcfe7f3cb03f90f6ac063be462e82ecf1..371f43ab5b75ed31209899d4afe091e1a19b94ab 100644 --- a/src/main/java/com/javaee/newssystem/service/IAdminService.java +++ b/src/main/java/com/javaee/newssystem/service/IAdminService.java @@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.javaee.newssystem.entity.Admin; import com.baomidou.mybatisplus.extension.service.IService; import com.javaee.newssystem.entity.User; +import com.javaee.newssystem.vo.AdminVo; /** *

@@ -15,6 +16,6 @@ import com.javaee.newssystem.entity.User; */ public interface IAdminService extends IService { - Admin Login(String userName,String password); + AdminVo Login(String userName, String password); } diff --git a/src/main/java/com/javaee/newssystem/service/ICommentService.java b/src/main/java/com/javaee/newssystem/service/ICommentService.java index 975e2e3bf8c8001f4f1f6112d884cf7c790a8edb..629406200ab8b1a198b5453ba64dc42b4f8a2171 100644 --- a/src/main/java/com/javaee/newssystem/service/ICommentService.java +++ b/src/main/java/com/javaee/newssystem/service/ICommentService.java @@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.extension.service.IService; import com.javaee.newssystem.entity.News; import com.javaee.newssystem.entity.Team; import com.javaee.newssystem.entity.User; +import com.javaee.newssystem.vo.CommentVo; import org.springframework.web.multipart.MultipartFile; /** @@ -18,7 +19,7 @@ import org.springframework.web.multipart.MultipartFile; */ public interface ICommentService extends IService { - Comment createComment(Comment comment); + CommentVo createComment(Comment comment); Boolean createLike(Long userId, Long commentId); @@ -26,10 +27,12 @@ public interface ICommentService extends IService { Boolean deleteComment(Long commentId); - Page GetFirstCommentList(Long newsId,Integer current, Integer size); + Page GetFirstCommentList(Long newsId, Integer current, Integer size, String token); - Page GetMyselfList(Long userId, Integer current, Integer size); + Page GetMyselfList(Long userId, Integer current, Integer size); - Page getLikeComment(Long userId, Integer current, Integer size); + Page getLikeComment(Long userId, Integer current, Integer size); + + Page GetSecondCommentList(Long userId, Integer current, Integer size,String token); } diff --git a/src/main/java/com/javaee/newssystem/service/INewsService.java b/src/main/java/com/javaee/newssystem/service/INewsService.java index 3d98e095f28f503099ff5f81da4811fb809c0153..1f037e44d3d3aa2e89c21de238a1367f999b117e 100644 --- a/src/main/java/com/javaee/newssystem/service/INewsService.java +++ b/src/main/java/com/javaee/newssystem/service/INewsService.java @@ -1,9 +1,13 @@ package com.javaee.newssystem.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.javaee.newssystem.entity.HotWord; import com.javaee.newssystem.entity.News; import com.baomidou.mybatisplus.extension.service.IService; import com.javaee.newssystem.mapper.NewsMapper; +import com.javaee.newssystem.vo.NewsVo; + +import java.util.List; /** *

@@ -15,34 +19,46 @@ import com.javaee.newssystem.mapper.NewsMapper; */ public interface INewsService extends IService { - Page GetPublicList(Integer current, Integer size); + Page GetPublicList(Integer current, Integer size,String token); - void CreateNews(News news); + NewsVo CreateNews(News news,String token); - void SaveNews(News news); + NewsVo SaveNews(News news,String token); - Page GetFocusList(Long userId, Integer current, Integer size); + Page GetFocusList(Long userId, Integer current, Integer size); - Page GetTeamList(Long teamId,Integer current, Integer size); + Page GetTeamList(Long teamId,Integer current, Integer size,String token); - Page GetMyselfList(Long userId, Integer current, Integer size); + Page GetMyselfList(Long userId, Integer current, Integer size,String token); - News updateInfo(News news); + NewsVo updateInfo(News news,String token); Boolean deleteNews(Long newsId); - Page GetPassList(Integer current, Integer size); + Page GetPassList(Integer current, Integer size,String token); - Page GetUnPassList(Integer current, Integer size); + Page GetUnPassList(Integer current, Integer size); - Page GetUnReviewed(Integer current, Integer size); + Page GetUnReviewed(Integer current, Integer size); - Page GetSaveNews(Long userId, Integer current, Integer size); + Page GetSaveNews(Long userId, Integer current, Integer size); Boolean PassNews(Long newsId); Integer GetFocusNews(Long newsId); Boolean UnPassNews(Long newsId); + + Page searchNews(String key, Integer current, Integer size,String token); + + Page addUserInfo(Page page,Long requestorId); + + NewsVo addUserInfo(News news,Long requestorId); + + Boolean UserFocusNews(Long newsId,Long userId); + + Boolean UserCancelFocusNews(Long newsId, Long userId); + + Page getNewsListBycategory(String key, Integer current, Integer size); } diff --git a/src/main/java/com/javaee/newssystem/service/ITeamService.java b/src/main/java/com/javaee/newssystem/service/ITeamService.java index bb2d032da7f7eb8c2e9d74000e3378fa07d2696c..15da038c874fe2479f1639e9a952d478ee465a14 100644 --- a/src/main/java/com/javaee/newssystem/service/ITeamService.java +++ b/src/main/java/com/javaee/newssystem/service/ITeamService.java @@ -17,11 +17,11 @@ import java.util.List; */ public interface ITeamService extends IService { - Team createTeam(Team team, MultipartFile headImg); + Team createTeam(Team team); Page getTeamList(Long userId, Integer current, Integer size); - Team updateInfo(Team team, MultipartFile headImg); + Team updateInfo(Team team); Boolean deleteTeam(Long teamId); diff --git a/src/main/java/com/javaee/newssystem/service/IUploadService.java b/src/main/java/com/javaee/newssystem/service/IUploadService.java new file mode 100644 index 0000000000000000000000000000000000000000..4049d0865d45c5dcbf7bc678765b4221d1128ff3 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/IUploadService.java @@ -0,0 +1,7 @@ +package com.javaee.newssystem.service; + +import org.springframework.web.multipart.MultipartFile; + +public interface IUploadService { + String upload(MultipartFile headImg); +} diff --git a/src/main/java/com/javaee/newssystem/service/IUserService.java b/src/main/java/com/javaee/newssystem/service/IUserService.java index 2bb1fe403142cbae054ad0b7887dc7af0e208418..3d155482276031f2731bfb97f321ecee92eff056 100644 --- a/src/main/java/com/javaee/newssystem/service/IUserService.java +++ b/src/main/java/com/javaee/newssystem/service/IUserService.java @@ -3,6 +3,7 @@ package com.javaee.newssystem.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.javaee.newssystem.entity.User; import com.baomidou.mybatisplus.extension.service.IService; +import com.javaee.newssystem.vo.UserRespVo; import org.springframework.web.multipart.MultipartFile; import java.util.List; @@ -17,29 +18,29 @@ import java.util.List; */ public interface IUserService extends IService { - User Login(String userName,String password); + Long Login(String userName,String password); - void Register(User user); + Boolean Register(User user); - User updateInfo(User user, MultipartFile headImg); + UserRespVo updateInfo(User user); Boolean Logout(Long userId); - Page getFocusUser(Long userId, Integer current, Integer size); + Page getFocusUser(Long userId, Integer current, Integer size); Boolean addFocusUser(Long userId,Long focusedUserId); Boolean unFocus(Long userId,Long focusedUserId); - Page adminGetUserList(Integer current,Integer size); + Page adminGetUserList(Integer current,Integer size); Boolean adminLogoutUser(Long userId); Boolean adminUnlogoutUser(Long userId); - List search(String userName); + List search(String userName); Boolean updatePassword(Long userId, String oldPassword, String newsPassword); - User getUserInfo(String token); + UserRespVo getUserInfo(Long userId); } diff --git a/src/main/java/com/javaee/newssystem/service/RedisService.java b/src/main/java/com/javaee/newssystem/service/RedisService.java new file mode 100644 index 0000000000000000000000000000000000000000..36c3ee15c64cd582a27f1edb344df3fd69aedce1 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/RedisService.java @@ -0,0 +1,14 @@ +package com.javaee.newssystem.service; + +import com.javaee.newssystem.entity.HotWord; + +import java.util.List; + +public interface RedisService { + + List getHotKey(Integer number); + + Integer getUserNumber(); + + Double[] getNewsNumber(); +} diff --git a/src/main/java/com/javaee/newssystem/service/ScheduledService.java b/src/main/java/com/javaee/newssystem/service/ScheduledService.java new file mode 100644 index 0000000000000000000000000000000000000000..df9e8a43ce12d2360c1457830582d356a6f95241 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/ScheduledService.java @@ -0,0 +1,85 @@ +package com.javaee.newssystem.service; + +import com.javaee.newssystem.entity.HotWord; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ScanOptions; +import org.springframework.data.redis.core.ZSetOperations; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Iterator; +import java.util.Set; + +@Service +public class ScheduledService { + + /** + * second(秒),minute(分),hour(时),day of month(日),month(月),day of week(周几). + * + */ + +// @Scheduled(cron = "0/10 * * * * *") + public void hello(){ + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + System.out.println("当前时间:"+simpleDateFormat.format(new Date())); + System.out.println("hello(测试定时任务,每10秒输出)"); + } + + @Autowired + RedisTemplate redisTemplate; + +// 每天凌晨0点执行,清理热搜内容。 + @Scheduled(cron = "0 0 0 * * *") + public void redisHotKeyClean(){ + Set> typedTupleSet = redisTemplate.opsForZSet().reverseRangeByScoreWithScores("newsHotKey",1,50000); + Iterator> iterator = typedTupleSet.iterator(); + int flag = 0; + double score = 1; + while (iterator.hasNext()){ + flag++; + ZSetOperations.TypedTuple typedTuple = iterator.next(); + score = Math.ceil(typedTuple.getScore()); + if(flag>=200) + break; + } + if (flag>=201) + redisTemplate.opsForZSet().removeRangeByScore("newsHotKey",1,score); + } + +// 每日末,删除第前七天的新增新闻量数据 + @Scheduled(cron = "59 59 23 * * *") + public void redisNewsNumberClean(){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 6); + String startTime = sdf.format(calendar.getTime()); + redisTemplate.opsForZSet().remove("newsNumber", startTime); + } + +// 每日初,加入今天的‘新增新闻量’属性 + @Scheduled(cron = "1 0 0 * * *") + public void redisNewsNumberAdd(){ + String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); + redisTemplate.opsForZSet().incrementScore("newsNumber",format,0); + } + +// 每30秒统计日活跃人数 + @Scheduled(cron = "0/30 * * * * *") + public void getActiveUserNumber(){ + ScanOptions scanOptions = ScanOptions.scanOptions().count(10L).match("userInfo" + "*").build(); + Cursor cursors = redisTemplate.scan(scanOptions); + Long number = 0L; + while (cursors.hasNext()){ + cursors.next(); + number++; + } + cursors.close(); + redisTemplate.opsForValue().set("ActiveUserNumber",number); + } + +} diff --git a/src/main/java/com/javaee/newssystem/service/impl/AdminServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/AdminServiceImpl.java index f6344c161db8e3c3861ec73c7c706c75a65842bd..1d435d7224e79826205dc61e9067e7ace81f0a06 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/AdminServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/AdminServiceImpl.java @@ -7,6 +7,8 @@ import com.javaee.newssystem.mapper.AdminMapper; import com.javaee.newssystem.service.IAdminService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.javaee.newssystem.utils.MD5Util; +import com.javaee.newssystem.vo.AdminVo; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -30,7 +32,7 @@ public class AdminServiceImpl extends ServiceImpl implements AdminMapper adminMapper; @Override - public Admin Login(String adminName, String adminPassword) { + public AdminVo Login(String adminName, String adminPassword) { try { Map map = new HashMap<>(); map.put("admin_name",adminName); @@ -39,7 +41,9 @@ public class AdminServiceImpl extends ServiceImpl implements if(adminList!=null&&!adminList.isEmpty()){ Admin admin = adminList.get(0); admin.setAdminPassword(null); - return admin; + AdminVo vo = new AdminVo(); + BeanUtils.copyProperties(admin,vo); + return vo; } } catch (Exception e) { return null; diff --git a/src/main/java/com/javaee/newssystem/service/impl/CommentServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/CommentServiceImpl.java index 2b4765f37668895e0954cf6131bd8a7f27be8152..a05d84216e75de24a31c2dcfd1a46dbc59c56220 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/CommentServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/CommentServiceImpl.java @@ -7,8 +7,13 @@ import com.javaee.newssystem.entity.News; import com.javaee.newssystem.entity.Team; import com.javaee.newssystem.entity.User; import com.javaee.newssystem.mapper.CommentMapper; +import com.javaee.newssystem.mapper.UserMapper; import com.javaee.newssystem.service.ICommentService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.javaee.newssystem.utils.JwtUtil; +import com.javaee.newssystem.vo.CommentVo; +import com.javaee.newssystem.vo.NewsVo; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -16,6 +21,7 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** *

@@ -31,13 +37,16 @@ public class CommentServiceImpl extends ServiceImpl impl @Autowired CommentMapper commentMapper; + @Autowired + UserMapper userMapper; + @Override - public Comment createComment(Comment comment) { + public CommentVo createComment(Comment comment) { comment.setCreateTime(new Date()); System.out.println(new Date()); comment.setStatus(0); commentMapper.insert(comment); - return comment; + return addUserInfo(comment,comment.getUserId()); } @Override @@ -57,27 +66,26 @@ public class CommentServiceImpl extends ServiceImpl impl } - public Page GetFirstCommentList(Long newsId,Integer current, Integer size) { + @Override + public Page GetFirstCommentList(Long newsId, Integer current, Integer size, String token) { Page page=new Page<>(current,size); QueryWrapper queryWrapper=new QueryWrapper(); - queryWrapper.eq("news_id",newsId); - queryWrapper.eq("status","0"); - queryWrapper.eq("parent_comment_id","0"); + queryWrapper.eq("news_id",newsId).eq("parent_comment_id",0L); commentMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,tokenToRequestorId(token)); } @Override - public Page GetMyselfList(Long userId, Integer current, Integer size) { + public Page GetMyselfList(Long userId, Integer current, Integer size) { Page page=new Page<>(current,size); QueryWrapper queryWrapper=new QueryWrapper(); queryWrapper.eq("user_id",userId); commentMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,userId); } @Override - public Page getLikeComment(Long userId, Integer current, Integer size) { + public Page getLikeComment(Long userId, Integer current, Integer size) { List likeCommentIdList = commentMapper.selectLikeByUserId(userId); System.out.println(likeCommentIdList); QueryWrapper queryWrapper = new QueryWrapper<>(); @@ -87,16 +95,66 @@ public class CommentServiceImpl extends ServiceImpl impl Page page = new Page<>(current,size); commentMapper.selectPage(page,queryWrapper); System.out.println(page); - return page; + return addUserInfo(page,userId); } - - public Page GetSecondCommentList(Long commentId,Integer current, Integer size) { + @Override + public Page GetSecondCommentList(Long commentId,Integer current, Integer size,String token) { Page page=new Page<>(current,size); QueryWrapper queryWrapper=new QueryWrapper(); - queryWrapper.eq("status","0"); queryWrapper.eq("parent_comment_id",commentId); commentMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,tokenToRequestorId(token)); + } + + + public Page addUserInfo(Page page, Long requestorId) { + List commentList = page.getRecords(); + + List commentVoList = commentList.stream().map(news -> { + CommentVo newsVo = addUserInfo(news, requestorId); + return newsVo; + }).collect(Collectors.toList()); + +// List userIdList = newsList.stream().map(News::getUserId).collect(Collectors.toList()); +// List userList = userMapper.selectBatchIds(userIdList); +// for (NewsVo newsVo : newsVoList) { +// for (User user : userList) { +// if (user.getUserId().equals(newsVo.getUserId())){ +// newsVo.setUserName(user.getUserName()); +// newsVo.setUserIcon(user.getUserIcon()); +// userList.remove(user); +// break; +// } +// } +// } + Page commentVoPage = new Page<>(); + BeanUtils.copyProperties(page,commentVoPage); + commentVoPage.setRecords(commentVoList); + return commentVoPage; + } + + public CommentVo addUserInfo(Comment comment,Long requestorId) { + CommentVo vo = new CommentVo(); + BeanUtils.copyProperties(comment,vo); + vo.setIsLike(false); + User user = userMapper.selectById(comment.getUserId()); + if (user==null) return vo; + vo.setUserIcon(user.getUserIcon()); + vo.setUserName(user.getUserName()); + if(requestorId!=null){ + Integer i = commentMapper.isExist(requestorId,vo.getNewsId()); + vo.setIsLike(i>0); + } + return vo; + } + + private Long tokenToRequestorId(String token){ + Map map = JwtUtil.parse(token); + Long requestorId = null; + if((Boolean) map.get("status")){ + requestorId = (Long) map.get("id"); + } + return requestorId; } } diff --git a/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java index 02bf2bfe39f36b9237fd8e86a0547d497c38100c..5c75b862d56390543903c72feb373262060261c9 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java @@ -3,17 +3,25 @@ package com.javaee.newssystem.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.javaee.newssystem.entity.News; +import com.javaee.newssystem.entity.User; import com.javaee.newssystem.mapper.NewsMapper; +import com.javaee.newssystem.mapper.UserMapper; import com.javaee.newssystem.service.INewsService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.javaee.newssystem.utils.JwtUtil; +import com.javaee.newssystem.vo.NewsVo; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.text.SimpleDateFormat; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** *

@@ -23,57 +31,62 @@ import java.util.Map; * @author qjj * @since 2022-11-28 */ +@CacheConfig(cacheNames = "newsInfo") @Service - public class NewsServiceImpl extends ServiceImpl implements INewsService { @Autowired NewsMapper newsMapper; + @Autowired + UserMapper userMapper; + @Autowired + RedisTemplate redisTemplate; @Override - public Page GetPublicList(Integer current, Integer size) { + public Page GetPublicList(Integer current, Integer size,String token) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); - queryWrapper.eq("state","已通过"); + QueryWrapper queryWrapper=new QueryWrapper<>(); + queryWrapper.eq("state","已通过") + .isNull("belong_team_id"); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,tokenToRequestorId(token)); } @Override - public Page GetFocusList(Long userId, Integer current, Integer size) { - + public Page GetFocusList(Long userId, Integer current, Integer size) { Page page=new Page<>(current,size); List focusNewsId=newsMapper.getFocusListByid(userId); - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.in("news_id",focusNewsId); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,userId); } @Override - public Page GetTeamList(Long teamId,Integer current, Integer size) { + public Page GetTeamList(Long teamId,Integer current, Integer size,String token) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); - queryWrapper.eq("belong_team_id",teamId); + QueryWrapper queryWrapper=new QueryWrapper<>(); + queryWrapper.eq("belong_team_id",teamId).eq("state","已通过"); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,tokenToRequestorId(token)); } @Override - public Page GetMyselfList(Long userId, Integer current, Integer size) { + public Page GetMyselfList(Long userId, Integer current, Integer size,String token) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); - queryWrapper.eq("user_id",userId); + QueryWrapper queryWrapper=new QueryWrapper<>(); + queryWrapper.eq("user_id",userId) + .eq("state","已通过"); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,tokenToRequestorId(token)); } @Override - public News updateInfo(News news) { + public NewsVo updateInfo(News news,String token) { newsMapper.updateById(news); - return news; + return addUserInfo(news,tokenToRequestorId(token)); } @Override @@ -82,46 +95,46 @@ public class NewsServiceImpl extends ServiceImpl implements IN } @Override - public Page GetPassList(Integer current, Integer size) { + public Page GetPassList(Integer current, Integer size,String token) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("state","已通过"); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,tokenToRequestorId(token)); } @Override - public Page GetUnPassList(Integer current, Integer size) { + public Page GetUnPassList(Integer current, Integer size) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("state","未通过"); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,null); } @Override - public Page GetUnReviewed(Integer current, Integer size) { + public Page GetUnReviewed(Integer current, Integer size) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("state","未审核"); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,null); } @Override - public Page GetSaveNews(Long userId, Integer current, Integer size) { + public Page GetSaveNews(Long userId, Integer current, Integer size) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("state","已保存").and(wrapper->wrapper.eq("user_id",userId)); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,null); } @Override public Boolean PassNews(Long newsId) { News old=newsMapper.selectById(newsId); if(old!=null&&old.getState().equals("未审核")){ - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("news_id",newsId); News news=new News(); news.setState("已通过"); @@ -134,7 +147,7 @@ public class NewsServiceImpl extends ServiceImpl implements IN public Boolean UnPassNews(Long newsId) { News old=newsMapper.selectById(newsId); if(old!=null&&old.getState().equals("未审核")){ - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("news_id",newsId); News news=new News(); news.setState("未通过"); @@ -150,19 +163,118 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Transactional @Override - public void CreateNews(News news) { + public NewsVo CreateNews(News news,String token) { news.setState("未审核"); - news.setCreateTime(new Date()); + Date date = new Date(); + news.setCreateTime(date); news.setStatus(0); + String format = new SimpleDateFormat("yyyy-MM-dd").format(date); + redisTemplate.opsForZSet().incrementScore("newsNumber",format,1); newsMapper.insert(news); + return addUserInfo(news,tokenToRequestorId(token)); } @Override - public void SaveNews(News news) { + public NewsVo SaveNews(News news,String token) { news.setState("已保存"); - news.setCreateTime(new Date()); + Date date = new Date(); + news.setCreateTime(date); + String format = new SimpleDateFormat("yyyy-MM-dd").format(date); + redisTemplate.opsForZSet().incrementScore("newsNumber",format,1); news.setStatus(0); newsMapper.insert(news); + return addUserInfo(news,tokenToRequestorId(token)); + } + + @Override + public Page searchNews(String key, Integer current, Integer size,String token) { + redisTemplate.opsForZSet().incrementScore("newsHotKey",key,1); + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.like("title",key).eq("state","已通过") + .or() + .like("content",key).eq("state","已通过"); + Page page = newsMapper.selectPage(new Page<>(current, size), queryWrapper); + return addUserInfo(page,tokenToRequestorId(token)); } + @Override + public Page addUserInfo(Page page,Long requestorId) { + List newsList = page.getRecords(); + + List newsVoList = newsList.stream().map(news -> { + NewsVo newsVo = addUserInfo(news, requestorId); + return newsVo; + }).collect(Collectors.toList()); + +// List userIdList = newsList.stream().map(News::getUserId).collect(Collectors.toList()); +// List userList = userMapper.selectBatchIds(userIdList); +// for (NewsVo newsVo : newsVoList) { +// for (User user : userList) { +// if (user.getUserId().equals(newsVo.getUserId())){ +// newsVo.setUserName(user.getUserName()); +// newsVo.setUserIcon(user.getUserIcon()); +// userList.remove(user); +// break; +// } +// } +// } + Page newsVoPage = new Page<>(); + BeanUtils.copyProperties(page,newsVoPage); + newsVoPage.setRecords(newsVoList); + return newsVoPage; + } + + @Override + public NewsVo addUserInfo(News news,Long requestorId) { + NewsVo newsVo = new NewsVo(); + BeanUtils.copyProperties(news,newsVo); + User user = userMapper.selectById(news.getUserId()); + if (user==null) return newsVo; + newsVo.setUserIcon(user.getUserIcon()); + newsVo.setUserName(user.getUserName()); + if(requestorId!=null){ + Integer i = userMapper.isExist(requestorId,newsVo.getNewsId()); + newsVo.setIsFocus(i>0); + Integer j = userMapper.isExistInFocusUser(requestorId,newsVo.getUserId()); + newsVo.setIsFocusAuthor(j>0); + } + else { + newsVo.setIsFocus(false); + newsVo.setIsFocusAuthor(false); + } + return newsVo; + } + + @Override + public Boolean UserFocusNews(Long newsId,Long userId) { + Integer j = newsMapper.isExist(newsId,userId); + if(j>0) return false; + Integer i = newsMapper.insertToFocusWithNews(newsId,userId); + return i>0; + } + + @Override + public Boolean UserCancelFocusNews(Long newsId, Long userId) { + Integer j = newsMapper.isExist(newsId,userId); + if(j==0) return false; + Integer i = newsMapper.deleteFromFocusWithNews(newsId,userId); + return i>0; + } + + @Override + public Page getNewsListBycategory(String key, Integer current, Integer size) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("category",key).eq("state","已通过"); + Page page = newsMapper.selectPage(new Page(current,size), queryWrapper); + return addUserInfo(page, null); + } + + private Long tokenToRequestorId(String token){ + Map map = JwtUtil.parse(token); + Long requestorId = null; + if((Boolean) map.get("status")){ + requestorId = (Long) map.get("id"); + } + return requestorId; + } } diff --git a/src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..814e334ccaaaf93a5e45d60614d73c5c8f1278a8 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java @@ -0,0 +1,65 @@ +package com.javaee.newssystem.service.impl; + +import com.javaee.newssystem.entity.HotWord; +import com.javaee.newssystem.service.RedisService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ZSetOperations; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.*; + +@Service +public class RedisServiceImpl implements RedisService { + + @Autowired + RedisTemplate redisTemplate; + + @Override + public Double[] getNewsNumber(){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Double[] scores = new Double[7]; + for (int i = 0;i=0;i--){ + calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1); + value = sdf.format(calendar.getTime()); + score = redisTemplate.opsForZSet().score("newsNumber", value); + scores[i] = score; + } + return scores; + } + + @Override + public Integer getUserNumber(){ + Object number = redisTemplate.opsForValue().get("ActiveUserNumber"); + return (Integer) number; + } + + @Override + public List getHotKey(Integer number){ + if(number==null){ + number = 10; + } + List hotWordList = new ArrayList<>(); + Set> typedTupleSet = redisTemplate.opsForZSet().reverseRangeByScoreWithScores("newsHotKey",1,50000); + Iterator> iterator = typedTupleSet.iterator(); + int flag = 0; + while (iterator.hasNext()){ + flag++; + ZSetOperations.TypedTuple typedTuple = iterator.next(); + String value = (String)typedTuple.getValue(); + int score = (int) Math.ceil(typedTuple.getScore()); + HotWord hotWord = new HotWord(value,score); + hotWordList.add(hotWord); + if ( flag >= number ) break; + } + return hotWordList; + } +} diff --git a/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java index 2ebf226f0785e7b7ddb4daa1b24bf5e625d6a1fe..0c2228913e6faa1c486d77bb2c7c7af47fdd4a53 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java @@ -9,8 +9,10 @@ import com.javaee.newssystem.service.ITeamService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.javaee.newssystem.utils.MyUtil; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.FileSystemUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; @@ -35,23 +37,8 @@ public class TeamServiceImpl extends ServiceImpl implements IT TeamMapper teamMapper; @Override - public Team createTeam(Team team, MultipartFile headImg) { + public Team createTeam(Team team) { team.setCreateTime(new Date()); - //处理头像资源 - if(!headImg.isEmpty()){ -// 生成新的头像路径 - Map map = MyUtil.getPath(headImg); - try { -// 更新新头像资源并更新数据库 - headImg.transferTo(new File(map.get("headImgPath"))); - team.setTeamIcon(map.get("filename")); - teamMapper.insert(team); - return team; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } teamMapper.insert(team); return team; } @@ -67,37 +54,26 @@ public class TeamServiceImpl extends ServiceImpl implements IT return teamPage; } + @Value("${web.upload-path}") + private String uploadPath; + + @Transactional @Override - public Team updateInfo(Team team, MultipartFile headImg) { + public Team updateInfo(Team team) { //获取旧的团队信息 Team oldTeam = teamMapper.selectById(team); if(oldTeam==null){ return null; } - //处理头像资源 - if(!headImg.isEmpty()){ - -// 生成新的头像路径 - Map map = MyUtil.getPath(headImg); + if(team.getTeamIcon()!=null){ // 获取旧的头像路径 if (oldTeam.getTeamIcon()!=null){ - String oldHeadImgPath = map.get("objectImgPath")+oldTeam.getTeamIcon(); + String oldHeadImgPath =uploadPath+oldTeam.getTeamIcon(); // 删除旧头像资源 File file = new File(oldHeadImgPath); - file.delete(); - } - try { -// 更新新头像资源并更新数据库 - headImg.transferTo(new File(map.get("headImgPath"))); - team.setTeamIcon(map.get("filename")); - teamMapper.updateById(team); - team = teamMapper.selectById(team); - return team; - } catch (IOException e) { - e.printStackTrace(); - return null; + FileSystemUtils.deleteRecursively(file); } } // 头像不用更新,直接更新数据库 @@ -108,7 +84,15 @@ public class TeamServiceImpl extends ServiceImpl implements IT @Override public Boolean deleteTeam(Long teamId) { - return teamMapper.deleteById(teamId)>0; + Team oldTeam = teamMapper.selectById(teamId); + int i = teamMapper.deleteById(teamId); + if(i>0){ + //数据库删除成功,删除头像资源 + File file = new File(uploadPath+oldTeam.getTeamIcon()); + FileSystemUtils.deleteRecursively(file); + return true; + } + return false; } @Transactional diff --git a/src/main/java/com/javaee/newssystem/service/impl/UploadServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/UploadServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e189e25d5f4d53c91f7b981ffbfa7aed921a503c --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/impl/UploadServiceImpl.java @@ -0,0 +1,40 @@ +package com.javaee.newssystem.service.impl; + +import com.javaee.newssystem.service.IUploadService; +import com.javaee.newssystem.utils.MyUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +@Service +public class UploadServiceImpl implements IUploadService { + + @Value("${web.upload-path}") + private String uploadPath; + + @Override + public String upload(MultipartFile headImg) { + if(headImg!=null&&!headImg.isEmpty()){ + try { +// 生成新的头像路径 + Map map = MyUtil.getPath(headImg); +// 存储 + File folder = new File(uploadPath); + if(!folder.isDirectory()){ + folder.mkdirs(); + } + headImg.transferTo(new File(folder,map.get("filename"))); + String name = map.get("filename"); + return name; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + return null; + } +} diff --git a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java index bba61d36ed5f2467c970d2edbb3b72f2498f22c5..cbbcd6aa31cb8fcfbb7c4a02c4012bbff11d9af9 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java @@ -10,17 +10,31 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.javaee.newssystem.utils.JwtUtil; import com.javaee.newssystem.utils.MD5Util; import com.javaee.newssystem.utils.MyUtil; +import com.javaee.newssystem.utils.RedisUtil; +import com.javaee.newssystem.vo.UserRespVo; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.FileSystemUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; +import java.nio.file.FileSystem; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** @@ -31,39 +45,35 @@ import java.util.Map; * @author qjj * @since 2022-11-28 */ +@CacheConfig(cacheNames = "userInfo") @Service public class UserServiceImpl extends ServiceImpl implements IUserService { @Autowired UserMapper userMapper; - @Override - public User Login(String userName, String password) { + public Long Login(String userName, String password){ try { - Map map = new HashMap<>(); - if(userName.contains("@")){ - map.put("user_email",userName); - } - else { - map.put("user_phone",userName); - } - map.put("user_password",MD5Util.encryMD5(password.getBytes())); - List userList = userMapper.selectByMap(map); - if(userList!=null&&!userList.isEmpty()){ - User user = userList.get(0); - user.setUserPassword(null); - return user; - } + password = MD5Util.encryMD5(password.getBytes()); } catch (Exception e) { - return null; + e.printStackTrace(); + } + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.select("user_id") + .eq("user_email",userName).eq("user_password",password) + .or() + .eq("user_phone",userName).eq("user_password",password); + List userList = userMapper.selectList(queryWrapper); + if(userList!=null&&!userList.isEmpty()){ + return userList.get(0).getUserId(); } return null; } @Transactional @Override - public void Register(User user) { + public Boolean Register(User user) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_phone",user.getUserPhone()) .or() @@ -74,70 +84,60 @@ public class UserServiceImpl extends ServiceImpl implements IU // 密码加密处理 user.setUserPassword(MD5Util.encryMD5(user.getUserPassword().getBytes())); user.setCreateTime(new Date()); - userMapper.insert(user); + return userMapper.insert(user)>0; } catch (Exception e) { e.printStackTrace(); } - } + return false; } + @Value("${web.upload-path}") + private String uploadPath; + + @CachePut(key = "#result.userId",condition = "#result!=null") @Transactional @Override - public User updateInfo(User user, MultipartFile headImg) { + public UserRespVo updateInfo(User user) { //获取旧的用户信息 User oldUser = userMapper.selectById(user.getUserId()); //处理头像资源 - if(oldUser!=null&&!headImg.isEmpty()){ - -// 生成新的头像路径 - Map map = MyUtil.getPath(headImg); + if(oldUser!=null&&user.getUserIcon()!=null){ // 获取旧的头像路径 if(oldUser.getUserIcon()!=null){ - String oldHeadImgPath = map.get("objectImgPath")+oldUser.getUserIcon(); + String oldHeadImgPath = uploadPath+oldUser.getUserIcon(); // 删除旧头像资源 File file = new File(oldHeadImgPath); - file.delete(); - } - try { -// 更新新头像资源并更新数据库 - headImg.transferTo(new File(map.get("headImgPath"))); - user.setUserIcon(map.get("filename")); - userMapper.updateById(user); - user = userMapper.selectById(user); - user.setUserPassword(null); - return user; - } catch (IOException e) { - e.printStackTrace(); - return null; + FileSystemUtils.deleteRecursively(file); } } // 头像不用更新,直接更新数据库 + if (oldUser==null) return null; userMapper.updateById(user); user = userMapper.selectById(user); - user.setUserPassword(null); - return user; + UserRespVo vo = new UserRespVo(); + BeanUtils.copyProperties(user,vo); + return vo; } + @CacheEvict(key = "#userId") @Transactional @Override public Boolean Logout(Long userId) { User oldUser = userMapper.selectById(userId); - String objectImgPath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\headImg\\"; int i = userMapper.deleteById(userId); if(i>0){ //数据库删除成功,删除头像资源 - File file = new File(objectImgPath+oldUser.getUserIcon()); - file.delete(); + File file = new File(uploadPath+oldUser.getUserIcon()); + FileSystemUtils.deleteRecursively(file); return true; } - else return false; } @Transactional @Override - public Page getFocusUser(Long userId, Integer current, Integer size) { + public Page getFocusUser(Long userId, Integer current, Integer size) { List focusUserIdList = userMapper.selectFocusUserId(userId); QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.select("user_name","user_icon","user_signature"); @@ -145,28 +145,50 @@ public class UserServiceImpl extends ServiceImpl implements IU queryWrapper.in("user_id",focusUserIdList); Page page = new Page<>(current,size); userMapper.selectPage(page,queryWrapper); - return page; + Page respVoPage = new Page<>(); + BeanUtils.copyProperties(page,respVoPage); + List userList = page.getRecords(); + List voList = userList.stream().map((user -> { + UserRespVo vo = new UserRespVo(); + BeanUtils.copyProperties(user, vo); + return vo; + })).collect(Collectors.toList()); + respVoPage.setRecords(voList); + return respVoPage; } return null; } @Override public Boolean addFocusUser(Long userId, Long focusedUserId) { + List list = userMapper.selectFocusUserId(userId); + for (Long aLong : list) { + if(aLong.equals(focusedUserId)) return false; + } return userMapper.insertFocus(userId,focusedUserId)>0; } @Override public Boolean unFocus(Long userId, Long focusedUserId) { - return userMapper.delete(userId,focusedUserId)>0; + return userMapper.deleteFromFocusAndUser(userId,focusedUserId)>0; } @Override - public Page adminGetUserList(Integer current, Integer size) { + public Page adminGetUserList(Integer current, Integer size) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.select("user_id","user_name","user_icon","user_signature","user_email","user_position","user_email","user_phone","create_time"); Page page = new Page<>(current,size); userMapper.selectPage(page,queryWrapper); - return page; + Page respVoPage = new Page<>(current,size); + BeanUtils.copyProperties(page,respVoPage); + List userList = page.getRecords(); + List voList = userList.stream().map((user -> { + UserRespVo vo = new UserRespVo(); + BeanUtils.copyProperties(user, vo); + return vo; + })).collect(Collectors.toList()); + respVoPage.setRecords(voList); + return respVoPage; } @Override @@ -180,12 +202,17 @@ public class UserServiceImpl extends ServiceImpl implements IU } @Override - public List search(String userName) { + public List search(String userName) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.select("user_id","user_phone","user_name","user_email","user_signature","user_icon","user_position") .eq("user_name",userName); List userList = userMapper.selectList(queryWrapper); - return userList; + List voList = userList.stream().map((user -> { + UserRespVo vo = new UserRespVo(); + BeanUtils.copyProperties(user, vo); + return vo; + })).collect(Collectors.toList()); + return voList; } @Transactional @@ -208,15 +235,12 @@ public class UserServiceImpl extends ServiceImpl implements IU } } + @Cacheable(key = "#userId") @Override - public User getUserInfo(String token) { - Map map = JwtUtil.parse(token); - if((Boolean) map.get("status")){ - Long id = (Long) map.get("id"); - User user = userMapper.selectById(id); - user.setUserPassword(null); - return user; - } - return null; + public UserRespVo getUserInfo(Long userId) { + User user = userMapper.selectById(userId); + UserRespVo vo = new UserRespVo(); + BeanUtils.copyProperties(user,vo); + return vo; } } diff --git a/src/main/java/com/javaee/newssystem/utils/JwtUtil.java b/src/main/java/com/javaee/newssystem/utils/JwtUtil.java index 95bad3d37e80fb44ee1999c8bc6e1cdaf35d2973..95449c73cadc4e98c3dfc5d17d42a833dae3301c 100644 --- a/src/main/java/com/javaee/newssystem/utils/JwtUtil.java +++ b/src/main/java/com/javaee/newssystem/utils/JwtUtil.java @@ -8,7 +8,7 @@ import java.util.Map; public class JwtUtil { - private final static long expirationTime = 1000*60*30; + private final static long expirationTime = 1000*60*60*24; private final static String signature = "GUET2020.qjj#lz&wj*jtw%"; public static String getToken(Long id,String role){ diff --git a/src/main/java/com/javaee/newssystem/utils/MyUtil.java b/src/main/java/com/javaee/newssystem/utils/MyUtil.java index 87c6e7f75ad97797873a73576186ed6c9ab53cb4..cfebd719c0aa3d6675051d2eae707e3612422607 100644 --- a/src/main/java/com/javaee/newssystem/utils/MyUtil.java +++ b/src/main/java/com/javaee/newssystem/utils/MyUtil.java @@ -1,7 +1,9 @@ package com.javaee.newssystem.utils; +import org.springframework.util.ResourceUtils; import org.springframework.web.multipart.MultipartFile; +import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -11,7 +13,13 @@ public class MyUtil { public static Map getPath(MultipartFile file){ String filename = file.getOriginalFilename(); String suffixName = filename.substring(filename.lastIndexOf(".")); - String objectImgPath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\headImg\\"; + String objectImgPath = null; + try { + objectImgPath = ResourceUtils.getURL("classpath:").getPath() + "static/"; + } catch (FileNotFoundException e) { + e.printStackTrace(); + } +// String objectImgPath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\headImg\\"; String uuid = UUID.randomUUID().toString().replace("-",""); String headImgPath = objectImgPath+uuid+suffixName; Map map = new HashMap<>(); diff --git a/src/main/java/com/javaee/newssystem/utils/RedisUtil.java b/src/main/java/com/javaee/newssystem/utils/RedisUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..9c752ae979f332124150e1d809faee0e699fcba4 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/utils/RedisUtil.java @@ -0,0 +1,522 @@ +package com.javaee.newssystem.utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +@Component +public class RedisUtil { + + @Autowired + private RedisTemplate redisTemplate; + /** + * 给一个指定的 key 值附加过期时间 + * + * @param key + * @param time + * @return + */ + public boolean expire(String key, long time) { + return redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + /** + * 根据key 获取过期时间 + * + * @param key + * @return + */ + public long getTime(String key) { + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + /** + * 根据key 获取过期时间 + * + * @param key + * @return + */ + public boolean hasKey(String key) { + return redisTemplate.hasKey(key); + } + /** + * 移除指定key的过期时间 + * + * @param key + * @return + */ + public boolean persist(String key) { + return redisTemplate.boundValueOps(key).persist(); + } + + //- - - - - - - - - - - - - - - - - - - - - String类型 - - - - - - - - - - - - - - - - - - - - + + /** + * 根据key获取值 + * + * @param key 键 + * @return 值 + */ + public Object get(String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 将值放入缓存 + * + * @param key 键 + * @param value 值 + * @return true成功 false 失败 + */ + public void set(String key, String value) { + redisTemplate.opsForValue().set(key, value); + } + + /** + * 将值放入缓存并设置时间 + * + * @param key 键 + * @param value 值 + * @param time 时间(秒) -1为无期限 + * @return true成功 false 失败 + */ + public void set(String key, Object value, long time) { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + redisTemplate.opsForValue().set(key, value); + } + } + + /** + * 批量添加 key (重复的键会覆盖) + * + * @param keyAndValue + */ + public void batchSet(Map keyAndValue) { + redisTemplate.opsForValue().multiSet(keyAndValue); + } + + /** + * 批量添加 key-value 只有在键不存在时,才添加 + * map 中只要有一个key存在,则全部不添加 + * + * @param keyAndValue + */ + public void batchSetIfAbsent(Map keyAndValue) { + redisTemplate.opsForValue().multiSetIfAbsent(keyAndValue); + } + + /** + * 对一个 key-value 的值进行加减操作, + * 如果该 key 不存在 将创建一个key 并赋值该 number + * 如果 key 存在,但 value 不是长整型 ,将报错 + * + * @param key + * @param number + */ + public Long increment(String key, long number) { + return redisTemplate.opsForValue().increment(key, number); + } + + /** + * 对一个 key-value 的值进行加减操作, + * 如果该 key 不存在 将创建一个key 并赋值该 number + * 如果 key 存在,但 value 不是 纯数字 ,将报错 + * + * @param key + * @param number + */ + public Double increment(String key, double number) { + return redisTemplate.opsForValue().increment(key, number); + } + + //- - - - - - - - - - - - - - - - - - - - - set类型 - - - - - - - - - - - - - - - - - - - - + + /** + * 将数据放入set缓存 + * + * @param key 键 + * @return + */ + public void sSet(String key, String value) { + redisTemplate.opsForSet().add(key, value); + } + + /** + * 获取变量中的值 + * + * @param key 键 + * @return + */ + public Set members(String key) { + return redisTemplate.opsForSet().members(key); + } + + /** + * 随机获取变量中指定个数的元素 + * + * @param key 键 + * @param count 值 + * @return + */ + public void randomMembers(String key, long count) { + redisTemplate.opsForSet().randomMembers(key, count); + } + + /** + * 随机获取变量中的元素 + * + * @param key 键 + * @return + */ + public Object randomMember(String key) { + return redisTemplate.opsForSet().randomMember(key); + } + + /** + * 弹出变量中的元素 + * + * @param key 键 + * @return + */ + public Object pop(String key) { + return redisTemplate.opsForSet().pop("setValue"); + } + + /** + * 获取变量中值的长度 + * + * @param key 键 + * @return + */ + public long size(String key) { + return redisTemplate.opsForSet().size(key); + } + + /** + * 根据value从一个set中查询,是否存在 + * + * @param key 键 + * @param value 值 + * @return true 存在 false不存在 + */ + public boolean sHasKey(String key, Object value) { + return redisTemplate.opsForSet().isMember(key, value); + } + + /** + * 检查给定的元素是否在变量中。 + * + * @param key 键 + * @param obj 元素对象 + * @return + */ + public boolean isMember(String key, Object obj) { + return redisTemplate.opsForSet().isMember(key, obj); + } + + /** + * 转移变量的元素值到目的变量。 + * + * @param key 键 + * @param value 元素对象 + * @param destKey 元素对象 + * @return + */ + public boolean move(String key, String value, String destKey) { + return redisTemplate.opsForSet().move(key, value, destKey); + } + + /** + * 批量移除set缓存中元素 + * + * @param key 键 + * @param values 值 + * @return + */ + public void remove(String key, Object... values) { + redisTemplate.opsForSet().remove(key, values); + } + + /** + * 通过给定的key求2个set变量的差值 + * + * @param key 键 + * @param destKey 键 + * @return + */ + public Set difference(String key, String destKey) { + return redisTemplate.opsForSet().difference(key, destKey); + } + + + //- - - - - - - - - - - - - - - - - - - - - hash类型 - - - - - - - - - - - - - - - - - - - - + + /** + * 加入缓存 + * + * @param key 键 + * @param map 键 + * @return + */ + public void add(String key, Map map) { + redisTemplate.opsForHash().putAll(key, map); + } + + /** + * 获取 key 下的 所有 hashkey 和 value + * + * @param key 键 + * @return + */ + public Map getHashEntries(String key) { + return redisTemplate.opsForHash().entries(key); + } + + /** + * 验证指定 key 下 有没有指定的 hashkey + * + * @param key + * @param hashKey + * @return + */ + public boolean hashKey(String key, String hashKey) { + return redisTemplate.opsForHash().hasKey(key, hashKey); + } + + /** + * 获取指定key的值string + * + * @param key 键 + * @param key2 键 + * @return + */ + public String getMapString(String key, String key2) { + return redisTemplate.opsForHash().get("map1", "key1").toString(); + } + + /** + * 获取指定的值Int + * + * @param key 键 + * @param key2 键 + * @return + */ + public Integer getMapInt(String key, String key2) { + return (Integer) redisTemplate.opsForHash().get("map1", "key1"); + } + + /** + * 弹出元素并删除 + * + * @param key 键 + * @return + */ + public String popValue(String key) { + return redisTemplate.opsForSet().pop(key).toString(); + } + + /** + * 删除指定 hash 的 HashKey + * + * @param key + * @param hashKeys + * @return 删除成功的 数量 + */ + public Long delete(String key, String... hashKeys) { + return redisTemplate.opsForHash().delete(key, hashKeys); + } + + /** + * 给指定 hash 的 hashkey 做增减操作 + * + * @param key + * @param hashKey + * @param number + * @return + */ + public Long increment(String key, String hashKey, long number) { + return redisTemplate.opsForHash().increment(key, hashKey, number); + } + + /** + * 给指定 hash 的 hashkey 做增减操作 + * + * @param key + * @param hashKey + * @param number + * @return + */ + public Double increment(String key, String hashKey, Double number) { + return redisTemplate.opsForHash().increment(key, hashKey, number); + } + + /** + * 获取 key 下的 所有 hashkey 字段 + * + * @param key + * @return + */ + public Set hashKeys(String key) { + return redisTemplate.opsForHash().keys(key); + } + + /** + * 获取指定 hash 下面的 键值对 数量 + * + * @param key + * @return + */ + public Long hashSize(String key) { + return redisTemplate.opsForHash().size(key); + } + + //- - - - - - - - - - - - - - - - - - - - - list类型 - - - - - - - - - - - - - - - - - - - - + + /** + * 在变量左边添加元素值 + * + * @param key + * @param value + * @return + */ + public void leftPush(String key, Object value) { + redisTemplate.opsForList().leftPush(key, value); + } + + /** + * 获取集合指定位置的值。 + * + * @param key + * @param index + * @return + */ + public Object index(String key, long index) { + return redisTemplate.opsForList().index("list", 1); + } + + /** + * 获取指定区间的值。 + * + * @param key + * @param start + * @param end + * @return + */ + public List range(String key, long start, long end) { + return redisTemplate.opsForList().range(key, start, end); + } + + /** + * 把最后一个参数值放到指定集合的第一个出现中间参数的前面, + * 如果中间参数值存在的话。 + * + * @param key + * @param pivot + * @param value + * @return + */ + public void leftPush(String key, String pivot, String value) { + redisTemplate.opsForList().leftPush(key, pivot, value); + } + + /** + * 向左边批量添加参数元素。 + * + * @param key + * @param values + * @return + */ + public void leftPushAll(String key, String... values) { +// redisTemplate.opsForList().leftPushAll(key,"w","x","y"); + redisTemplate.opsForList().leftPushAll(key, values); + } + + /** + * 向集合最右边添加元素。 + * + * @param key + * @param value + * @return + */ + public void leftPushAll(String key, String value) { + redisTemplate.opsForList().rightPush(key, value); + } + + /** + * 向左边批量添加参数元素。 + * + * @param key + * @param values + * @return + */ + public void rightPushAll(String key, String... values) { + //redisTemplate.opsForList().leftPushAll(key,"w","x","y"); + redisTemplate.opsForList().rightPushAll(key, values); + } + + /** + * 向已存在的集合中添加元素。 + * + * @param key + * @param value + * @return + */ + public void rightPushIfPresent(String key, Object value) { + redisTemplate.opsForList().rightPushIfPresent(key, value); + } + + /** + * 向已存在的集合中添加元素。 + * + * @param key + * @return + */ + public long listLength(String key) { + return redisTemplate.opsForList().size(key); + } + + /** + * 移除集合中的左边第一个元素。 + * + * @param key + * @return + */ + public void leftPop(String key) { + redisTemplate.opsForList().leftPop(key); + } + + /** + * 移除集合中左边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。 + * + * @param key + * @return + */ + public void leftPop(String key, long timeout, TimeUnit unit) { + redisTemplate.opsForList().leftPop(key, timeout, unit); + } + + /** + * 移除集合中右边的元素。 + * + * @param key + * @return + */ + public void rightPop(String key) { + redisTemplate.opsForList().rightPop(key); + } + + /** + * 移除集合中右边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。 + * + * @param key + * @return + */ + public void rightPop(String key, long timeout, TimeUnit unit) { + redisTemplate.opsForList().rightPop(key, timeout, unit); + } +} diff --git a/src/main/java/com/javaee/newssystem/vo/AdminVo.java b/src/main/java/com/javaee/newssystem/vo/AdminVo.java new file mode 100644 index 0000000000000000000000000000000000000000..91374c5ce48d805384689c4cc6811acc4e5bca30 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/AdminVo.java @@ -0,0 +1,20 @@ +package com.javaee.newssystem.vo; + +import lombok.Data; + +@Data +public class AdminVo { + + private Long adminId; + + /** + * 管理员名称 + */ + private String userName; + + /** + * 管理员密码 + */ + private String password; + +} diff --git a/src/main/java/com/javaee/newssystem/vo/CommentVo.java b/src/main/java/com/javaee/newssystem/vo/CommentVo.java new file mode 100644 index 0000000000000000000000000000000000000000..9b22094e5ebe0194a785ca8d71e09edebdee6a09 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/CommentVo.java @@ -0,0 +1,45 @@ +package com.javaee.newssystem.vo; + +import lombok.Data; + +import java.util.Date; + +@Data +public class CommentVo { + + /** + * 评论id,自动创建 + */ + private Long commentId; + + /** + * 用户id + */ + private Long userId; + + /** + * 消息id + */ + private Long newsId; + + /** + * 评论内容 + */ + private String content; + + /** + * 评论时间 + */ + private Date createTime; + + /** + * 父级评论id + */ + private Long parentCommentId; + + private String userName; + + private String userIcon; + + private Boolean isLike; +} diff --git a/src/main/java/com/javaee/newssystem/vo/CommentWithUserVo.java b/src/main/java/com/javaee/newssystem/vo/CommentWithUserVo.java new file mode 100644 index 0000000000000000000000000000000000000000..1107af0c22a4949782023a415457be7460d93d5a --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/CommentWithUserVo.java @@ -0,0 +1,18 @@ +package com.javaee.newssystem.vo; + +import lombok.Data; + +@Data +public class CommentWithUserVo { + + /** + * 评论id,自动创建 + */ + private Long commentId; + + /** + * 用户id + */ + private Long userId; + +} diff --git a/src/main/java/com/javaee/newssystem/vo/NewsVo.java b/src/main/java/com/javaee/newssystem/vo/NewsVo.java new file mode 100644 index 0000000000000000000000000000000000000000..eee3398645a8253e5e32f92be2b1af7034ce166c --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/NewsVo.java @@ -0,0 +1,71 @@ +package com.javaee.newssystem.vo; + + +import lombok.Data; + +import javax.validation.constraints.Pattern; +import java.util.Date; + +@Data +public class NewsVo { + /** + * 消息id + */ + private Long newsId; + + /** + * 创建者id + */ + private Long userId; + + /** + * 新闻类型 + */ + private String category; + + /** + * 新闻标题 + */ + @Pattern(regexp = "^.{3,100}$",message = "标题长度必须在3-100之间") + private String title; + + /** + * 新闻内容 + */ + @Pattern(regexp = "^.{10,}$",message = "内容长度必须在10以上") + private String content; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 消息归属地(空则为公共,非空则归属该团队) + */ + private Long belongTeamId; + + /** + * 消息状态(未审核、已通过、已打回、已保存) + */ + private String state; + /** + * 发布者用户名 + */ + private String userName; + + /** + * 发布者头像路径 + */ + private String userIcon; + + /** + * 请求者是否关注了此消息 + */ + private Boolean isFocus; + + /** + * 请求者是否关注了作者 + */ + private Boolean isFocusAuthor; +} diff --git a/src/main/java/com/javaee/newssystem/vo/NewsWithUserVo.java b/src/main/java/com/javaee/newssystem/vo/NewsWithUserVo.java new file mode 100644 index 0000000000000000000000000000000000000000..9668e642eea6e34866c81d92ffee63e9b199553d --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/NewsWithUserVo.java @@ -0,0 +1,11 @@ +package com.javaee.newssystem.vo; + +import lombok.Data; + +@Data +public class NewsWithUserVo { + + private Long newsId; + private Long userId; + +} diff --git a/src/main/java/com/javaee/newssystem/vo/TeamVo.java b/src/main/java/com/javaee/newssystem/vo/TeamVo.java new file mode 100644 index 0000000000000000000000000000000000000000..9d37321f27c6ed4bf571ae18a728d203a53e9a05 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/TeamVo.java @@ -0,0 +1,11 @@ +package com.javaee.newssystem.vo; + +import lombok.Data; + +@Data +public class TeamVo { + + private Long teamId; + private Long newsId; + private Long userId; +} diff --git a/src/main/java/com/javaee/newssystem/vo/UserRespVo.java b/src/main/java/com/javaee/newssystem/vo/UserRespVo.java new file mode 100644 index 0000000000000000000000000000000000000000..281d603f5c52717515c27c73bdad63a3b665c920 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/UserRespVo.java @@ -0,0 +1,49 @@ +package com.javaee.newssystem.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +@Data +public class UserRespVo implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long userId; + + /** + * 用户名 + */ + private String userName; + + /** + * 手机号 + */ + private String userPhone; + + /** + * 邮箱,对照着用户id,登录使用 + */ + private String userEmail; + + /** + * 用户头像 + */ + private String userIcon; + + /** + * 用户职位 + */ + private String userPosition; + + /** + * 用户个性签名 + */ + private String userSignature; + + /** + * 账号创建时间 + */ + private Date createTime; +} diff --git a/src/main/java/com/javaee/newssystem/vo/UserVo.java b/src/main/java/com/javaee/newssystem/vo/UserVo.java new file mode 100644 index 0000000000000000000000000000000000000000..0c955df7ada51db34152f8a5a9f8e437ceaa3128 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/UserVo.java @@ -0,0 +1,33 @@ +package com.javaee.newssystem.vo; + + +import lombok.Data; +import org.springframework.web.bind.annotation.RequestBody; + +import javax.validation.constraints.Pattern; +import java.util.Date; + +@Data +public class UserVo { + /** + * 用户id,自动创建 + */ + private Long userId; + + /** + * 用户名 + */ + @Pattern(regexp = "^.{3,20}$",message = "用户名长度必须在3-20之间") + private String userName; + + /** + * 密码 + */ + @Pattern(regexp = "^[a-zA-Z]\\w{5,17}$",message = "密码必须以字母开头,长度在6~18之间,只能包含字母、数字和下划线") + private String userPassword; + + private String oldPassword; + private String newPassword; + + private Long focusedUserId; +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 37c5c89b77d2cdb7dce417f6386374e1f80c9a09..3ad78e52c6becaf1f959e5d45a4740c0b16757f9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,17 +1,35 @@ +web: +# upload-path: /usr/local/project/HeadImg + upload-path: D:/HeadImg/ spring: datasource: - url: jdbc:mysql://124.70.20.202:3306/javaee?serverTimezone=Asia/Shanghai - username: root - password: QQqq814287041 + url: jdbc:mysql://47.92.76.106:3306/javaee?serverTimezone=Asia/Shanghai + username: remote + password: eLrMpql_0010yu +# url: jdbc:mysql://127.0.0.1:3306/news?serverTimezone=Asia/Shanghai +# username: root +# password: 123456 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver - + redis: + host: 127.0.0.1 + port: 6379 + password: + database: 0 + lettuce: + pool: + max-active: 16 + max-idle: 32 + min-idle: 8 jackson: # 返回时间戳 serialization: write-dates-as-timestamps: true time-zone: GMT+8 + # 数据为null则不会序列化 + default-property-inclusion: non_null + web: + resources: + static-locations: file:${web.upload-path} mybatis-plus: - configuration: - log-impl: org.apache.ibatis.logging.stdout.StdOutImpl type-aliases-package: com.javaee.newssystem.entity \ No newline at end of file diff --git a/src/main/resources/mapper/CommentMapper.xml b/src/main/resources/mapper/CommentMapper.xml index 0245b68541dc00cd17dcb1f932f548a631211ebf..f43172bced9ed54202df84acc96ceffb60b2799e 100644 --- a/src/main/resources/mapper/CommentMapper.xml +++ b/src/main/resources/mapper/CommentMapper.xml @@ -18,8 +18,11 @@ SELECT comment_id FROM user_comment_like WHERE user_id=#{userId} - + SELECT COUNT(*) FROM user_comment_like WHERE comment_id=#{commentId} AND user_id=#{userId} diff --git a/src/main/resources/mapper/NewsMapper.xml b/src/main/resources/mapper/NewsMapper.xml index 00ebe146446a340994856317f4959f8759900dd1..527d7cd99ed6972a1670b35427a9c13c259d1f94 100644 --- a/src/main/resources/mapper/NewsMapper.xml +++ b/src/main/resources/mapper/NewsMapper.xml @@ -1,13 +1,21 @@ + + INSERT INTO focus_news values (#{userId},#{newsId}) + + + DELETE FROM focus_news WHERE user_id=#{userId} AND news_id=#{newsId} + - SELECT count(*) FROM focus_news WHERE news_id=#{newsId} - + diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml index 9db97c770934167645ce91dcdc6ca09fdaad4fb4..8989ea9fd9c87eabbe0e13ba2537888f2bd45b31 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/src/main/resources/mapper/UserMapper.xml @@ -7,11 +7,18 @@ UPDATE user SET status=0 WHERE user_id=#{userId} - + DELETE FROM focus_user WHERE user_id=#{userId} AND focused_user_id=#{focusedUserId} + + + diff --git a/src/main/resources/templates/404.html b/src/main/resources/templates/404.html deleted file mode 100644 index 85563cc67c24f824f08fbcd7dbd9f2993498d528..0000000000000000000000000000000000000000 --- a/src/main/resources/templates/404.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - 404页面 - - -

404,页面丢失

-

测试自定义的错误页面

- - \ No newline at end of file diff --git a/src/test/java/com/javaee/newssystem/MybatisPlusTest.java b/src/test/java/com/javaee/newssystem/MybatisPlusTest.java index 1b4344bd93ecc74fcd88eb62ca798e1317fca66b..2168dc6641a430ed4805db5d135ebf5a6f29a850 100644 --- a/src/test/java/com/javaee/newssystem/MybatisPlusTest.java +++ b/src/test/java/com/javaee/newssystem/MybatisPlusTest.java @@ -4,13 +4,16 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.javaee.newssystem.entity.News; import com.javaee.newssystem.entity.User; +import com.javaee.newssystem.mapper.CommentMapper; import com.javaee.newssystem.mapper.NewsMapper; import com.javaee.newssystem.mapper.TeamMapper; import com.javaee.newssystem.mapper.UserMapper; +import com.javaee.newssystem.service.impl.NewsServiceImpl; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import javax.xml.crypto.Data; import java.util.*; @SpringBootTest @@ -24,6 +27,12 @@ public class MybatisPlusTest { NewsMapper newsMapper; TeamMapper teamMapper; + @Autowired + CommentMapper commentMapper; + + @Autowired + NewsServiceImpl newsService; + // 测试插入数据 @Test public void insetUserTest(){ @@ -97,4 +106,6 @@ public class MybatisPlusTest { Long[] s = teamMapper.getTeamId(4L, "附属"); System.out.println(s); } + + } diff --git a/src/test/java/com/javaee/newssystem/OtherTest.java b/src/test/java/com/javaee/newssystem/OtherTest.java index b612ba7f481575d4842d2ea5abd0f23dadb930b6..c94616d27860b8beb6ae5ac224f91b4ba036d267 100644 --- a/src/test/java/com/javaee/newssystem/OtherTest.java +++ b/src/test/java/com/javaee/newssystem/OtherTest.java @@ -1,12 +1,20 @@ package com.javaee.newssystem; import com.javaee.newssystem.entity.Comment; +import com.javaee.newssystem.entity.News; +import com.javaee.newssystem.entity.User; import com.javaee.newssystem.mapper.CommentMapper; import com.javaee.newssystem.utils.JwtUtil; +import com.javaee.newssystem.vo.NewsVo; import org.junit.jupiter.api.Test; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; import java.util.Date; +import java.util.List; public class OtherTest { @@ -16,4 +24,26 @@ public class OtherTest { // JwtUtil.parse(token); } + + @Test + public void Test1(){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 6); + String startTime = sdf.format(calendar.getTime()); + System.out.println("开始时间:"+startTime); + } + + @Test + public void Test2(){ + Long L1 = 130L; + Long L2 = 130L; + System.out.println(130L==130L);//true + System.out.println(L1==130L);//true + System.out.println(L1==L2);//false + } + + @Test + public void Test3(){ + } } diff --git a/src/test/java/com/javaee/newssystem/RedisTest.java b/src/test/java/com/javaee/newssystem/RedisTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ce05904b7ed0f5a1b8d17a36886825bcc2407354 --- /dev/null +++ b/src/test/java/com/javaee/newssystem/RedisTest.java @@ -0,0 +1,97 @@ +package com.javaee.newssystem; + +import com.javaee.newssystem.entity.HotWord; +import com.javaee.newssystem.entity.User; +import com.javaee.newssystem.utils.RedisUtil; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ScanOptions; +import org.springframework.data.redis.core.ZSetOperations; + +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.function.Consumer; + + +@SpringBootTest +public class RedisTest { + + @Autowired + RedisUtil redisUtil; + + @Test + public void test1(){ + redisUtil.set("test2","Java连接测试"); + Object test = redisUtil.get("test2"); + redisUtil.expire("test2",5L); + System.out.println(test); + } + + @Test + public void test2() throws InterruptedException { +// 模拟100次请求,每次请求的userId是i + for (int i = 0; i < 100; i++) { + Thread.sleep(200); + redisUtil.set(String.valueOf(i),String.valueOf(i),20L); + } + + Thread.sleep(5000); +// for (int i = 0; i < 100; i++) { +// Thread.sleep(200); +// redisUtil.set("第二次"+i,String.valueOf(i),30L); +// } + + for (int i = 0; i < 100; i++) { + Object o = redisUtil.get(String.valueOf(i)); + System.out.println(o); + } + } + + @Autowired + RedisTemplate redisTemplate; + + @Test + public void test3(){ + redisTemplate.opsForZSet().removeRangeByScore("newsHotKey",1,3); + Set> typedTupleSet = redisTemplate.opsForZSet().reverseRangeByScoreWithScores("newsHotKey",1,50000); + Iterator> iterator = typedTupleSet.iterator(); + List list = new ArrayList<>(); + while (iterator.hasNext()){ + ZSetOperations.TypedTuple typedTuple = iterator.next(); + String value = (String)typedTuple.getValue(); + int score = (int) Math.ceil(typedTuple.getScore()); + list.add(new HotWord(value,score)); + } + System.out.println(list.size()); + list.forEach(System.out::println); + } + + @Test + public void test4(){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String value = sdf.format(new Date()); + redisTemplate.opsForZSet().score("newsNumber", value); + Calendar calendar = Calendar.getInstance(); + for (int i = 5;i>=0;i--){ + calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1); + value = sdf.format(calendar.getTime()); + redisTemplate.opsForZSet().incrementScore("newsNumber",value,i); + } + } + + @Test + public void test5(){ + ScanOptions scanOptions = ScanOptions.scanOptions().match("userInfo" + "*").build(); + Cursor cursors = redisTemplate.scan(scanOptions); + Long number = 0L; + while (cursors.hasNext()){ + cursors.next(); + number++; + } + cursors.close(); + } +}