先写一个BookDao接口
package com.java1234.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.java1234.entity.Book;
/**
* 图书Dao接口
* @author user
*
*/
public interface BookDao extends JpaRepository<Book, Integer>{
}
再写一个BookController类
package com.java1234;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.java1234.dao.BookDao;
import com.java1234.entity.Book;
/**
* Book控制类
* @author user
*
*/
@Controller
@RequestMapping("/book")
public class BookController {
@Resource
private BookDao bookDao;
/**
* 查询所有图书
* @return
*/
@RequestMapping(value="/list")
public ModelAndView list(){
ModelAndView mav=new ModelAndView();
mav.addObject("bookList", bookDao.findAll());
mav.setViewName("bookList");
return mav;
}
/**
* 添加图书
* @param book
* @return
*/
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(Book book){
bookDao.save(book);
return "forward:/book/list";
}
@GetMapping(value="/preUpdate/{id}")
public ModelAndView preUpdate(@PathVariable("id") Integer id){
ModelAndView mav=new ModelAndView();
mav.addObject("book", bookDao.getOne(id));
mav.setViewName("bookUpdate");
return mav;
}
/**
* 修改图书
* @param book
* @return
*/
@PostMapping(value="/update")
public String update(Book book){
bookDao.save(book);
return "forward:/book/list";
}
/**
* 删除图书
* @param id
* @return
*/
@RequestMapping(value="/delete",method=RequestMethod.GET)
public String delete(Integer id){
bookDao.delete(id);
return "forward:/book/list";
}
}
用的是freemarker模板引擎,引入相关依赖。
bookList.ftl文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理页面</title>
</head>
<body>
<a href="/bookAdd.html">添加图书</a>
<table>
<tr>
<th>编号</th>
<th>图书名称</th>
<th>操作</th>
</tr>
<#list bookList as book>
<tr>
<td>${book.id}</td>
<td>${book.bookName}</td>
<td>
<a href="/book/preUpdate/${book.id}">修改</a>
<a href="/book/delete?id=${book.id}">删除</a>
</td>
</tr>
</#list>
</table>
</body>
</html>
bookAdd.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书添加页面</title>
</head>
<body>
<form action="book/add" method="post">
图书名称:<input type="text" name="bookName"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
bookUpdate.ftl文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书更新页面</title>
</head>
<body>
<form action="/book/update" method="post">
<input type="hidden" name="id" value="${book.id}"/>
图书名称:<input type="text" name="bookName" value="${book.bookName}"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>