SpringBoot项目中实现信息类别的新增和更新
在前端通过传递不同id区分
<a href="#" th:href="@{/admin/tags/input/{id}(id=-1)}" class="ui mini right floated teal basic button">新增</a>
<a href="#" th:href="@{/admin/tags/input/{id}(id=${type.id})}" class="ui mini teal basic button">更新</a>
在后端通过Id判断
@GetMapping("input/{id}")
public String input(@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";
}
Controller层
@Controller
@RequestMapping("/admin/tags")
public class TagController {
@Autowired
private TagService tagService;
@RequestMapping
public String list(@PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable, Model model){
Page<Tag> page=tagService.listTag(pageable);
model.addAttribute("page",page);
return "admin/tags";
}
@GetMapping("{id}/delete")
public String delete(@PathVariable Long id){
tagService.delete(id);
return "redirect:/admin/tags";
}
@GetMapping("input/{id}")
public String toinput(@PathVariable Long id,Model model){
if(id==-1){
Tag tag=new Tag();
model.addAttribute("tag",tag);
}else{
Tag tag=tagService.findTagById(id);
model.addAttribute("tag",tag);
}
return "admin/tags-input";
}
@RequestMapping("input")
public String input(Tag tag){
tagService.input(tag);
return "redirect:/admin/tags";
}
}
Dao层
package com.zr.dao;
import com.zr.po.Type;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TypeDao extends JpaRepository<Type,Long> {
}
service层
@Service
public class TagServiceImpl implements TagService {
@Autowired
private TagDao tagDao;
public Page<Tag> listTag(Pageable pageable) {
return tagDao.findAll(pageable);
}
public void delete(Long id) {
tagDao.deleteById(id);
}
public Tag findTagById(Long id) {
return tagDao.getOne(id);
}
public void input(Tag tag) {
tagDao.save(tag);
}
public List<Tag> listTag() {
return tagDao.findAll();
}
public List<Tag> findTagByTagId(String tagIds) {
//1,2,3
List<Long> ids=new ArrayList<>();
if(!StringUtils.isEmpty(tagIds)){
String[]strings = tagIds.split(",");
for(String s:strings){
if(!StringUtils.isEmpty(s)){
ids.add(new Long(s));
}
}
}
return tagDao.findAllById(ids);
}
public String getTagIds(List<Tag> tags) {
//1,2,3==>1,2,3 是第一个就不需要添加逗号
StringBuffer ids=new StringBuffer();
if(!tags.isEmpty()){
boolean flag=false;
for(Tag t:tags){
if(flag){
ids.append(",");
ids.append(t.getId());
}else{
ids.append(t.getId());
flag=true;
}
}
}
return ids.toString();
}
}```java