本次项目功能实现基于上一篇博客。
由于新闻标签和新闻分类类似,这里只选取type部分进行介绍。controller层TypeController,首先是删除功能,先接收url中的id,再调用service层的deleteById,然后回到标签界面;接着是新增和修改功能,对于新增url会传来一个id其值为-1,对于修改url会传来一个id其值为前端页面的id值(在生成表时,id已存入值),所以当id不为-1时,通过调用service层的findById方法根据id获取一个type对象,当id等于-1时,则产生一个type对象,并将其添加到model属性中,然后跳转到types-input页面,在types-input页面,用户可以输入type的名字,当发出input请求时,会调用service层的input方法,将type数据存入到数据库中。
@RequestMapping("delete/{id}")
public String delete(@PathVariable Long id){
typeService.deleteById(id);
return "redirect:/admin/types";
}
@RequestMapping("input/{id}")
public String toInput(@PathVariable Long id,Model model){
Type type = null;
if(id!=-1){
type = typeService.findById(id);
}else{
type = new Type();
}
model.addAttribute("type",type);
return "admin/types-input";
}
@RequestMapping("input")
public String input(Type type){
typeService.input(type);
return "redirect:/admin/types";
}
而service层,又是调用dao层接口的方法,dao层的接口通过继承JpaRepository接口,可以实现一些简单的sql查询,getOne,deleteById,save都是JpaRepository已经定义好的。
package com.zr.service.impl;
import com.zr.dao.TypeDao;
import com.zr.po.Type;
import com.zr.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
public class TypeServiceImpl implements TypeService {
@Autowired
private TypeDao typeDao;
@Override
public Page<Type> listType(Pageable pageable) {
return typeDao.findAll(pageable);
}
@Override
public Type findById(Long id) {
return typeDao.getOne(id);
}
@Override
public void deleteById(Long id) {
typeDao.deleteById(id);
}
@Override
public void input(Type type) {
typeDao.save(type);
}
}
dao层的typeDao接口如下。
package com.zr.dao;
import com.zr.po.Type;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TypeDao extends JpaRepository<Type,Long> {
}
页面新增url
页面修改及删除url
通过post请求修改或新增type
代码已上传GitHub