❣博主主页: 33的博客❣
▶️文章专栏分类:项目日记◀️
🚚我的代码仓库: 33的代码仓库🚚
🫵🫵🫵关注我带你了解更多项目内容
1.前言
在上一篇文章中,我们已经完成了登录模块的后端逻辑,接下来就进入了博客页面,我们一起继续完成博客页面的相关逻辑吧
2.获取博客列表
BlogController类:
@RequestMapping("/getList")
public List<BlogList> getList(){
log.info("获取博客列表");
return blogService.getList();
}
BlogService类:
public List<BlogList> getList(){
return blogMapper.selectAll();
}
3.获取博客详情
BlogController类:
@RequestMapping("/getBlogDetail")
public BlogInfo getBlogDetail(Integer blogId){
log.info("getBlogDetail, blogId+{}",blogId);
BlogInfo blogInfo= blogService.getBlogDetail(blogId);
return blogInfo;
}
BlogService类:
public BlogInfo getBlogDetail(Integer blogId) {
return blogMapper.selectById(blogId);
}
4.新增博客
BlogController类:
@RequestMapping("/add")
public Boolean addBook(BlogInfo blogInfo,HttpServletRequest request){
log.info("添加图书,blogInfo.getTitle{}",blogInfo.getTitle());
log.info("添加图书,blogInfo.getContent{}",blogInfo.getContent());
if(!StringUtils.hasLength(blogInfo.getContent())||!StringUtils.hasLength(blogInfo.getTitle())){
return false;
}
String token=request.getHeader(Constants.REQUEST_HEADER_TOKEN);
Integer userId=JwyUtils.getIdByToken(token);
if(userId==null||userId<0){
return false;
}
blogInfo.setUserId(userId);
return blogService.insertBlog(blogInfo);
}
BlogService类:
public Boolean insertBlog(BlogInfo blogInfo) {
Integer i = blogMapper.insertBlog(blogInfo);
if(i>0){
return true;
}else {
return false;
}
}
5.更新博客
BlogController类:
@RequestMapping("/update")
public Boolean update(BlogInfo blogInfo){
log.info("更新博客");
if (blogInfo.getId()==null
|| !StringUtils.hasLength(blogInfo.getTitle())
|| !StringUtils.hasLength(blogInfo.getContent())){
return false;
}
blogService.update(blogInfo);
return true;
}
BlogService类:
public Integer update(BlogInfo blogInfo) {
return blogMapper.updateBlog(blogInfo);
}
6.删除博客
BlogController类:
@RequestMapping("/delete")
public Boolean delete(Integer blogId){
log.info("删除博客, blogId:{}", blogId);
if (blogId<=0){
return false;
}
BlogInfo blogInfo = new BlogInfo();
blogInfo.setId(blogId);
blogInfo.setDeleteFlag(1); //删除
blogService.update(blogInfo);
return true;
}
BlogService类:
public Integer update(BlogInfo blogInfo) {
return blogMapper.updateBlog(blogInfo);
}
7.拦截器
我们已经完成了博客页面的业务逻辑,但我们发现不管用户是否登录,我们前端直接请求后端的某一个逻辑如/blog/getBlogDetail,都可以获得对应的内容,显然这样是非常不合理的,我们希望只有用户登录,才能获得进行博客操作。因为之前,我们已经把用户的信息存入localStorage中,在后续请求中,并会携带这个信息。
@RequestMapping("/getBlogDetail")
public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request){
log.info("getBlogDetail, blogId+{}",blogId);
BlogInfo blogInfo= blogService.getBlogDetail(blogId);
String token=request.getHeader(Constants.REQUEST_HEADER_TOKEN);
Integer userId=JwyUtils.getIdByToken(token);
if(userId!=null&&userId==blogInfo.getUserId()){
blogInfo.setLoginUser(true);
}else {
blogInfo.setLoginUser(false);
}
return blogInfo;
}
那么我们可以在每一条后端逻辑中判断用户是否登录的操作,再进行后续操作,可是如果在每一段逻辑中都手动去添加,非常的繁琐。那有什么进行统一处理的操作吗?当然是有的,就是拦截器。
设置拦截器内容:
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token=request.getHeader(Constants.REQUEST_HEADER_TOKEN);
log.info("从header中获取token:{}", token);
Claims claims= JwyUtils.parseToken(token);
if(claims==null){
response.setStatus(401);
return false;
}
return true;
}
}
添加拦截器:
@Component
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
private final List excludes = Arrays.asList(
"/**/*.html",
"/blog-editormd/**",
"/css/**",
"/js/**",
"/pic/**",
"/user/login",
"/user/register"
);
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(excludes);
}
}
9.统一处理
9.1统一结果返回
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
@Autowired
private ObjectMapper objectMapper;
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@SneakyThrows
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof Result){
return body;
}
if (body instanceof String){
return objectMapper.writeValueAsString(Result.sucess(body));
}
return Result.sucess(body);
}
}
9.2统一异常处理
@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler
public Result handle(Exception e){
log.error("发生异常, e:", e);
return Result.fail("内部错误, 请联系管理员");
}
@ExceptionHandler
public Result handle(NoResourceFoundException e){
log.error("文件不存在:{}", e.getResourcePath());
return Result.fail("内部错误, 请联系管理员");
}
}
10.总结
我们已经完成了基本的业务逻辑,接下来,就只剩下前端模块,在下一篇文章中,我们再进行完善。
下期预告:博客前端模块