From fef504fadc60d2758a2d649eec9e88fd19162a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=A4=E5=8F=AA=E9=B1=BC=E5=95=8A=E4=B8=A4=E5=8F=AA?= =?UTF-8?q?=E9=B1=BC?= <2986871391@qq.com> Date: Thu, 22 Dec 2022 15:25:08 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E7=83=AD=E6=90=9C=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 38 +- .../newssystem/NewsSystemApplication.java | 4 + .../newssystem/config/AdminWebConfig.java | 14 +- .../javaee/newssystem/config/RedisConfig.java | 57 ++ .../controller/ExceptionControllerAdvice.java | 37 ++ .../newssystem/controller/NewsController.java | 91 +-- .../controller/RedisController.java | 17 + .../newssystem/controller/UserController.java | 59 +- .../com/javaee/newssystem/entity/HotWord.java | 18 + .../com/javaee/newssystem/entity/Msg.java | 26 +- .../com/javaee/newssystem/entity/User.java | 7 + .../newssystem/service/INewsService.java | 7 + .../newssystem/service/IUserService.java | 2 +- .../newssystem/service/RedisService.java | 9 + .../newssystem/service/ScheduledService.java | 18 + .../service/impl/NewsServiceImpl.java | 45 +- .../service/impl/RedisServiceImpl.java | 21 + .../service/impl/UserServiceImpl.java | 15 +- .../javaee/newssystem/utils/RedisUtil.java | 522 ++++++++++++++++++ src/main/resources/application.yml | 17 +- .../java/com/javaee/newssystem/RedisTest.java | 42 ++ 21 files changed, 924 insertions(+), 142 deletions(-) create mode 100644 src/main/java/com/javaee/newssystem/config/RedisConfig.java create mode 100644 src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java create mode 100644 src/main/java/com/javaee/newssystem/controller/RedisController.java create mode 100644 src/main/java/com/javaee/newssystem/entity/HotWord.java create mode 100644 src/main/java/com/javaee/newssystem/service/RedisService.java create mode 100644 src/main/java/com/javaee/newssystem/service/ScheduledService.java create mode 100644 src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java create mode 100644 src/main/java/com/javaee/newssystem/utils/RedisUtil.java create mode 100644 src/test/java/com/javaee/newssystem/RedisTest.java diff --git a/pom.xml b/pom.xml index 5047f1b..4e7ab0f 100644 --- a/pom.xml +++ b/pom.xml @@ -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 8475e4b..516e9bb 100644 --- a/src/main/java/com/javaee/newssystem/NewsSystemApplication.java +++ b/src/main/java/com/javaee/newssystem/NewsSystemApplication.java @@ -2,7 +2,11 @@ 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 +@EnableCaching @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 6d9aaa9..a92ca27 100644 --- a/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java +++ b/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java @@ -13,12 +13,12 @@ public class AdminWebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 添加登录验证的拦截器 - registry.addInterceptor(new LoginInterceptor()) - .addPathPatterns("/**") - .excludePathPatterns("/user/login","/admin/login","/user/register"); -// 添加管理员身份验证的拦截器 - registry.addInterceptor(new AdminInterceptor()) - .excludePathPatterns("/admin/login") - .addPathPatterns("/admin/**"); +// registry.addInterceptor(new LoginInterceptor()) +// .addPathPatterns("/**") +// .excludePathPatterns("/user/login","/admin/login","/user/register"); +//// 添加管理员身份验证的拦截器 +// registry.addInterceptor(new AdminInterceptor()) +// .excludePathPatterns("/admin/login") +// .addPathPatterns("/admin/**"); } } 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 0000000..9f09a09 --- /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 + */ + +//编写我们自己的RedisTemplate +@Configuration +public class RedisConfig { + //固定redis模板,在工作中,拿去就可以用 + @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/ExceptionControllerAdvice.java b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java new file mode 100644 index 0000000..dbff3d7 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java @@ -0,0 +1,37 @@ +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.ObjectError; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.ArrayList; +import java.util.List; + +@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); + } + return Msg.fail("参数校验错误",400).add("errorMessage",messageStr); + } + + + @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 34a30f9..5bd1c9a 100644 --- a/src/main/java/com/javaee/newssystem/controller/NewsController.java +++ b/src/main/java/com/javaee/newssystem/controller/NewsController.java @@ -2,13 +2,17 @@ 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.utils.CheckClassUtil; +import com.mysql.cj.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +import java.util.List; + /** *

* 前端控制器 @@ -117,10 +121,7 @@ public class NewsController { public Msg deleteTeam(Long newsId){ if(newsId!=null){ Boolean b = newsService.deleteNews(newsId); - if(b){ - Msg msg = Msg.success("删除成功"); - return msg; - } + return b?Msg.success("删除成功"):Msg.fail("删除失败"); } return Msg.fail("缺少参数"); } @@ -137,67 +138,23 @@ public class NewsController { 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("缺少参数"); -// } +// 根据关键词查找消息 + @GetMapping("search") + public Msg searchNews(String key,Integer current,Integer size){ + if(!StringUtils.isNullOrEmpty(key)){ + Page page = newsService.searchNews(key,current,size); + return Msg.success("获取成功").add("data",page); + } + return Msg.fail("缺少参数"); + } + +// 获取热搜 + @GetMapping("/topsearch") + public Msg getTopsearch(Integer number){ + if (number==null){ + number = 10; + } + List hotWords = newsService.getHotKey(number); + return Msg.success("获取成功").add("data",hotWords); + } } 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 0000000..8f0d510 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/controller/RedisController.java @@ -0,0 +1,17 @@ +package com.javaee.newssystem.controller; + + +import com.javaee.newssystem.entity.Msg; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RedisController { + + @GetMapping("getHotKey") + public Msg getHotKey(){ + + return null; + } + +} diff --git a/src/main/java/com/javaee/newssystem/controller/UserController.java b/src/main/java/com/javaee/newssystem/controller/UserController.java index 928984a..cd48e8f 100644 --- a/src/main/java/com/javaee/newssystem/controller/UserController.java +++ b/src/main/java/com/javaee/newssystem/controller/UserController.java @@ -9,13 +9,12 @@ import com.javaee.newssystem.utils.CheckClassUtil; import com.javaee.newssystem.utils.JwtUtil; import com.mysql.cj.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; 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 java.util.List; /** @@ -35,15 +34,14 @@ public class UserController { // 用户登录 @RequestMapping(value = "/login",method = RequestMethod.POST) - public Msg Login(String userName,String userPassword){ + public Msg Login(String userName, String userPassword){ 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); + Msg msg = Msg.success("登录成功").add("data",user); // 生成token msg.add("token", JwtUtil.getToken(user.getUserId(),"用户")); return msg; @@ -55,31 +53,21 @@ public class UserController { // 用户注册 @RequestMapping(value = "/register",method = RequestMethod.POST) - public Msg Register(User user){ + public Msg Register(@Validated 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("注册成功").add("data",user):Msg.fail("用户名已存在"); } return Msg.fail("注册失败,缺少参数"); } // 用户修改信息 @RequestMapping(value = "/update/info",method = RequestMethod.POST) - public Msg updateInfo(User user,@RequestPart("headImg") MultipartFile headImg){ + public Msg updateInfo(@Validated User user,@RequestPart("headImg") MultipartFile headImg){ 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; + return Msg.success("修改成功").add("data",user); } else Msg.fail("修改失败"); @@ -102,7 +90,7 @@ public class UserController { // 用户修改密码 @PostMapping("/update/password") - public Msg updatePassword(Long userId,String oldPassword,String newPassword){ + public Msg updatePassword(Long userId, String oldPassword, String newPassword){ if(userId!=null&&CheckClassUtil.checkStringList(oldPassword,newPassword)){ Boolean b = userService.updatePassword(userId,oldPassword,newPassword); return b?Msg.success("修改密码成功"):Msg.fail("密码错误"); @@ -115,12 +103,7 @@ public class UserController { public Msg Logout(Long userId){ if(userId!=null){ Boolean b = userService.Logout(userId); - if(b){ - return Msg.success("注销成功"); - } - else { - return Msg.fail("该用户已被注销"); - } + return b?Msg.success("注销成功"):Msg.fail("该用户已被注销"); } return Msg.fail("缺少参数"); } @@ -130,9 +113,7 @@ public class UserController { 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; + return Msg.success("查询成功").add("data",page); } return Msg.fail("缺少参数"); } @@ -142,12 +123,7 @@ public class UserController { public Msg addFocusUser(Long userId,Long focusedUserId){ 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("缺少参数"); } @@ -157,12 +133,7 @@ public class UserController { public Msg unfocus(Long userId,Long focusedUserId){ 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("缺少参数"); } @@ -173,9 +144,7 @@ public class UserController { if(!StringUtils.isNullOrEmpty(userName)){ List userList = userService.search(userName); if (!userList.isEmpty()){ - Msg msg = Msg.success("查找成功"); - msg.add("data",userList); - return msg; + return Msg.success("查找成功").add("data",userList); } else 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 0000000..9f7f4e2 --- /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 0f38a69..403ca02 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/User.java b/src/main/java/com/javaee/newssystem/entity/User.java index 4aab674..0bdf02b 100644 --- a/src/main/java/com/javaee/newssystem/entity/User.java +++ b/src/main/java/com/javaee/newssystem/entity/User.java @@ -2,7 +2,9 @@ package com.javaee.newssystem.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; +import org.springframework.validation.annotation.Validated; +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[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|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/service/INewsService.java b/src/main/java/com/javaee/newssystem/service/INewsService.java index 3d98e09..372bc9f 100644 --- a/src/main/java/com/javaee/newssystem/service/INewsService.java +++ b/src/main/java/com/javaee/newssystem/service/INewsService.java @@ -1,10 +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 java.util.List; + /** *

* 服务类 @@ -44,5 +47,9 @@ public interface INewsService extends IService { Integer GetFocusNews(Long newsId); Boolean UnPassNews(Long newsId); + + Page searchNews(String key, Integer current, Integer size); + + List getHotKey(Integer number); } diff --git a/src/main/java/com/javaee/newssystem/service/IUserService.java b/src/main/java/com/javaee/newssystem/service/IUserService.java index 2bb1fe4..43b839c 100644 --- a/src/main/java/com/javaee/newssystem/service/IUserService.java +++ b/src/main/java/com/javaee/newssystem/service/IUserService.java @@ -19,7 +19,7 @@ public interface IUserService extends IService { User Login(String userName,String password); - void Register(User user); + Boolean Register(User user); User updateInfo(User user, MultipartFile headImg); 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 0000000..90f72b1 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/RedisService.java @@ -0,0 +1,9 @@ +package com.javaee.newssystem.service; + +import java.util.List; + +public interface RedisService { + + List getHotKey(); + +} 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 0000000..7872448 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/ScheduledService.java @@ -0,0 +1,18 @@ +package com.javaee.newssystem.service; + +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +public class ScheduledService { + + /** + * second(秒),minute(分),hour(时),day of month(日),month(月),day of week(周几). + * + */ + +// @Scheduled(cron = "0/10 * * * * *") + public void hello(){ + System.out.println("hello(测试定时任务,每10秒输出)"); + } +} 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 02bf2bf..7d8e2fe 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java @@ -2,18 +2,21 @@ 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.HotWord; import com.javaee.newssystem.entity.News; import com.javaee.newssystem.mapper.NewsMapper; import com.javaee.newssystem.service.INewsService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.javaee.newssystem.utils.RedisUtil; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.w3c.dom.ls.LSInput; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** *

@@ -30,6 +33,12 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Autowired NewsMapper newsMapper; + @Autowired + RedisUtil redisUtil; + + @Autowired + RedisTemplate redisTemplate; + @Override public Page GetPublicList(Integer current, Integer size) { @@ -165,4 +174,32 @@ public class NewsServiceImpl extends ServiceImpl implements IN newsMapper.insert(news); } + @Override + public Page searchNews(String key, Integer current, Integer size) { + 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 page; + } + + @Override + public List getHotKey(Integer number){ + List hotWordList = new ArrayList<>(); + Set> typedTupleSet = redisTemplate.opsForZSet().reverseRangeByScoreWithScores("newsHotKey",1,100); + 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/RedisServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java new file mode 100644 index 0000000..296fee5 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java @@ -0,0 +1,21 @@ +package com.javaee.newssystem.service.impl; + +import com.javaee.newssystem.service.RedisService; +import com.javaee.newssystem.utils.RedisUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class RedisServiceImpl implements RedisService { + + @Autowired + RedisUtil redisUtil; + + + @Override + public List getHotKey() { + 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 bba61d3..d0dce9f 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java @@ -10,7 +10,11 @@ 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 org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -37,6 +41,8 @@ public class UserServiceImpl extends ServiceImpl implements IU @Autowired UserMapper userMapper; + @Autowired + RedisUtil redisUtil; @Override public User Login(String userName, String password) { @@ -63,7 +69,7 @@ public class UserServiceImpl extends ServiceImpl implements IU @Transactional @Override - public void Register(User user) { + public Boolean Register(User user) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_phone",user.getUserPhone()) .or() @@ -74,14 +80,15 @@ 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; } +// @CachePut(value = "userInfo") @Transactional @Override public User updateInfo(User user, MultipartFile headImg) { @@ -119,6 +126,7 @@ public class UserServiceImpl extends ServiceImpl implements IU return user; } +// @CacheEvict(value = "uerInfo",key = "#userId") @Transactional @Override public Boolean Logout(Long userId) { @@ -208,6 +216,7 @@ public class UserServiceImpl extends ServiceImpl implements IU } } +// @Cacheable(cacheNames = "userInfo",key = "#token") @Override public User getUserInfo(String token) { Map map = JwtUtil.parse(token); 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 0000000..9c752ae --- /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/resources/application.yml b/src/main/resources/application.yml index 37c5c89..912600a 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,16 +1,27 @@ spring: datasource: - url: jdbc:mysql://124.70.20.202:3306/javaee?serverTimezone=Asia/Shanghai + url: jdbc:mysql://localhost:3306/news?serverTimezone=Asia/Shanghai username: root - password: QQqq814287041 + 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 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 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 0000000..71c456f --- /dev/null +++ b/src/test/java/com/javaee/newssystem/RedisTest.java @@ -0,0 +1,42 @@ +package com.javaee.newssystem; + +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; + + +@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); + } + } +} -- Gitee From dc01248abb5a6b506d4fc04900061521cfcb9bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=A4=E5=8F=AA=E9=B1=BC=E5=95=8A=E4=B8=A4=E5=8F=AA?= =?UTF-8?q?=E9=B1=BC?= <2986871391@qq.com> Date: Thu, 29 Dec 2022 12:30:45 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E7=94=A8=E6=88=B7=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../javaee/newssystem/config/CacheConfig.java | 36 +++++++++++++++++++ .../javaee/newssystem/config/RedisConfig.java | 4 +-- .../newssystem/controller/NewsController.java | 3 -- .../newssystem/controller/UserController.java | 18 ++++++---- .../newssystem/service/IUserService.java | 2 +- .../newssystem/service/ScheduledService.java | 5 +++ .../service/impl/NewsServiceImpl.java | 33 +++++++++-------- .../service/impl/UserServiceImpl.java | 22 ++++++------ 8 files changed, 85 insertions(+), 38 deletions(-) create mode 100644 src/main/java/com/javaee/newssystem/config/CacheConfig.java 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 0000000..c2cf64e --- /dev/null +++ b/src/main/java/com/javaee/newssystem/config/CacheConfig.java @@ -0,0 +1,36 @@ +package com.javaee.newssystem.config; + +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.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; + + +import java.time.Duration; + +@Configuration +public class CacheConfig { + + private Long expirationTime = 60L * 60L; + + @Bean(name = "cacheManager") + @Primary + public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { + RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + //设置过期时间 + .entryTtl(Duration.ofSeconds(expirationTime)) + //禁止缓存null对象 + .disableCachingNullValues() + //定义了key和value的序列化协议,同时hash key和hash value也被定义 + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())); + + 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 index 9f09a09..ffb028c 100644 --- a/src/main/java/com/javaee/newssystem/config/RedisConfig.java +++ b/src/main/java/com/javaee/newssystem/config/RedisConfig.java @@ -19,10 +19,10 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; * @describe */ -//编写我们自己的RedisTemplate + @Configuration public class RedisConfig { - //固定redis模板,在工作中,拿去就可以用 + @Bean("redisTemplate") @SuppressWarnings("all") //改成String,Object类型 diff --git a/src/main/java/com/javaee/newssystem/controller/NewsController.java b/src/main/java/com/javaee/newssystem/controller/NewsController.java index 5bd1c9a..9ac9535 100644 --- a/src/main/java/com/javaee/newssystem/controller/NewsController.java +++ b/src/main/java/com/javaee/newssystem/controller/NewsController.java @@ -151,9 +151,6 @@ public class NewsController { // 获取热搜 @GetMapping("/topsearch") public Msg getTopsearch(Integer number){ - if (number==null){ - number = 10; - } List hotWords = newsService.getHotKey(number); return Msg.success("获取成功").add("data",hotWords); } diff --git a/src/main/java/com/javaee/newssystem/controller/UserController.java b/src/main/java/com/javaee/newssystem/controller/UserController.java index cd48e8f..817c09a 100644 --- a/src/main/java/com/javaee/newssystem/controller/UserController.java +++ b/src/main/java/com/javaee/newssystem/controller/UserController.java @@ -16,6 +16,7 @@ import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.util.List; +import java.util.Map; /** *

@@ -79,13 +80,18 @@ public class UserController { @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("不存在此用户"); + Map map = JwtUtil.parse(token); + if((Boolean) map.get("status")){ + Long id = (Long) map.get("id"); + User user = userService.getUserInfo(id); + if(user!=null){ + return Msg.success("获取成功").add("data",user); + } + else { + return Msg.fail("不存在此用户"); + } } + return Msg.fail("token失效,请重新登录"); } // 用户修改密码 diff --git a/src/main/java/com/javaee/newssystem/service/IUserService.java b/src/main/java/com/javaee/newssystem/service/IUserService.java index 43b839c..3687992 100644 --- a/src/main/java/com/javaee/newssystem/service/IUserService.java +++ b/src/main/java/com/javaee/newssystem/service/IUserService.java @@ -41,5 +41,5 @@ public interface IUserService extends IService { Boolean updatePassword(Long userId, String oldPassword, String newsPassword); - User getUserInfo(String token); + User getUserInfo(Long userId); } diff --git a/src/main/java/com/javaee/newssystem/service/ScheduledService.java b/src/main/java/com/javaee/newssystem/service/ScheduledService.java index 7872448..62a29d2 100644 --- a/src/main/java/com/javaee/newssystem/service/ScheduledService.java +++ b/src/main/java/com/javaee/newssystem/service/ScheduledService.java @@ -3,6 +3,9 @@ package com.javaee.newssystem.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.text.SimpleDateFormat; +import java.util.Date; + @Service public class ScheduledService { @@ -13,6 +16,8 @@ public class ScheduledService { // @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秒输出)"); } } 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 7d8e2fe..020b106 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java @@ -9,6 +9,8 @@ import com.javaee.newssystem.service.INewsService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.javaee.newssystem.utils.RedisUtil; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.Cacheable; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ZSetOperations; @@ -26,8 +28,8 @@ import java.util.*; * @author qjj * @since 2022-11-28 */ +@CacheConfig(cacheNames = "newsInfo") @Service - public class NewsServiceImpl extends ServiceImpl implements INewsService { @Autowired @@ -39,12 +41,12 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Autowired RedisTemplate redisTemplate; - @Override public Page GetPublicList(Integer current, Integer size) { 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; } @@ -52,19 +54,19 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Override 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; } + @Cacheable @Override public Page GetTeamList(Long teamId,Integer current, Integer size) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("belong_team_id",teamId); newsMapper.selectPage(page,queryWrapper); return page; @@ -73,7 +75,7 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Override public Page GetMyselfList(Long userId, Integer current, Integer size) { Page page=new Page<>(current,size); - QueryWrapper queryWrapper=new QueryWrapper(); + QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("user_id",userId); newsMapper.selectPage(page,queryWrapper); return page; @@ -93,7 +95,7 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Override public Page GetPassList(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; @@ -102,7 +104,7 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Override 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; @@ -111,7 +113,7 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Override 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; @@ -120,7 +122,7 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Override 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; @@ -130,7 +132,7 @@ public class NewsServiceImpl extends ServiceImpl implements IN 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("已通过"); @@ -143,7 +145,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("未通过"); @@ -187,6 +189,9 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Override public List getHotKey(Integer number){ + if(number==null){ + number = 10; + } List hotWordList = new ArrayList<>(); Set> typedTupleSet = redisTemplate.opsForZSet().reverseRangeByScoreWithScores("newsHotKey",1,100); Iterator> iterator = typedTupleSet.iterator(); 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 d0dce9f..13d83b0 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java @@ -12,6 +12,7 @@ import com.javaee.newssystem.utils.MD5Util; import com.javaee.newssystem.utils.MyUtil; import com.javaee.newssystem.utils.RedisUtil; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; @@ -35,6 +36,7 @@ import java.util.Map; * @author qjj * @since 2022-11-28 */ +@CacheConfig(cacheNames = "userInfo") @Service public class UserServiceImpl extends ServiceImpl implements IUserService { @@ -67,6 +69,7 @@ public class UserServiceImpl extends ServiceImpl implements IU return null; } + @Transactional @Override public Boolean Register(User user) { @@ -88,7 +91,7 @@ public class UserServiceImpl extends ServiceImpl implements IU return false; } -// @CachePut(value = "userInfo") + @CachePut(key = "#user.userId") @Transactional @Override public User updateInfo(User user, MultipartFile headImg) { @@ -126,7 +129,7 @@ public class UserServiceImpl extends ServiceImpl implements IU return user; } -// @CacheEvict(value = "uerInfo",key = "#userId") + @CacheEvict(value = "uerInfo",key = "#userId") @Transactional @Override public Boolean Logout(Long userId) { @@ -216,16 +219,11 @@ public class UserServiceImpl extends ServiceImpl implements IU } } -// @Cacheable(cacheNames = "userInfo",key = "#token") + @Cacheable(cacheNames = "userInfo",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 User getUserInfo(Long userId) { + User user = userMapper.selectById(userId); + user.setUserPassword(null); + return user; } } -- Gitee From 32ec8981bf18c2bd0b4f1831f21e1ac0d346a386 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=A4=E5=8F=AA=E9=B1=BC=E5=95=8A=E4=B8=A4=E5=8F=AA?= =?UTF-8?q?=E9=B1=BC?= <2986871391@qq.com> Date: Sat, 7 Jan 2023 17:55:26 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/javaee/newssystem/config/CacheConfig.java | 7 +++++-- .../controller/ExceptionControllerAdvice.java | 2 +- .../javaee/newssystem/controller/NewsController.java | 5 +++-- .../javaee/newssystem/controller/TeamController.java | 5 +++-- .../javaee/newssystem/controller/UserController.java | 12 +++++------- .../java/com/javaee/newssystem/entity/HotWord.java | 6 +++--- src/main/java/com/javaee/newssystem/entity/News.java | 3 +++ src/main/java/com/javaee/newssystem/entity/Team.java | 2 ++ .../newssystem/service/impl/UserServiceImpl.java | 1 + 9 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/javaee/newssystem/config/CacheConfig.java b/src/main/java/com/javaee/newssystem/config/CacheConfig.java index c2cf64e..f38644f 100644 --- a/src/main/java/com/javaee/newssystem/config/CacheConfig.java +++ b/src/main/java/com/javaee/newssystem/config/CacheConfig.java @@ -1,5 +1,6 @@ package com.javaee.newssystem.config; +import com.javaee.newssystem.entity.User; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -7,6 +8,8 @@ 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; @@ -26,8 +29,8 @@ public class CacheConfig { .entryTtl(Duration.ofSeconds(expirationTime)) //禁止缓存null对象 .disableCachingNullValues() - //定义了key和value的序列化协议,同时hash key和hash value也被定义 - .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())); + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<>(User.class))); return RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(cacheConfiguration) diff --git a/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java index dbff3d7..71f3920 100644 --- a/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java +++ b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java @@ -32,6 +32,6 @@ public class ExceptionControllerAdvice { @ExceptionHandler(value = Throwable.class) public Msg handleException(Throwable throwable){ log.error("错误",throwable); - return Msg.fail("系统异常"); + 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 9ac9535..54faecd 100644 --- a/src/main/java/com/javaee/newssystem/controller/NewsController.java +++ b/src/main/java/com/javaee/newssystem/controller/NewsController.java @@ -11,6 +11,7 @@ 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; /** @@ -31,7 +32,7 @@ public class NewsController { //创建消息 @PostMapping(value = "/upload") - public Msg CreateNews(News news){ + public Msg CreateNews(@Valid News news){ if(CheckClassUtil.checkNews(news)){ newsService.CreateNews(news); if(news.getNewsId()!=null){ @@ -45,7 +46,7 @@ public class NewsController { //保存消息 @PostMapping(value = "/save") - public Msg SaveNews(News news){ + public Msg SaveNews(@Valid News news){ if(CheckClassUtil.checkNews(news)){ newsService.SaveNews(news); if(news.getNewsId()!=null){ diff --git a/src/main/java/com/javaee/newssystem/controller/TeamController.java b/src/main/java/com/javaee/newssystem/controller/TeamController.java index 6ae9072..57a536e 100644 --- a/src/main/java/com/javaee/newssystem/controller/TeamController.java +++ b/src/main/java/com/javaee/newssystem/controller/TeamController.java @@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.*; import org.springframework.stereotype.Controller; import org.springframework.web.multipart.MultipartFile; +import javax.validation.Valid; import java.util.List; /** @@ -31,7 +32,7 @@ public class TeamController { // 创建团队 @PostMapping("/create") - public Msg createTeam(Team team, @RequestPart("headImg")MultipartFile headImg){ + public Msg createTeam(@Valid Team team, @RequestPart("headImg")MultipartFile headImg){ if(CheckClassUtil.checkTeam(team)){ team = teamService.createTeam(team,headImg); if(team.getTeamId()!=null){ @@ -60,7 +61,7 @@ public class TeamController { // 更新团队信息 @PostMapping("/update/info") - public Msg updateInfo(Team team, @RequestPart("headImg")MultipartFile headImg){ + public Msg updateInfo(@Valid Team team, @RequestPart("headImg")MultipartFile headImg){ if(team!=null&&team.getTeamId()!=null){ team = teamService.updateInfo(team,headImg); Msg msg = Msg.success("更改信息成功"); diff --git a/src/main/java/com/javaee/newssystem/controller/UserController.java b/src/main/java/com/javaee/newssystem/controller/UserController.java index 817c09a..1d98e58 100644 --- a/src/main/java/com/javaee/newssystem/controller/UserController.java +++ b/src/main/java/com/javaee/newssystem/controller/UserController.java @@ -9,12 +9,11 @@ import com.javaee.newssystem.utils.CheckClassUtil; import com.javaee.newssystem.utils.JwtUtil; import com.mysql.cj.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; import java.util.List; import java.util.Map; @@ -54,7 +53,7 @@ public class UserController { // 用户注册 @RequestMapping(value = "/register",method = RequestMethod.POST) - public Msg Register(@Validated User user){ + public Msg Register(@Valid User user){ if (CheckClassUtil.checkUser(user)){ Boolean b = userService.Register(user); return b?Msg.success("注册成功").add("data",user):Msg.fail("用户名已存在"); @@ -64,7 +63,7 @@ public class UserController { // 用户修改信息 @RequestMapping(value = "/update/info",method = RequestMethod.POST) - public Msg updateInfo(@Validated User user,@RequestPart("headImg") MultipartFile headImg){ + public Msg updateInfo(@Valid User user, @RequestPart(value = "headImg",required = false) MultipartFile headImg){ if(user.getUserId()!=null){ user = userService.updateInfo(user, headImg); if(user!=null){ @@ -78,8 +77,7 @@ public class UserController { // 用户获取个人信息(通过token) @GetMapping("/info") - public Msg userInfo(HttpServletRequest request){ - String token = request.getHeader("token"); + public Msg userInfo(@RequestHeader("token") String token){ Map map = JwtUtil.parse(token); if((Boolean) map.get("status")){ Long id = (Long) map.get("id"); @@ -152,7 +150,7 @@ public class UserController { if (!userList.isEmpty()){ return Msg.success("查找成功").add("data",userList); } - 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 index 9f7f4e2..0367a31 100644 --- a/src/main/java/com/javaee/newssystem/entity/HotWord.java +++ b/src/main/java/com/javaee/newssystem/entity/HotWord.java @@ -6,13 +6,13 @@ import lombok.Data; @Data public class HotWord { - String hotword; + String hotWord; Integer num; - public HotWord(String hotword, Integer num) { - this.hotword = hotword; + public HotWord(String hotWord, Integer num) { + this.hotWord = hotWord; this.num = num; } } diff --git a/src/main/java/com/javaee/newssystem/entity/News.java b/src/main/java/com/javaee/newssystem/entity/News.java index 96503ca..fbd32fd 100644 --- a/src/main/java/com/javaee/newssystem/entity/News.java +++ b/src/main/java/com/javaee/newssystem/entity/News.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; @@ -37,11 +38,13 @@ public class News implements Serializable { /** * 新闻标题 */ + @Pattern(regexp = "^.{3,100}$",message = "标题长度必须在3-100之间") private String title; /** * 新闻内容 */ + @Pattern(regexp = "^.{10,}$",message = "内容长度必须在10以上") private String content; /** diff --git a/src/main/java/com/javaee/newssystem/entity/Team.java b/src/main/java/com/javaee/newssystem/entity/Team.java index 80ab34c..b271d39 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/service/impl/UserServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java index 13d83b0..78a4a00 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java @@ -123,6 +123,7 @@ public class UserServiceImpl extends ServiceImpl implements IU } } // 头像不用更新,直接更新数据库 + if (oldUser==null) return null; userMapper.updateById(user); user = userMapper.selectById(user); user.setUserPassword(null); -- Gitee From b4644414bed04f581b7ec56faca2a7e69276b0a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=A4=E5=8F=AA=E9=B1=BC=E5=95=8A=E4=B8=A4=E5=8F=AA?= =?UTF-8?q?=E9=B1=BC?= <2986871391@qq.com> Date: Fri, 3 Feb 2023 22:32:17 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E8=A7=A3=E6=95=A3=E6=88=96=E6=B3=A8?= =?UTF-8?q?=E9=94=80=E5=90=8E=E8=B5=84=E6=BA=90=E5=88=A0=E9=99=A4=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../javaee/newssystem/config/RedisConfig.java | 2 +- .../newssystem/controller/TeamController.java | 2 +- .../newssystem/controller/UserController.java | 3 +- .../interceptor/LoginInterceptor.java | 2 +- .../service/impl/TeamServiceImpl.java | 30 ++++++++++++---- .../service/impl/UserServiceImpl.java | 34 ++++++++++++------- .../com/javaee/newssystem/utils/MyUtil.java | 10 +++++- src/main/resources/application.yml | 5 +++ src/main/resources/templates/404.html | 11 ------ 10 files changed, 64 insertions(+), 37 deletions(-) delete mode 100644 src/main/resources/templates/404.html diff --git a/pom.xml b/pom.xml index 4e7ab0f..509edc7 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 diff --git a/src/main/java/com/javaee/newssystem/config/RedisConfig.java b/src/main/java/com/javaee/newssystem/config/RedisConfig.java index ffb028c..fd53b63 100644 --- a/src/main/java/com/javaee/newssystem/config/RedisConfig.java +++ b/src/main/java/com/javaee/newssystem/config/RedisConfig.java @@ -27,7 +27,7 @@ public class RedisConfig { @SuppressWarnings("all") //改成String,Object类型 public RedisTemplate redisTemplate(RedisConnectionFactory factory) { - //我们为了自己开发方便,一般直接使用 + RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(factory); diff --git a/src/main/java/com/javaee/newssystem/controller/TeamController.java b/src/main/java/com/javaee/newssystem/controller/TeamController.java index 57a536e..c23a420 100644 --- a/src/main/java/com/javaee/newssystem/controller/TeamController.java +++ b/src/main/java/com/javaee/newssystem/controller/TeamController.java @@ -61,7 +61,7 @@ public class TeamController { // 更新团队信息 @PostMapping("/update/info") - public Msg updateInfo(@Valid Team team, @RequestPart("headImg")MultipartFile headImg){ + public Msg updateInfo(@Valid Team team, @RequestPart(value = "headImg",required = false)MultipartFile headImg){ if(team!=null&&team.getTeamId()!=null){ team = teamService.updateInfo(team,headImg); Msg msg = Msg.success("更改信息成功"); diff --git a/src/main/java/com/javaee/newssystem/controller/UserController.java b/src/main/java/com/javaee/newssystem/controller/UserController.java index 1d98e58..bba2240 100644 --- a/src/main/java/com/javaee/newssystem/controller/UserController.java +++ b/src/main/java/com/javaee/newssystem/controller/UserController.java @@ -9,6 +9,7 @@ import com.javaee.newssystem.utils.CheckClassUtil; import com.javaee.newssystem.utils.JwtUtil; import com.mysql.cj.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.ClassUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -70,7 +71,7 @@ public class UserController { return Msg.success("修改成功").add("data",user); } else - Msg.fail("修改失败"); + return Msg.fail("修改失败"); } return Msg.fail("修改失败,缺少用户id"); } diff --git a/src/main/java/com/javaee/newssystem/interceptor/LoginInterceptor.java b/src/main/java/com/javaee/newssystem/interceptor/LoginInterceptor.java index 8728c71..d61832b 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/service/impl/TeamServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java index 2ebf226..f44fc59 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; @@ -67,6 +69,9 @@ public class TeamServiceImpl extends ServiceImpl implements IT return teamPage; } + @Value("${web.upload-path}") + private String uploadPath; + @Override public Team updateInfo(Team team, MultipartFile headImg) { //获取旧的团队信息 @@ -78,19 +83,22 @@ public class TeamServiceImpl extends ServiceImpl implements IT //处理头像资源 if(!headImg.isEmpty()){ - -// 生成新的头像路径 - Map map = MyUtil.getPath(headImg); // 获取旧的头像路径 if (oldTeam.getTeamIcon()!=null){ - String oldHeadImgPath = map.get("objectImgPath")+oldTeam.getTeamIcon(); + String oldHeadImgPath =uploadPath+oldTeam.getTeamIcon(); // 删除旧头像资源 File file = new File(oldHeadImgPath); - file.delete(); + FileSystemUtils.deleteRecursively(file); } try { +// 生成新的头像路径 + Map map = MyUtil.getPath(headImg); // 更新新头像资源并更新数据库 - headImg.transferTo(new File(map.get("headImgPath"))); + File folder = new File(uploadPath); + if(!folder.isDirectory()){ + folder.mkdirs(); + } + headImg.transferTo(new File(folder,map.get("filename"))); team.setTeamIcon(map.get("filename")); teamMapper.updateById(team); team = teamMapper.selectById(team); @@ -108,7 +116,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/UserServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java index 78a4a00..585cfc4 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java @@ -12,16 +12,20 @@ import com.javaee.newssystem.utils.MD5Util; import com.javaee.newssystem.utils.MyUtil; import com.javaee.newssystem.utils.RedisUtil; 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.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; @@ -91,7 +95,10 @@ public class UserServiceImpl extends ServiceImpl implements IU return false; } - @CachePut(key = "#user.userId") + @Value("${web.upload-path}") + private String uploadPath; + + @CachePut(key = "#user.userId",condition = "#result!=null") @Transactional @Override public User updateInfo(User user, MultipartFile headImg) { @@ -99,19 +106,22 @@ public class UserServiceImpl extends ServiceImpl implements IU User oldUser = userMapper.selectById(user.getUserId()); //处理头像资源 if(oldUser!=null&&!headImg.isEmpty()){ - -// 生成新的头像路径 - Map map = MyUtil.getPath(headImg); // 获取旧的头像路径 if(oldUser.getUserIcon()!=null){ - String oldHeadImgPath = map.get("objectImgPath")+oldUser.getUserIcon(); + String oldHeadImgPath = uploadPath+oldUser.getUserIcon(); // 删除旧头像资源 File file = new File(oldHeadImgPath); - file.delete(); + FileSystemUtils.deleteRecursively(file); } try { +// 生成新的头像路径 + Map map = MyUtil.getPath(headImg); // 更新新头像资源并更新数据库 - headImg.transferTo(new File(map.get("headImgPath"))); + File folder = new File(uploadPath); + if(!folder.isDirectory()){ + folder.mkdirs(); + } + headImg.transferTo(new File(folder,map.get("filename"))); user.setUserIcon(map.get("filename")); userMapper.updateById(user); user = userMapper.selectById(user); @@ -130,20 +140,18 @@ public class UserServiceImpl extends ServiceImpl implements IU return user; } - @CacheEvict(value = "uerInfo",key = "#userId") + @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; } @@ -220,7 +228,7 @@ public class UserServiceImpl extends ServiceImpl implements IU } } - @Cacheable(cacheNames = "userInfo",key = "#userId") + @Cacheable(key = "#userId") @Override public User getUserInfo(Long userId) { User user = userMapper.selectById(userId); diff --git a/src/main/java/com/javaee/newssystem/utils/MyUtil.java b/src/main/java/com/javaee/newssystem/utils/MyUtil.java index 87c6e7f..cfebd71 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/resources/application.yml b/src/main/resources/application.yml index 912600a..56b83a2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,3 +1,5 @@ +web: + upload-path: D:/HeadImg/ spring: datasource: url: jdbc:mysql://localhost:3306/news?serverTimezone=Asia/Shanghai @@ -22,6 +24,9 @@ spring: 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 diff --git a/src/main/resources/templates/404.html b/src/main/resources/templates/404.html deleted file mode 100644 index 85563cc..0000000 --- a/src/main/resources/templates/404.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - 404页面 - - -

404,页面丢失

-

测试自定义的错误页面

- - \ No newline at end of file -- Gitee From ea05f70c2d6dec26ab340e438d1c6f394c154e4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=A4=E5=8F=AA=E9=B1=BC=E5=95=8A=E4=B8=A4=E5=8F=AA?= =?UTF-8?q?=E9=B1=BC?= <2986871391@qq.com> Date: Fri, 17 Feb 2023 13:44:15 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E5=8A=A0=E5=85=A5VO=EF=BC=8C=E6=8E=A5?= =?UTF-8?q?=E6=94=B6Json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../newssystem/config/AdminWebConfig.java | 14 +- .../javaee/newssystem/config/CacheConfig.java | 2 +- .../controller/AdminController.java | 51 ++++-- .../controller/CommentController.java | 10 +- .../controller/ExceptionControllerAdvice.java | 32 ++-- .../newssystem/controller/NewsController.java | 93 ++++++----- .../controller/RedisController.java | 10 +- .../newssystem/controller/TeamController.java | 18 +- .../newssystem/controller/UserController.java | 41 +++-- .../com/javaee/newssystem/entity/News.java | 36 ++-- .../com/javaee/newssystem/entity/User.java | 1 - .../newssystem/mapper/CommentMapper.java | 2 + .../javaee/newssystem/mapper/NewsMapper.java | 5 +- .../javaee/newssystem/mapper/UserMapper.java | 4 + .../newssystem/service/INewsService.java | 33 ++-- .../newssystem/service/IUserService.java | 2 +- .../newssystem/service/RedisService.java | 7 +- .../newssystem/service/ScheduledService.java | 62 +++++++ .../service/impl/NewsServiceImpl.java | 156 ++++++++++++------ .../service/impl/RedisServiceImpl.java | 54 +++++- .../service/impl/TeamServiceImpl.java | 3 +- .../service/impl/UserServiceImpl.java | 38 ++--- .../java/com/javaee/newssystem/vo/NewsVo.java | 66 ++++++++ .../javaee/newssystem/vo/NewsWithUserVo.java | 11 ++ .../java/com/javaee/newssystem/vo/UserVo.java | 33 ++++ src/main/resources/application.yml | 10 +- src/main/resources/mapper/NewsMapper.xml | 9 +- src/main/resources/mapper/UserMapper.xml | 4 + .../javaee/newssystem/MybatisPlusTest.java | 11 ++ .../java/com/javaee/newssystem/OtherTest.java | 30 ++++ .../java/com/javaee/newssystem/RedisTest.java | 55 ++++++ 31 files changed, 672 insertions(+), 231 deletions(-) create mode 100644 src/main/java/com/javaee/newssystem/vo/NewsVo.java create mode 100644 src/main/java/com/javaee/newssystem/vo/NewsWithUserVo.java create mode 100644 src/main/java/com/javaee/newssystem/vo/UserVo.java diff --git a/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java b/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java index a92ca27..6d9aaa9 100644 --- a/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java +++ b/src/main/java/com/javaee/newssystem/config/AdminWebConfig.java @@ -13,12 +13,12 @@ public class AdminWebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 添加登录验证的拦截器 -// registry.addInterceptor(new LoginInterceptor()) -// .addPathPatterns("/**") -// .excludePathPatterns("/user/login","/admin/login","/user/register"); -//// 添加管理员身份验证的拦截器 -// registry.addInterceptor(new AdminInterceptor()) -// .excludePathPatterns("/admin/login") -// .addPathPatterns("/admin/**"); + registry.addInterceptor(new LoginInterceptor()) + .addPathPatterns("/**") + .excludePathPatterns("/user/login","/admin/login","/user/register"); +// 添加管理员身份验证的拦截器 + registry.addInterceptor(new AdminInterceptor()) + .excludePathPatterns("/admin/login") + .addPathPatterns("/admin/**"); } } diff --git a/src/main/java/com/javaee/newssystem/config/CacheConfig.java b/src/main/java/com/javaee/newssystem/config/CacheConfig.java index f38644f..3173549 100644 --- a/src/main/java/com/javaee/newssystem/config/CacheConfig.java +++ b/src/main/java/com/javaee/newssystem/config/CacheConfig.java @@ -19,7 +19,7 @@ import java.time.Duration; @Configuration public class CacheConfig { - private Long expirationTime = 60L * 60L; + private Long expirationTime = 60L * 60L * 24L; @Bean(name = "cacheManager") @Primary diff --git a/src/main/java/com/javaee/newssystem/controller/AdminController.java b/src/main/java/com/javaee/newssystem/controller/AdminController.java index 35867cd..028a38b 100644 --- a/src/main/java/com/javaee/newssystem/controller/AdminController.java +++ b/src/main/java/com/javaee/newssystem/controller/AdminController.java @@ -6,13 +6,22 @@ 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.NewsVo; 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.function.Consumer; /** *

@@ -36,10 +45,12 @@ 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 String userName,@RequestBody String password){ if(StringUtils.isNullOrEmpty(userName)&&StringUtils.isNullOrEmpty(password)){ return Msg.fail("登录失败,缺少参数"); } @@ -73,7 +84,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,7 +94,7 @@ public class AdminController { // 管理员恢复用户账号 @RequestMapping(value = "/unlogout",method = RequestMethod.POST) - public Msg unlogoutUser(Long userId){ + public Msg unlogoutUser(@RequestBody Long userId){ if(userId!=null){ Boolean b = userService.adminUnlogoutUser(userId); if(b) @@ -96,7 +107,7 @@ public class AdminController { // 管理员修改消息状态为通过 @RequestMapping(value = "/status/pass",method = RequestMethod.POST) - public Msg pass(Long newsId){ + public Msg pass(@RequestBody Long newsId){ if(newsId!=null){ Boolean b = newsService.PassNews(newsId); return b?Msg.success("修改为通过成功"):Msg.fail("修改为通过失败"); @@ -106,7 +117,7 @@ public class AdminController { // 管理员修改消息状态为未通过 @RequestMapping(value = "/status/unpass",method = RequestMethod.POST) - public Msg unpass(Long newsId){ + public Msg unpass(@RequestBody Long newsId){ if(newsId!=null){ Boolean b = newsService.UnPassNews(newsId); return b?Msg.success("修改为未通过成功"):Msg.fail("修改为未通过失败"); @@ -118,7 +129,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 +139,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 +149,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 +182,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 ac20d3a..3c34119 100644 --- a/src/main/java/com/javaee/newssystem/controller/CommentController.java +++ b/src/main/java/com/javaee/newssystem/controller/CommentController.java @@ -26,7 +26,7 @@ public class CommentController { //发表一级评论 @PostMapping("/first") - public Msg createComment(Comment comment){ + public Msg createComment(@RequestBody Comment comment){ if(comment!=null){ comment=commentService.createComment(comment); if (comment.getCommentId() != null){ @@ -40,7 +40,7 @@ public class CommentController { //发表二级评论 @PostMapping("/second") - public Msg createSecondComment(Comment comment){ + public Msg createSecondComment(@RequestBody Comment comment){ if(comment!=null){ comment=commentService.createComment(comment); if (comment.getCommentId() != null){ @@ -54,7 +54,7 @@ public class CommentController { //点赞评论 @PostMapping("/like") - public Msg createLike(Long userId,Long commentId){ + public Msg createLike(@RequestBody Long userId,@RequestBody Long commentId){ if(userId!=null && commentId != null){ Boolean b = commentService.createLike(userId,commentId); return b?Msg.success("点赞成功"):Msg.fail("点赞失败"); @@ -64,7 +64,7 @@ public class CommentController { //取消点赞 @PostMapping("/unlike") - public Msg deleteLike(Long userId,Long commentId){ + public Msg deleteLike(@RequestBody Long userId,@RequestBody Long commentId){ if(userId!=null && commentId != null){ Boolean b = commentService.deleteLike(userId,commentId); return b?Msg.success("取消成功"):Msg.fail("取消失败"); @@ -74,7 +74,7 @@ public class CommentController { //删除评论 @PostMapping("/delete") - public Msg deleteComment(Long commentId){ + public Msg deleteComment(@RequestBody Long commentId){ if(commentId != null){ Boolean b = commentService.deleteComment(commentId); return b?Msg.success("删除评论成功"):Msg.fail("删除评论失败"); diff --git a/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java index 71f3920..3f026b2 100644 --- a/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java +++ b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java @@ -2,12 +2,16 @@ 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") @@ -15,17 +19,23 @@ 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); - } - return Msg.fail("参数校验错误",400).add("errorMessage",messageStr); +// 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<>(); + bindingResult.getFieldErrors().forEach(fieldError -> { + errorMap.put(fieldError.getField(),fieldError.getDefaultMessage()); + }); + return Msg.fail("参数校验错误",400).add("data",errorMap); } diff --git a/src/main/java/com/javaee/newssystem/controller/NewsController.java b/src/main/java/com/javaee/newssystem/controller/NewsController.java index 54faecd..9113e2a 100644 --- a/src/main/java/com/javaee/newssystem/controller/NewsController.java +++ b/src/main/java/com/javaee/newssystem/controller/NewsController.java @@ -6,7 +6,10 @@ 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.*; @@ -29,16 +32,16 @@ public class NewsController { @Autowired NewsServiceImpl newsService; + @Autowired + RedisServiceImpl redisService; //创建消息 @PostMapping(value = "/upload") - public Msg CreateNews(@Valid 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("缺少参数"); @@ -46,13 +49,11 @@ public class NewsController { //保存消息 @PostMapping(value = "/save") - public Msg SaveNews(@Valid 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("缺少参数"); @@ -62,64 +63,54 @@ 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){ + public Msg deleteTeam(@RequestBody Long newsId){ if(newsId!=null){ Boolean b = newsService.deleteNews(newsId); return b?Msg.success("删除成功"):Msg.fail("删除失败"); @@ -129,21 +120,39 @@ public class NewsController { //获取消息的关注人数 @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("缺少参数"); + } + + //关注消息 + @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){ + public Msg searchNews(String key,Integer current,Integer size,@RequestHeader("token") String token){ if(!StringUtils.isNullOrEmpty(key)){ - Page page = newsService.searchNews(key,current,size); + Page page = newsService.searchNews(key,current,size,token); return Msg.success("获取成功").add("data",page); } return Msg.fail("缺少参数"); @@ -152,7 +161,7 @@ public class NewsController { // 获取热搜 @GetMapping("/topsearch") public Msg getTopsearch(Integer number){ - List hotWords = newsService.getHotKey(number); + List hotWords = redisService.getHotKey(number); return Msg.success("获取成功").add("data",hotWords); } } diff --git a/src/main/java/com/javaee/newssystem/controller/RedisController.java b/src/main/java/com/javaee/newssystem/controller/RedisController.java index 8f0d510..7fd1ad7 100644 --- a/src/main/java/com/javaee/newssystem/controller/RedisController.java +++ b/src/main/java/com/javaee/newssystem/controller/RedisController.java @@ -1,17 +1,15 @@ package com.javaee.newssystem.controller; -import com.javaee.newssystem.entity.Msg; -import org.springframework.web.bind.annotation.GetMapping; +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 { - @GetMapping("getHotKey") - public Msg getHotKey(){ + @Autowired + RedisTemplate redisTemplate; - return null; - } } diff --git a/src/main/java/com/javaee/newssystem/controller/TeamController.java b/src/main/java/com/javaee/newssystem/controller/TeamController.java index c23a420..96f906d 100644 --- a/src/main/java/com/javaee/newssystem/controller/TeamController.java +++ b/src/main/java/com/javaee/newssystem/controller/TeamController.java @@ -9,11 +9,9 @@ import com.javaee.newssystem.utils.CheckClassUtil; 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 javax.validation.Valid; -import java.util.List; /** *

@@ -32,7 +30,7 @@ public class TeamController { // 创建团队 @PostMapping("/create") - public Msg createTeam(@Valid Team team, @RequestPart("headImg")MultipartFile headImg){ + public Msg createTeam(@RequestBody @Valid Team team, @RequestPart("headImg")MultipartFile headImg){ if(CheckClassUtil.checkTeam(team)){ team = teamService.createTeam(team,headImg); if(team.getTeamId()!=null){ @@ -61,7 +59,7 @@ public class TeamController { // 更新团队信息 @PostMapping("/update/info") - public Msg updateInfo(@Valid Team team, @RequestPart(value = "headImg",required = false)MultipartFile headImg){ + public Msg updateInfo(@RequestBody @Valid Team team, @RequestPart(value = "headImg",required = false) MultipartFile headImg){ if(team!=null&&team.getTeamId()!=null){ team = teamService.updateInfo(team,headImg); Msg msg = Msg.success("更改信息成功"); @@ -73,7 +71,7 @@ public class TeamController { // 解散团队 @PostMapping("/delete") - public Msg deleteTeam(Long teamId){ + public Msg deleteTeam(@RequestBody Long teamId){ if(teamId!=null){ Boolean b = teamService.deleteTeam(teamId); return b?Msg.success("解散成功"):Msg.fail("解散失败"); @@ -83,7 +81,7 @@ public class TeamController { // 置顶消息 @PostMapping("/first") - public Msg firstNews(Long teamId,Long newsId){ + public Msg firstNews(@RequestBody Long teamId,@RequestBody Long newsId){ if(teamId!=null&&newsId!=null){ Team team = teamService.firstNews(teamId,newsId); if(team!=null){ @@ -97,7 +95,7 @@ public class TeamController { // 邀请用户 @PostMapping("/invite") - public Msg inviteUser(Long teamId,Long userId){ + public Msg inviteUser(@RequestBody Long teamId,@RequestBody Long userId){ if(teamId!=null&&userId!=null){ Boolean b = teamService.invite(teamId,userId); if (b){ @@ -111,7 +109,7 @@ public class TeamController { // 踢出用户 @PostMapping("/deleteMember") - public Msg deleteUser(Long teamId,Long userId){ + public Msg deleteUser(@RequestBody Long teamId,@RequestBody Long userId){ if(teamId!=null&&userId!=null){ Boolean b = teamService.deleteUser(teamId,userId); if(b){ @@ -125,7 +123,7 @@ public class TeamController { // 转换管理权 @PostMapping("/change/leader") - public Msg changeLeader(Long teamId,Long userId){ + public Msg changeLeader(@RequestBody Long teamId,@RequestBody Long userId){ if(teamId!=null&&userId!=null){ Boolean b = teamService.changeLeader(teamId,userId); return b?Msg.success("转让成功"):Msg.fail("转让失败"); @@ -151,7 +149,7 @@ public class TeamController { // 成员退出团队 @PostMapping("/member/delete") - public Msg memberDelete(Long userId,Long teamId){ + public Msg memberDelete(@RequestBody Long userId,@RequestBody Long teamId){ if(userId!=null&&teamId!=null){ Boolean b = teamService.memberDelete(userId,teamId); if(b) diff --git a/src/main/java/com/javaee/newssystem/controller/UserController.java b/src/main/java/com/javaee/newssystem/controller/UserController.java index bba2240..b97cf82 100644 --- a/src/main/java/com/javaee/newssystem/controller/UserController.java +++ b/src/main/java/com/javaee/newssystem/controller/UserController.java @@ -7,9 +7,9 @@ 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.UserVo; import com.mysql.cj.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.ClassUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -35,17 +35,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("登录成功").add("data",user); + Long userId = userService.Login(userName, userPassword); + if (userId!=null){ + User userInfo = userService.getUserInfo(userId); + if(userInfo!=null){ + Msg msg = Msg.success("登录成功").add("data",userInfo); // 生成token - msg.add("token", JwtUtil.getToken(user.getUserId(),"用户")); - return msg; + msg.add("token", JwtUtil.getToken(userInfo.getUserId(),"用户")); + return msg; + } + return Msg.fail("登录成功,但服务器内部出现错误"); } else return Msg.fail("账号或密码错误"); @@ -54,17 +60,17 @@ public class UserController { // 用户注册 @RequestMapping(value = "/register",method = RequestMethod.POST) - public Msg Register(@Valid User user){ + public Msg Register(@RequestBody @Valid User user){ if (CheckClassUtil.checkUser(user)){ Boolean b = userService.Register(user); - return b?Msg.success("注册成功").add("data",user):Msg.fail("用户名已存在"); + return b?Msg.success("注册成功"):Msg.fail("用户名已存在"); } return Msg.fail("注册失败,缺少参数"); } // 用户修改信息 @RequestMapping(value = "/update/info",method = RequestMethod.POST) - public Msg updateInfo(@Valid User user, @RequestPart(value = "headImg",required = false) MultipartFile headImg){ + public Msg updateInfo(@RequestBody @Valid User user, @RequestPart(value = "headImg",required = false) MultipartFile headImg){ if(user.getUserId()!=null){ user = userService.updateInfo(user, headImg); if(user!=null){ @@ -95,7 +101,10 @@ public class UserController { // 用户修改密码 @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("密码错误"); @@ -105,7 +114,7 @@ public class UserController { // 用户注销账号 @RequestMapping(value = "logout",method = RequestMethod.POST) - public Msg Logout(Long userId){ + public Msg Logout(@RequestBody Long userId){ if(userId!=null){ Boolean b = userService.Logout(userId); return b?Msg.success("注销成功"):Msg.fail("该用户已被注销"); @@ -125,7 +134,9 @@ public class UserController { // 添加关注用户 @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); return b?Msg.success("取消关注成功"):Msg.fail("该用户未被关注"); @@ -135,7 +146,9 @@ public class UserController { // 取消关注用户 @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); return b?Msg.success("取消关注成功"):Msg.fail("该用户未被关注"); diff --git a/src/main/java/com/javaee/newssystem/entity/News.java b/src/main/java/com/javaee/newssystem/entity/News.java index fbd32fd..5278b56 100644 --- a/src/main/java/com/javaee/newssystem/entity/News.java +++ b/src/main/java/com/javaee/newssystem/entity/News.java @@ -1,5 +1,6 @@ package com.javaee.newssystem.entity; + import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; @@ -68,13 +69,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; } @@ -82,6 +77,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; } @@ -135,15 +139,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/User.java b/src/main/java/com/javaee/newssystem/entity/User.java index 0bdf02b..3d78ded 100644 --- a/src/main/java/com/javaee/newssystem/entity/User.java +++ b/src/main/java/com/javaee/newssystem/entity/User.java @@ -2,7 +2,6 @@ package com.javaee.newssystem.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; -import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Pattern; import java.io.Serializable; diff --git a/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java b/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java index adb9316..74863a5 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 diff --git a/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java b/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java index c26a376..922c47a 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,8 @@ 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); } diff --git a/src/main/java/com/javaee/newssystem/mapper/UserMapper.java b/src/main/java/com/javaee/newssystem/mapper/UserMapper.java index 1675513..61df026 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; /** *

@@ -24,4 +26,6 @@ public interface UserMapper extends BaseMapper { Integer delete(Long userId,Long focusedUserId); Integer changeStatus(Long userId); + + Integer isExist(Long userId,Long newsId); } diff --git a/src/main/java/com/javaee/newssystem/service/INewsService.java b/src/main/java/com/javaee/newssystem/service/INewsService.java index 372bc9f..0b55bac 100644 --- a/src/main/java/com/javaee/newssystem/service/INewsService.java +++ b/src/main/java/com/javaee/newssystem/service/INewsService.java @@ -5,6 +5,7 @@ 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; @@ -18,29 +19,29 @@ import java.util.List; */ 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); @@ -48,8 +49,14 @@ public interface INewsService extends IService { Boolean UnPassNews(Long newsId); - Page searchNews(String key, Integer current, Integer size); + Page searchNews(String key, Integer current, Integer size,String token); - List getHotKey(Integer number); + Page addUserInfo(Page page,Long requestorId); + + NewsVo addUserInfo(News news,Long requestorId); + + Boolean UserFocusNews(Long newsId,Long userId); + + Boolean UserCancelFocusNews(Long newsId, Long userId); } diff --git a/src/main/java/com/javaee/newssystem/service/IUserService.java b/src/main/java/com/javaee/newssystem/service/IUserService.java index 3687992..07f2a2a 100644 --- a/src/main/java/com/javaee/newssystem/service/IUserService.java +++ b/src/main/java/com/javaee/newssystem/service/IUserService.java @@ -17,7 +17,7 @@ import java.util.List; */ public interface IUserService extends IService { - User Login(String userName,String password); + Long Login(String userName,String password); Boolean Register(User user); diff --git a/src/main/java/com/javaee/newssystem/service/RedisService.java b/src/main/java/com/javaee/newssystem/service/RedisService.java index 90f72b1..36c3ee1 100644 --- a/src/main/java/com/javaee/newssystem/service/RedisService.java +++ b/src/main/java/com/javaee/newssystem/service/RedisService.java @@ -1,9 +1,14 @@ package com.javaee.newssystem.service; +import com.javaee.newssystem.entity.HotWord; + import java.util.List; public interface RedisService { - List getHotKey(); + 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 index 62a29d2..7796f7d 100644 --- a/src/main/java/com/javaee/newssystem/service/ScheduledService.java +++ b/src/main/java/com/javaee/newssystem/service/ScheduledService.java @@ -1,10 +1,19 @@ 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 { @@ -20,4 +29,57 @@ public class ScheduledService { 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++; + if(flag>=201){ + ZSetOperations.TypedTuple typedTuple = iterator.next(); + score = Math.ceil(typedTuple.getScore()); + break; + } + } + 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/NewsServiceImpl.java b/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java index 020b106..fec51dd 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java @@ -2,23 +2,26 @@ 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.HotWord; 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.RedisUtil; +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.cache.annotation.Cacheable; import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.w3c.dom.ls.LSInput; -import java.util.*; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; /** *

@@ -34,57 +37,56 @@ public class NewsServiceImpl extends ServiceImpl implements IN @Autowired NewsMapper newsMapper; - @Autowired - RedisUtil redisUtil; + 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","已通过") .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.in("news_id",focusNewsId); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,userId); } - @Cacheable @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.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.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 @@ -93,39 +95,39 @@ 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.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.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.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.eq("state","已保存").and(wrapper->wrapper.eq("user_id",userId)); newsMapper.selectPage(page,queryWrapper); - return page; + return addUserInfo(page,null); } @Override @@ -161,50 +163,100 @@ 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) { + 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 page; + return addUserInfo(page,tokenToRequestorId(token)); } @Override - public List getHotKey(Integer number){ - if(number==null){ - number = 10; + 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); } - List hotWordList = new ArrayList<>(); - Set> typedTupleSet = redisTemplate.opsForZSet().reverseRangeByScoreWithScores("newsHotKey",1,100); - 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 newsVo; + } + + @Override + public Boolean UserFocusNews(Long newsId,Long userId) { + Integer i = newsMapper.insertToFocusWithNews(newsId,userId); + return i>0; + } + + @Override + public Boolean UserCancelFocusNews(Long newsId, Long userId) { + Integer i = newsMapper.deleteFromFocusWithNews(newsId,userId); + return i>0; + } + + private Long tokenToRequestorId(String token){ + Map map = JwtUtil.parse(token); + Long requestorId = null; + if((Boolean) map.get("status")){ + requestorId = (Long) map.get("id"); } - return hotWordList; + 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 index 296fee5..814e334 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/RedisServiceImpl.java @@ -1,21 +1,65 @@ package com.javaee.newssystem.service.impl; +import com.javaee.newssystem.entity.HotWord; import com.javaee.newssystem.service.RedisService; -import com.javaee.newssystem.utils.RedisUtil; 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.util.List; +import java.text.SimpleDateFormat; +import java.util.*; @Service public class RedisServiceImpl implements RedisService { @Autowired - RedisUtil redisUtil; + 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() { - return null; + 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 f44fc59..b54f375 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java @@ -72,6 +72,7 @@ public class TeamServiceImpl extends ServiceImpl implements IT @Value("${web.upload-path}") private String uploadPath; + @Transactional @Override public Team updateInfo(Team team, MultipartFile headImg) { //获取旧的团队信息 @@ -82,7 +83,7 @@ public class TeamServiceImpl extends ServiceImpl implements IT } //处理头像资源 - if(!headImg.isEmpty()){ + if(headImg!=null&&!headImg.isEmpty()){ // 获取旧的头像路径 if (oldTeam.getTeamIcon()!=null){ String oldHeadImgPath =uploadPath+oldTeam.getTeamIcon(); 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 585cfc4..b278c0b 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java @@ -17,6 +17,8 @@ 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; @@ -47,33 +49,25 @@ public class UserServiceImpl extends ServiceImpl implements IU @Autowired UserMapper userMapper; - @Autowired - RedisUtil redisUtil; - @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 Boolean Register(User user) { @@ -98,14 +92,14 @@ public class UserServiceImpl extends ServiceImpl implements IU @Value("${web.upload-path}") private String uploadPath; - @CachePut(key = "#user.userId",condition = "#result!=null") + @CachePut(key = "#result.userId",condition = "#result!=null") @Transactional @Override public User updateInfo(User user, MultipartFile headImg) { //获取旧的用户信息 User oldUser = userMapper.selectById(user.getUserId()); //处理头像资源 - if(oldUser!=null&&!headImg.isEmpty()){ + if(oldUser!=null&&headImg!=null&&!headImg.isEmpty()){ // 获取旧的头像路径 if(oldUser.getUserIcon()!=null){ String oldHeadImgPath = uploadPath+oldUser.getUserIcon(); 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 0000000..89d8d93 --- /dev/null +++ b/src/main/java/com/javaee/newssystem/vo/NewsVo.java @@ -0,0 +1,66 @@ +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; +} 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 0000000..9668e64 --- /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/UserVo.java b/src/main/java/com/javaee/newssystem/vo/UserVo.java new file mode 100644 index 0000000..0c955df --- /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 56b83a2..ecf639d 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,8 +1,12 @@ web: +# upload-path: /usr/local/project/HeadImg upload-path: D:/HeadImg/ spring: - datasource: - url: jdbc:mysql://localhost:3306/news?serverTimezone=Asia/Shanghai +# datasource: +# url: jdbc:mysql://127.0.0.1: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 @@ -30,4 +34,4 @@ spring: mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl - type-aliases-package: com.javaee.newssystem.entity \ No newline at end of file + type-aliases-package: com.javaee.newssystem.entity diff --git a/src/main/resources/mapper/NewsMapper.xml b/src/main/resources/mapper/NewsMapper.xml index 00ebe14..30c413a 100644 --- a/src/main/resources/mapper/NewsMapper.xml +++ b/src/main/resources/mapper/NewsMapper.xml @@ -1,13 +1,18 @@ + + 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 9db97c7..a43f10b 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/src/main/resources/mapper/UserMapper.xml @@ -14,4 +14,8 @@ + + diff --git a/src/test/java/com/javaee/newssystem/MybatisPlusTest.java b/src/test/java/com/javaee/newssystem/MybatisPlusTest.java index 1b4344b..2168dc6 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 b612ba7..c94616d 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 index 71c456f..ce05904 100644 --- a/src/test/java/com/javaee/newssystem/RedisTest.java +++ b/src/test/java/com/javaee/newssystem/RedisTest.java @@ -1,9 +1,20 @@ 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 @@ -39,4 +50,48 @@ public class RedisTest { 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(); + } } -- Gitee From 2622b10882d4cd709fa06c11448ad91d66f7f909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=A4=E5=8F=AA=E9=B1=BC=E5=95=8A=E4=B8=A4=E5=8F=AA?= =?UTF-8?q?=E9=B1=BC?= <2986871391@qq.com> Date: Sat, 18 Feb 2023 13:48:48 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E5=88=86=E7=A6=BB=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../newssystem/NewsSystemApplication.java | 1 - .../newssystem/config/AdminWebConfig.java | 15 +++- .../javaee/newssystem/config/CacheConfig.java | 1 + .../controller/AdminController.java | 36 ++++---- .../controller/CommentController.java | 36 ++++---- .../controller/ExceptionControllerAdvice.java | 4 +- .../newssystem/controller/NewsController.java | 20 +++-- .../newssystem/controller/TeamController.java | 45 +++++----- .../controller/UploadController.java | 24 +++++ .../newssystem/controller/UserController.java | 42 ++++----- .../com/javaee/newssystem/entity/News.java | 1 - .../com/javaee/newssystem/entity/User.java | 3 +- .../newssystem/mapper/CommentMapper.java | 1 + .../mapper/JacksonObjectMapper.java | 23 +++++ .../javaee/newssystem/mapper/NewsMapper.java | 3 + .../javaee/newssystem/mapper/UserMapper.java | 5 +- .../com/javaee/newssystem/mybatisgener.java | 29 ------ .../newssystem/service/IAdminService.java | 3 +- .../newssystem/service/ICommentService.java | 11 ++- .../newssystem/service/INewsService.java | 2 + .../newssystem/service/ITeamService.java | 4 +- .../newssystem/service/IUploadService.java | 7 ++ .../newssystem/service/IUserService.java | 11 +-- .../newssystem/service/ScheduledService.java | 10 +-- .../service/impl/AdminServiceImpl.java | 8 +- .../service/impl/CommentServiceImpl.java | 88 +++++++++++++++---- .../service/impl/NewsServiceImpl.java | 18 ++++ .../service/impl/TeamServiceImpl.java | 39 +------- .../service/impl/UploadServiceImpl.java | 40 +++++++++ .../service/impl/UserServiceImpl.java | 78 +++++++++------- .../com/javaee/newssystem/utils/JwtUtil.java | 2 +- .../com/javaee/newssystem/vo/AdminVo.java | 20 +++++ .../com/javaee/newssystem/vo/CommentVo.java | 45 ++++++++++ .../newssystem/vo/CommentWithUserVo.java | 18 ++++ .../java/com/javaee/newssystem/vo/NewsVo.java | 5 ++ .../java/com/javaee/newssystem/vo/TeamVo.java | 11 +++ .../com/javaee/newssystem/vo/UserRespVo.java | 49 +++++++++++ src/main/resources/application.yml | 18 ++-- src/main/resources/mapper/CommentMapper.xml | 7 +- src/main/resources/mapper/NewsMapper.xml | 3 + src/main/resources/mapper/UserMapper.xml | 5 +- 41 files changed, 561 insertions(+), 230 deletions(-) create mode 100644 src/main/java/com/javaee/newssystem/controller/UploadController.java create mode 100644 src/main/java/com/javaee/newssystem/mapper/JacksonObjectMapper.java delete mode 100644 src/main/java/com/javaee/newssystem/mybatisgener.java create mode 100644 src/main/java/com/javaee/newssystem/service/IUploadService.java create mode 100644 src/main/java/com/javaee/newssystem/service/impl/UploadServiceImpl.java create mode 100644 src/main/java/com/javaee/newssystem/vo/AdminVo.java create mode 100644 src/main/java/com/javaee/newssystem/vo/CommentVo.java create mode 100644 src/main/java/com/javaee/newssystem/vo/CommentWithUserVo.java create mode 100644 src/main/java/com/javaee/newssystem/vo/TeamVo.java create mode 100644 src/main/java/com/javaee/newssystem/vo/UserRespVo.java diff --git a/src/main/java/com/javaee/newssystem/NewsSystemApplication.java b/src/main/java/com/javaee/newssystem/NewsSystemApplication.java index 516e9bb..34b71df 100644 --- a/src/main/java/com/javaee/newssystem/NewsSystemApplication.java +++ b/src/main/java/com/javaee/newssystem/NewsSystemApplication.java @@ -6,7 +6,6 @@ import org.springframework.cache.annotation.EnableCaching; import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling -@EnableCaching @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 6d9aaa9..03f0c36 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 index 3173549..743c12b 100644 --- a/src/main/java/com/javaee/newssystem/config/CacheConfig.java +++ b/src/main/java/com/javaee/newssystem/config/CacheConfig.java @@ -1,6 +1,7 @@ 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; diff --git a/src/main/java/com/javaee/newssystem/controller/AdminController.java b/src/main/java/com/javaee/newssystem/controller/AdminController.java index 028a38b..af7b644 100644 --- a/src/main/java/com/javaee/newssystem/controller/AdminController.java +++ b/src/main/java/com/javaee/newssystem/controller/AdminController.java @@ -6,7 +6,10 @@ 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; @@ -21,6 +24,7 @@ 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; /** @@ -50,17 +54,19 @@ public class AdminController { // 管理员登录 @RequestMapping(value = "/login",method = RequestMethod.POST) - public Msg Login(@RequestBody String userName,@RequestBody 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 @@ -73,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; @@ -94,9 +100,9 @@ public class AdminController { // 管理员恢复用户账号 @RequestMapping(value = "/unlogout",method = RequestMethod.POST) - public Msg unlogoutUser(@RequestBody 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 @@ -107,9 +113,9 @@ public class AdminController { // 管理员修改消息状态为通过 @RequestMapping(value = "/status/pass",method = RequestMethod.POST) - public Msg pass(@RequestBody 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("缺少参数"); @@ -117,9 +123,9 @@ public class AdminController { // 管理员修改消息状态为未通过 @RequestMapping(value = "/status/unpass",method = RequestMethod.POST) - public Msg unpass(@RequestBody 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("缺少参数"); diff --git a/src/main/java/com/javaee/newssystem/controller/CommentController.java b/src/main/java/com/javaee/newssystem/controller/CommentController.java index 3c34119..d22c3d8 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.*; @@ -28,7 +30,7 @@ public class CommentController { @PostMapping("/first") 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; @@ -42,7 +44,7 @@ public class CommentController { @PostMapping("/second") 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(@RequestBody Long userId,@RequestBody 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(@RequestBody Long userId,@RequestBody 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(@RequestBody 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 index 3f026b2..fabebdd 100644 --- a/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java +++ b/src/main/java/com/javaee/newssystem/controller/ExceptionControllerAdvice.java @@ -32,10 +32,12 @@ public class ExceptionControllerAdvice { 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("参数校验错误",400).add("data",errorMap); + return Msg.fail(String.join(";",errorList),400); } diff --git a/src/main/java/com/javaee/newssystem/controller/NewsController.java b/src/main/java/com/javaee/newssystem/controller/NewsController.java index 9113e2a..7c85b7f 100644 --- a/src/main/java/com/javaee/newssystem/controller/NewsController.java +++ b/src/main/java/com/javaee/newssystem/controller/NewsController.java @@ -110,9 +110,9 @@ public class NewsController { //删除新闻内容 @PostMapping("/delete") - public Msg deleteTeam(@RequestBody Long newsId){ - if(newsId!=null){ - Boolean b = newsService.deleteNews(newsId); + 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("缺少参数"); @@ -133,7 +133,7 @@ public class NewsController { 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 b?Msg.success("关注成功"):Msg.fail("已关注,无需再次关注"); } return Msg.fail("缺少参数"); } @@ -143,7 +143,7 @@ public class NewsController { 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 b?Msg.success("取消关注成功"):Msg.fail("已经取消关注,无法取消"); } return Msg.fail("缺少参数"); } @@ -164,4 +164,14 @@ public class NewsController { 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/TeamController.java b/src/main/java/com/javaee/newssystem/controller/TeamController.java index 96f906d..aa16491 100644 --- a/src/main/java/com/javaee/newssystem/controller/TeamController.java +++ b/src/main/java/com/javaee/newssystem/controller/TeamController.java @@ -6,6 +6,7 @@ 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.*; @@ -30,9 +31,9 @@ public class TeamController { // 创建团队 @PostMapping("/create") - public Msg createTeam(@RequestBody @Valid 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); @@ -59,9 +60,9 @@ public class TeamController { // 更新团队信息 @PostMapping("/update/info") - public Msg updateInfo(@RequestBody @Valid Team team, @RequestPart(value = "headImg",required = false) 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; @@ -71,9 +72,9 @@ public class TeamController { // 解散团队 @PostMapping("/delete") - public Msg deleteTeam(@RequestBody 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("缺少参数"); @@ -81,9 +82,9 @@ public class TeamController { // 置顶消息 @PostMapping("/first") - public Msg firstNews(@RequestBody Long teamId,@RequestBody 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); @@ -95,9 +96,9 @@ public class TeamController { // 邀请用户 @PostMapping("/invite") - public Msg inviteUser(@RequestBody Long teamId,@RequestBody 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("邀请成功"); } @@ -109,9 +110,9 @@ public class TeamController { // 踢出用户 @PostMapping("/deleteMember") - public Msg deleteUser(@RequestBody Long teamId,@RequestBody 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("踢出成功"); } @@ -123,9 +124,9 @@ public class TeamController { // 转换管理权 @PostMapping("/change/leader") - public Msg changeLeader(@RequestBody Long teamId,@RequestBody 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("缺少参数"); @@ -149,9 +150,9 @@ public class TeamController { // 成员退出团队 @PostMapping("/member/delete") - public Msg memberDelete(@RequestBody Long userId,@RequestBody 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 0000000..a374db1 --- /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 b97cf82..de3ffad 100644 --- a/src/main/java/com/javaee/newssystem/controller/UserController.java +++ b/src/main/java/com/javaee/newssystem/controller/UserController.java @@ -7,8 +7,10 @@ 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.*; @@ -44,11 +46,11 @@ public class UserController { else { Long userId = userService.Login(userName, userPassword); if (userId!=null){ - User userInfo = userService.getUserInfo(userId); - if(userInfo!=null){ - Msg msg = Msg.success("登录成功").add("data",userInfo); + UserRespVo vo = userService.getUserInfo(userId); + if(vo!=null){ + Msg msg = Msg.success("登录成功").add("data",vo); // 生成token - msg.add("token", JwtUtil.getToken(userInfo.getUserId(),"用户")); + msg.add("token", JwtUtil.getToken(vo.getUserId(),"用户")); return msg; } return Msg.fail("登录成功,但服务器内部出现错误"); @@ -63,18 +65,18 @@ public class UserController { public Msg Register(@RequestBody @Valid User user){ if (CheckClassUtil.checkUser(user)){ Boolean b = userService.Register(user); - return b?Msg.success("注册成功"):Msg.fail("用户名已存在"); + return b?Msg.success("注册成功"):Msg.fail("用户已存在"); } return Msg.fail("注册失败,缺少参数"); } // 用户修改信息 @RequestMapping(value = "/update/info",method = RequestMethod.POST) - public Msg updateInfo(@RequestBody @Valid User user, @RequestPart(value = "headImg",required = false) MultipartFile headImg){ + public Msg updateInfo(@RequestBody @Valid User user){ if(user.getUserId()!=null){ - user = userService.updateInfo(user, headImg); - if(user!=null){ - return Msg.success("修改成功").add("data",user); + UserRespVo vo = userService.updateInfo(user); + if(vo!=null){ + return Msg.success("修改成功").add("data",vo); } else return Msg.fail("修改失败"); @@ -88,9 +90,9 @@ public class UserController { Map map = JwtUtil.parse(token); if((Boolean) map.get("status")){ Long id = (Long) map.get("id"); - User user = userService.getUserInfo(id); - if(user!=null){ - return Msg.success("获取成功").add("data",user); + UserRespVo vo = userService.getUserInfo(id); + if(vo!=null){ + return Msg.success("获取成功").add("data",vo); } else { return Msg.fail("不存在此用户"); @@ -114,9 +116,9 @@ public class UserController { // 用户注销账号 @RequestMapping(value = "logout",method = RequestMethod.POST) - public Msg Logout(@RequestBody Long userId){ - if(userId!=null){ - Boolean b = userService.Logout(userId); + 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("缺少参数"); @@ -126,7 +128,7 @@ 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); + Page page = userService.getFocusUser(userId, current, size); return Msg.success("查询成功").add("data",page); } return Msg.fail("缺少参数"); @@ -139,7 +141,7 @@ public class UserController { Long focusedUserId = userVo.getFocusedUserId(); if(userId!=null&&focusedUserId!=null){ Boolean b = userService.addFocusUser(userId, focusedUserId); - return b?Msg.success("取消关注成功"):Msg.fail("该用户未被关注"); + return b?Msg.success("取消关注成功"):Msg.fail("该用户已被关注"); } return Msg.fail("缺少参数"); } @@ -160,9 +162,9 @@ 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()){ - return Msg.success("查找成功").add("data",userList); + List voList = userService.search(userName); + if (!voList.isEmpty()){ + return Msg.success("查找成功").add("data",voList); } else return Msg.fail("查无此人"); } diff --git a/src/main/java/com/javaee/newssystem/entity/News.java b/src/main/java/com/javaee/newssystem/entity/News.java index 5278b56..f586274 100644 --- a/src/main/java/com/javaee/newssystem/entity/News.java +++ b/src/main/java/com/javaee/newssystem/entity/News.java @@ -45,7 +45,6 @@ public class News implements Serializable { /** * 新闻内容 */ - @Pattern(regexp = "^.{10,}$",message = "内容长度必须在10以上") private String content; /** diff --git a/src/main/java/com/javaee/newssystem/entity/User.java b/src/main/java/com/javaee/newssystem/entity/User.java index 3d78ded..6ba96c2 100644 --- a/src/main/java/com/javaee/newssystem/entity/User.java +++ b/src/main/java/com/javaee/newssystem/entity/User.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.NotNull; import javax.validation.constraints.Pattern; import java.io.Serializable; import java.util.Date; @@ -41,7 +42,7 @@ public class User implements Serializable { /** * 手机号 */ - @Pattern(regexp = "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$",message = "手机号格式不对") + @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; /** diff --git a/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java b/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java index 74863a5..adad32c 100644 --- a/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java +++ b/src/main/java/com/javaee/newssystem/mapper/CommentMapper.java @@ -19,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 0000000..eb2949d --- /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 922c47a..2811c0e 100644 --- a/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java +++ b/src/main/java/com/javaee/newssystem/mapper/NewsMapper.java @@ -23,4 +23,7 @@ public interface NewsMapper extends BaseMapper { 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 61df026..4a6df55 100644 --- a/src/main/java/com/javaee/newssystem/mapper/UserMapper.java +++ b/src/main/java/com/javaee/newssystem/mapper/UserMapper.java @@ -23,9 +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 ebd640e..0000000 --- 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 36426d5..371f43a 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 975e2e3..6294062 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 0b55bac..1f037e4 100644 --- a/src/main/java/com/javaee/newssystem/service/INewsService.java +++ b/src/main/java/com/javaee/newssystem/service/INewsService.java @@ -58,5 +58,7 @@ public interface INewsService extends IService { 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 bb2d032..15da038 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 0000000..4049d08 --- /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 07f2a2a..3d15548 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; @@ -21,25 +22,25 @@ public interface IUserService extends IService { 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(Long userId); + UserRespVo getUserInfo(Long userId); } diff --git a/src/main/java/com/javaee/newssystem/service/ScheduledService.java b/src/main/java/com/javaee/newssystem/service/ScheduledService.java index 7796f7d..df9e8a4 100644 --- a/src/main/java/com/javaee/newssystem/service/ScheduledService.java +++ b/src/main/java/com/javaee/newssystem/service/ScheduledService.java @@ -42,12 +42,12 @@ public class ScheduledService { double score = 1; while (iterator.hasNext()){ flag++; - if(flag>=201){ - ZSetOperations.TypedTuple typedTuple = iterator.next(); - score = Math.ceil(typedTuple.getScore()); - break; - } + ZSetOperations.TypedTuple typedTuple = iterator.next(); + score = Math.ceil(typedTuple.getScore()); + if(flag>=200) + break; } + if (flag>=201) redisTemplate.opsForZSet().removeRangeByScore("newsHotKey",1,score); } 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 f6344c1..1d435d7 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 2b4765f..a05d842 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 fec51dd..5c75b86 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/NewsServiceImpl.java @@ -235,22 +235,40 @@ public class NewsServiceImpl extends ServiceImpl implements IN 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; 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 b54f375..0c22289 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/TeamServiceImpl.java @@ -37,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; } @@ -74,16 +59,15 @@ public class TeamServiceImpl extends ServiceImpl implements IT @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!=null&&!headImg.isEmpty()){ + if(team.getTeamIcon()!=null){ // 获取旧的头像路径 if (oldTeam.getTeamIcon()!=null){ String oldHeadImgPath =uploadPath+oldTeam.getTeamIcon(); @@ -91,23 +75,6 @@ public class TeamServiceImpl extends ServiceImpl implements IT File file = new File(oldHeadImgPath); FileSystemUtils.deleteRecursively(file); } - try { -// 生成新的头像路径 - Map map = MyUtil.getPath(headImg); -// 更新新头像资源并更新数据库 - File folder = new File(uploadPath); - if(!folder.isDirectory()){ - folder.mkdirs(); - } - headImg.transferTo(new File(folder,map.get("filename"))); - team.setTeamIcon(map.get("filename")); - teamMapper.updateById(team); - team = teamMapper.selectById(team); - return team; - } catch (IOException e) { - e.printStackTrace(); - return null; - } } // 头像不用更新,直接更新数据库 teamMapper.updateById(team); 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 0000000..e189e25 --- /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 b278c0b..cbbcd6a 100644 --- a/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java +++ b/src/main/java/com/javaee/newssystem/service/impl/UserServiceImpl.java @@ -11,6 +11,8 @@ 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; @@ -32,6 +34,7 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** @@ -95,11 +98,11 @@ public class UserServiceImpl extends ServiceImpl implements IU @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!=null&&!headImg.isEmpty()){ + if(oldUser!=null&&user.getUserIcon()!=null){ // 获取旧的头像路径 if(oldUser.getUserIcon()!=null){ String oldHeadImgPath = uploadPath+oldUser.getUserIcon(); @@ -107,31 +110,14 @@ public class UserServiceImpl extends ServiceImpl implements IU File file = new File(oldHeadImgPath); FileSystemUtils.deleteRecursively(file); } - try { -// 生成新的头像路径 - Map map = MyUtil.getPath(headImg); -// 更新新头像资源并更新数据库 - File folder = new File(uploadPath); - if(!folder.isDirectory()){ - folder.mkdirs(); - } - headImg.transferTo(new File(folder,map.get("filename"))); - user.setUserIcon(map.get("filename")); - userMapper.updateById(user); - user = userMapper.selectById(user); - user.setUserPassword(null); - return user; - } catch (IOException e) { - e.printStackTrace(); - return null; - } } // 头像不用更新,直接更新数据库 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") @@ -151,7 +137,7 @@ public class UserServiceImpl extends ServiceImpl implements IU @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"); @@ -159,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 @@ -194,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 @@ -224,9 +237,10 @@ public class UserServiceImpl extends ServiceImpl implements IU @Cacheable(key = "#userId") @Override - public User getUserInfo(Long userId) { + public UserRespVo getUserInfo(Long userId) { User user = userMapper.selectById(userId); - user.setUserPassword(null); - return user; + 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 95bad3d..95449c7 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/vo/AdminVo.java b/src/main/java/com/javaee/newssystem/vo/AdminVo.java new file mode 100644 index 0000000..91374c5 --- /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 0000000..9b22094 --- /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 0000000..1107af0 --- /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 index 89d8d93..eee3398 100644 --- a/src/main/java/com/javaee/newssystem/vo/NewsVo.java +++ b/src/main/java/com/javaee/newssystem/vo/NewsVo.java @@ -63,4 +63,9 @@ public class NewsVo { * 请求者是否关注了此消息 */ private Boolean isFocus; + + /** + * 请求者是否关注了作者 + */ + private Boolean isFocusAuthor; } 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 0000000..9d37321 --- /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 0000000..281d603 --- /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/resources/application.yml b/src/main/resources/application.yml index ecf639d..3ad78e5 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -2,13 +2,13 @@ web: # upload-path: /usr/local/project/HeadImg upload-path: D:/HeadImg/ spring: -# datasource: -# url: jdbc:mysql://127.0.0.1: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 + datasource: + 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: @@ -32,6 +32,4 @@ spring: 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 + 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 0245b68..f43172b 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 30c413a..527d7cd 100644 --- a/src/main/resources/mapper/NewsMapper.xml +++ b/src/main/resources/mapper/NewsMapper.xml @@ -14,5 +14,8 @@ + diff --git a/src/main/resources/mapper/UserMapper.xml b/src/main/resources/mapper/UserMapper.xml index a43f10b..8989ea9 100644 --- a/src/main/resources/mapper/UserMapper.xml +++ b/src/main/resources/mapper/UserMapper.xml @@ -7,7 +7,7 @@ UPDATE user SET status=0 WHERE user_id=#{userId} - + DELETE FROM focus_user WHERE user_id=#{userId} AND focused_user_id=#{focusedUserId} @@ -18,4 +18,7 @@ + -- Gitee