Java开发学习.Day9
基于Springboot实现 添加和修改新闻功能
本文内容是基于Java开发学习.Day8内容上所实现的
由于添加新闻功能和修改新闻功能类似,仅在于是否在数据库具有id存在差异,因此可将两种功能一同实现
代码实现
整体文件路径
具体实现
在dao层中添加NewRepository接口
public interface NewRepository extends JpaRepository<News, Long>, JpaSpecificationExecutor<News> {
}
在po中添加News类
@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<Tag>();
@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;
}
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 + '\'' +
'}';
}
}
在vo中创建NewQuery类,对查询条件进行预处理
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 +
'}';
}
}
由于在创建和修改新闻时,需要选择Type和Tag,因此需要提前获取所有的Type和Tag。
分别在typeService和TagService接口中添加方法
在typeServiceImpl和tagServiceImpl中实现
TagService:
public interface TagService {
//查询
Page<Tag> listTag(Pageable pageable);
//新增
Tag saveTag(Tag tag);
Tag getTagByName(String name);
//删除
void deleteTag(Long id);
//编辑
Tag getTag(Long id);
Tag update(Long id, Tag tag);
List<Tag> listTag();
List<Tag> listTag(String ids);
}
TagServiceImpl
@Service
public class TagServiceImpl implements TagService {
@Autowired
private TagRepository tagRepository;
@Override
public Page<Tag> listTag(Pageable pageable) {
return tagRepository.findAll(pageable);
}
@Override
public Tag saveTag(Tag tag) {
return tagRepository.save(tag);
}
@Override
public Tag getTagByName(String name) {
return tagRepository.findByName(name);
}
@Override
public void deleteTag(Long id) {
tagRepository.deleteById(id);
}
@Override
public Tag getTag(Long id) {
return tagRepository.findById(id).orElse(null);
}
@Override
public Tag update(Long id, Tag tag) {
Tag tag1 = tagRepository.findById(id).orElse(null);
if(tag1==null){
System.out.println("获取更新对象出错");
return null;
}
BeanUtils.copyProperties(tag,tag1);
return tagRepository.save(tag1);
}
@Override
public List<Tag> listTag() {
return tagRepository.findAll();
}
@Override
public List<Tag> listTag(String ids) {
return tagRepository.findAllById(converToList(ids));
}
private List<Long> converToList(String ids){
List<Long> list =new ArrayList<>();
if(!"".equals(ids) && ids!=null){
String[] idArray=ids.split(",");
for(int i=0;i<idArray.length;i++){
list.add(new Long(idArray[i]));
}
}
System.out.println("ids:"+list);
return list;
}
}
TypeService
public interface TypeService {
Page<Type> listType(Pageable pageable);
Type getTypeByName(String name);
Type saveType(Type type);
void delete(Long id);
//编辑
Type getType(Long id);
Type updateType(Long id, Type type);
List<Type> listType();
}
TypeServiceImpl
@Service
public class TypeServiceImpl implements TypeService {
@Autowired
private TypeRepository typeRepository;
@Override
public Page<Type> listType(Pageable pageable) {
return typeRepository.findAll(pageable); //findAll方法来自jpa
}
@Override
public Type getTypeByName(String name) {
return typeRepository.findByName(name);
}
@Override
public Type saveType(Type type) {
return typeRepository.save(type);
}
@Override
public void delete(Long id) {
typeRepository.deleteById(id);
}
@Override
public Type getType(Long id) {
return typeRepository.findById(id).orElse(null);
}
@Override
public Type updateType(Long id, Type type) {
Type type1 = typeRepository.findById(id).orElse(null);
if(type1==null){
System.out.println("未获得更新对象");
return null;
}
BeanUtils.copyProperties(type,type1);
return typeRepository.save(type1);
}
@Override
public List<Type> listType() {
return typeRepository.findAll();
}
}
最后在web中添加newController,这也是功能的核心部分
setTypeAndTag用于初始化type和tag对象
input用于创建News对象,供用户新增新闻
toUpdate和post方法则用于更新和新增新闻,若已有id则为更新新闻,否则新增新闻。
@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="redirect:/admin/news";
@Autowired
private NewService newService;
@Autowired
private TypeService typeService;
@Autowired
private TagService tagService;
@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));
return "admin/news :: newsList";
}
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;
}
@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){
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;
}
}
功能展示
修改界面
新增界面