天天看點

【學習日記】(SpringBoot-part 4)新聞管理系統—添加和修改新聞功能效果展示實作過程

新聞管理系統的新聞添加和修改功能

  • 效果展示
  • 實作過程

添加新聞功能和修改功能的實作機制是差不多的,是以放到一起實作

效果展示

【學習日記】(SpringBoot-part 4)新聞管理系統—添加和修改新聞功能效果展示實作過程
【學習日記】(SpringBoot-part 4)新聞管理系統—添加和修改新聞功能效果展示實作過程
【學習日記】(SpringBoot-part 4)新聞管理系統—添加和修改新聞功能效果展示實作過程
【學習日記】(SpringBoot-part 4)新聞管理系統—添加和修改新聞功能效果展示實作過程

實作過程

  1. 添加實體類且聲明與其他實體關系

    在po檔案下添加News實體資訊如下,并在實體資訊中聲明和其他實體的關系

    實體關系:

    News to Type : n:1

    News to User : n:1

    News to Tags : n:n 因為News和Tags的實體關系為多對多,是以需要指定級聯,生成一個News-Tag關系表

@Entity
@Table(name = "t_news")
public class News {

    @Id //主鍵辨別
    @GeneratedValue(strategy = GenerationType.IDENTITY)  //自增
    private Long id;
    private String title;

    @Basic(fetch = FetchType.LAZY)        //懶加載  需要用到的時候再加載
    @Lob          //存儲量較大的内容用到@lob
    private String content;
    private  String firstPicture;
    private String flag;
    private String views;
    private boolean appreciation;
    private boolean shareStatement;
    private boolean commentabled;
    private boolean published;
    private boolean recommend;
    @Temporal(TemporalType.TIMESTAMP) //指定時間戳
    private Date createTime;
    @Temporal(TemporalType.TIMESTAMP) //指定時間戳
    private Date updateTime;

    @ManyToOne
    private Type type;
    @ManyToOne
    private User user;
    //還要加标簽tag
    @ManyToMany(cascade = CascadeType.PERSIST)   //指定級聯
    private List<Tag> tags = new ArrayList<>();

    @Transient  //表示不會在資料庫中生成這個字段  隻存在于本實體中
    private String tagIds;

    private String description;
    public News() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }



    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFirstPicture() {
        return firstPicture;
    }

    public void setFirstPicture(String firstPicture) {
        this.firstPicture = firstPicture;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public String getViews() {
        return views;
    }

    public void setViews(String views) {
        this.views = views;
    }

    public boolean isAppreciation() {
        return appreciation;
    }

    public void setAppreciation(boolean appreciation) {
        this.appreciation = appreciation;
    }

    public boolean isShareStatement() {
        return shareStatement;
    }

    public void setShareStatement(boolean shareStatement) {
        this.shareStatement = shareStatement;
    }

    public boolean isCommentabled() {
        return commentabled;
    }

    public void setCommentabled(boolean commentabled) {
        this.commentabled = commentabled;
    }

    public boolean isPublished() {
        return published;
    }

    public void setPublished(boolean published) {
        this.published = published;
    }

    public boolean isRecommend() {
        return recommend;
    }

    public void setRecommend(boolean recommend) {
        this.recommend = recommend;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }

    public String getTagIds() {
        return tagIds;
    }

    public void setTagIds(String tagIds) {
        this.tagIds = tagIds;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    //對一對多的标簽進行處理  如一個新聞有id為12345的tag  初始化為 1,2,3,4,5
    public void init(){
        this.tagIds = tagsToIds(this.getTags());
    }

    private String tagsToIds(List<Tag> tags){
        if(!tags.isEmpty()){
            StringBuffer ids = new StringBuffer();
            boolean flag = false;
            for(Tag tag:tags){
                if(flag){
                    ids.append(",");
                }else{
                    flag = true;
                }
                ids.append(tag.getId());
            }
            return ids.toString();
        }else{
            return tagIds;
        }
    }


    @Override
    public String toString() {
        return "News{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", firstPicture='" + firstPicture + '\'' +
                ", flag='" + flag + '\'' +
                ", views='" + views + '\'' +
                ", appreciation=" + appreciation +
                ", shareStatement=" + shareStatement +
                ", commentabled=" + commentabled +
                ", published=" + published +
                ", recommend=" + recommend +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", type=" + type +
                ", user=" + user +
                ", tags=" + tags +
                ", tagIds='" + tagIds + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}
           
  1. 建立vo檔案

    建立一個vo檔案夾,建立一個NewQuery類,該目錄和平常用的Util類似,是用來存放工具類的,在這裡我們聲明的NewQuery類,用來對接下來的新聞查詢功能,進行一個預處理,檔案目錄如下

    【學習日記】(SpringBoot-part 4)新聞管理系統—添加和修改新聞功能效果展示實作過程
//對查詢條件進行預處理
public class NewQuery {

    private String title;
    private Long typeId;
    private boolean recommend;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Long getTypeId() {
        return typeId;
    }

    public void setTypeId(Long typeId) {
        this.typeId = typeId;
    }

    public boolean isRecommend() {
        return recommend;
    }

    public void setRecommend(boolean recommend) {
        this.recommend = recommend;
    }

    @Override
    public String toString() {
        return "NewQuery{" +
                "title='" + title + '\'' +
                ", typeId=" + typeId +
                ", recommend=" + recommend +
                '}';
    }
}
           
  1. 聲明一個dao接口

    在dao目錄下建立一個NewRepository,隻需要聲明繼承Jpa,使用jpa中的方法

public interface NewRepository extends JpaRepository<News,Long> , JpaSpecificationExecutor<News> {   
}
           
  1. Service添加接口方法和實作方法

    建立一個NewService接口

public interface NewService {

    Page<News> listNew(Pageable pageable, NewQuery newQuery);

    //新增
    News saveNew(News news);
    //更新
    News getNew(Long id);
    News updateNew(Long id,News news);
}
           

在Impl中建立一個方法實作NewService接口中的方法

由于查詢資料一共可以結合三種方式進行查詢,是以在listNew方法中結合之前的NewQuery實作查詢資料的預處理,以及将資料結果顯示

@Service
public class NewServiceImpl implements NewService {

    @Autowired
    private NewRepository newRepository;

    //新聞管理中的新聞清單(包含查詢)
    @Override
    public Page<News> listNew(Pageable pageable, NewQuery newQuery) {
        return newRepository.findAll(new Specification<News>() {    //查詢構造器
            @Override       //criteriaQuery查詢條件的容器  criteriaBuilder表達式
            public Predicate toPredicate(Root<News> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(!"".equals(newQuery.getTitle()) && newQuery.getTitle()!=null) {   //标題不為空
                    predicates.add(cb.like(root.<String>get("title"), "%"+newQuery.getTitle()+"%"));
                }
                if(newQuery.getTypeId()!=null){   //根據分類查
                    predicates.add(cb.equal(root.get("type").get("id"),newQuery.getTypeId()));
                }
                if(newQuery.isRecommend()){ //根據是否被推薦查詢
                   predicates.add(cb.equal(root.get("recommend"),newQuery.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    @Override
    public News saveNew(News news) {
        if(news.getId()==null){  //為空 則為新增
            news.setCreateTime(new Date());
            news.setUpdateTime(new Date());
        }
        return newRepository.save(news);
    }

    @Override
    public News getNew(Long id) {
        return newRepository.findById(id).orElse(null);
    }

    @Override
    public News updateNew(Long id, News news) {
        News news1 = newRepository.findById(id).orElse(null);
        if(news1==null){
            System.out.println("未擷取更新對象");
        }

        BeanUtils.copyProperties(news,news1);
        news1.setUpdateTime(new Date());

        return newRepository.save(news1);
    }
}
           
  1. 修改控制器
@Controller
@RequestMapping("/admin")
public class NewController {

    private static final String INPUT = "admin/news-input";
    private static final String LIST = "admin/news";
    private static final String REDIRECT_LIST = "redirect:/admin/news";  //重定向

    @Autowired
    private NewService newService;

    @Autowired
    private TagService tagService;

    @Autowired
    private TypeService typeService;

    @GetMapping("/news")
    public String news(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                       Pageable pageable, NewQuery newQuery, Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("page",newService.listNew(pageable,newQuery));
        return LIST;
    }

    @PostMapping("/news/search")
    public String search(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                               Pageable pageable, NewQuery newQuery, Model model){

        model.addAttribute("page",newService.listNew(pageable,newQuery));
        System.out.println(model);
        return "admin/news :: newsList";
    }

    //用來在修改和新增news頁面顯示所有type和tag的
    public void setTypeAndTag(Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagService.listTag());
    }

    @GetMapping("/news/input")
    public String input(Model model){
        setTypeAndTag(model);
        System.out.println("運作到這裡了嗎?"+model);
        model.addAttribute("news",new News());
        return INPUT;
    }

    @GetMapping("/news/{id}/toUpdate")
    public String toUpdate(@PathVariable Long id, Model model){
        setTypeAndTag(model);
        News news = newService.getNew(id);
        news.init();
        model.addAttribute("news",news);
        return INPUT;
    }

    //跳轉頁面
    @PostMapping("/news/add")
    public String post(News news, RedirectAttributes attributes, HttpSession session){
        System.out.println("controller接收的news為:"+ news);
        news.setUser((User) session.getAttribute("user"));
        news.setType(typeService.getType(news.getType().getId()));
        news.setTags(tagService.listTag(news.getTagIds()));
        News news1;
        if(news.getId()==null){
            news1 = newService.saveNew(news);
        }else{
            news1 = newService.updateNew(news.getId(),news);
        }
        if(news1 == null){
            attributes.addFlashAttribute("message","操作失敗");
        }else {
            attributes.addFlashAttribute("message","操作成功");
        }

        return REDIRECT_LIST;

    }
}
           
  • news方法:
@GetMapping("/news")
public String news(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                   Pageable pageable, NewQuery newQuery, Model model){
    model.addAttribute("types",typeService.listType());
    model.addAttribute("page",newService.listNew(pageable,newQuery));
    return LIST;
}
           

用來在新聞界面将資料庫中所有資訊展示出,按更新時間進行排序,這裡新在typeService中聲明一個接口listType

//不分頁的List  在查找新聞界面顯示出
List<Type> listType();
           
@Override
public List<Type> listType() {
    return typeRepository.findAll();
}
           
  • search方法
@PostMapping("/news/search")
public String search(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
                            Pageable pageable, NewQuery newQuery, Model model){
     model.addAttribute("page",newService.listNew(pageable,newQuery));
     System.out.println(model);
     return "admin/news :: newsList";
 }
           

同樣按照更新時間進行排序,這裡使用之前Impl中實作的查詢方法

  • add方法
//用來在修改和新增news頁面顯示所有type和tag的
public void setTypeAndTag(Model model){
    model.addAttribute("types",typeService.listType());
    model.addAttribute("tags",tagService.listTag());
}

@GetMapping("/news/input")
public String input(Model model){
    setTypeAndTag(model);
    model.addAttribute("news",new News());
    return INPUT;
}
           

input.html中添加指向add路由

//跳轉頁面
@PostMapping("/news/add")
public String post(News news, RedirectAttributes attributes, HttpSession session){
    System.out.println("controller接收的news為:"+ news);
    news.setUser((User) session.getAttribute("user"));
    news.setType(typeService.getType(news.getType().getId()));
    news.setTags(tagService.listTag(news.getTagIds()));
    News news1;
    if(news.getId()==null){
        news1 = newService.saveNew(news);
    }else{
        news1 = newService.updateNew(news.getId(),news);
    }
    if(news1 == null){
        attributes.addFlashAttribute("message","操作失敗");
    }else {
        attributes.addFlashAttribute("message","操作成功");
    }
    return REDIRECT_LIST;
}
           

在建立時涉及到選擇已存在的tag和type,是以需要再去TagService中建立一個查詢所有tag資訊的接口并實作

//列所有标簽
List<Tag> listTag();
           
@Override
public List<Tag> listTag() {
    return tagRepository.findAll();
}
           
  • update方法
@GetMapping("/news/{id}/toUpdate")
public String toUpdate(@PathVariable Long id, Model model){
    setTypeAndTag(model);
    News news = newService.getNew(id);
    news.init();
    model.addAttribute("news",news);
    return INPUT;
}
           

更新和建立類似,需要判斷是否存在id,不存在即建立,存在即更新,需要在News實體類中進行一個初始化和判斷處理

//對一對多的标簽進行處理  如一個新聞有id為12345的tag  初始化為 1,2,3,4,5
public void init(){
    this.tagIds = tagsToIds(this.getTags());
}

private String tagsToIds(List<Tag> tags){
    if(!tags.isEmpty()){
        StringBuffer ids = new StringBuffer();
        boolean flag = false;
        for(Tag tag:tags){
            if(flag){
                ids.append(",");
            }else{
                flag = true;
            }
            ids.append(tag.getId());
        }
        return ids.toString();
    }else{
        return tagIds;
    }
}