中软国际暑期实习day11(2020.08.20)-Spring Boot项目实战(新闻项目-新闻管理)

今天在昨天的基础上实现新闻管理功能。

文章目录

1.新闻管理

新闻管理也主要是对新闻的一些基础操作,如查询所有等等。其核心代码如下所示

// 分页全查
    @GetMapping("/news")
    public String news(@PageableDefault(size = 3) Pageable pageable, Model model) {
        // 不仅需要查询当前页的数据  还需要查询全部的类别
        model.addAttribute("types", typeService.listType());
        model.addAttribute("page", newsService.listNews(pageable));
        return "admin/news";
    }

    // 新增的前置操作
    @GetMapping("/news/input")
    public String toAdd(Model model) {
        // 需要传递空对象  所有类别  所有标签
        model.addAttribute("news", new News());
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTag());
        return "admin/news-input";
    }

    // 新增操作
    @PostMapping("/news/add")
    public String addOrUpdate(News news, HttpSession session, RedirectAttributes attributes) {
        // 得到用户对象 将用户对下个存储到News对象中
        news.setUser((User) session.getAttribute("user"));
        // 得到Type对象 , 将Type对象存储到News对象中,    因为前台传递的Type对象中只有一个id  所以需要通过id找到整个type对象  再进行存储
        news.setType(typeService.getTypeById(news.getType().getId()));
        // 得到tags对象
        news.setTags(tagService.listTag(news.getTagIds()));
        System.out.println(news);

        News n;
        // 判断当前是新增或是更新
        if (news.getId() == null) {
            n = newsService.save(news);
        } else {
            n = newsService.updateNews(news.getId(), news);
        }

        if (n == null) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return "redirect:/admin/news";

    }

2.总结

  • JPA自带分页全查

Page<T> findAll(Pageable pageable);

在使用时直接调用该函数即可,注意需传入pageable参数(指定分页每页的项数等等)。例如@PageableDefault(size = 3) Pageable pageable就指定每页有三项数据。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值