一. Rest风格的API与传统API的区别
二. 添加依赖
本项目共需要以下依赖:
-
commons-logging-1.2.jar
-
druid-1.1.6.jar
-
fastjson-1.2.47.jar
-
jstl.jar
-
mysql-connector-java-5.1.47.jar
-
spring-aop-5.1.8.RELEASE.jar
-
spring-beans-5.1.8.RELEASE.jar
-
spring-context-5.1.8.RELEASE.jar
-
spring-core-5.1.8.RELEASE.jar
-
spring-expression-5.1.8.RELEASE.jar
-
spring-jdbc-5.1.8.RELEASE.jar
-
spring-tx-5.1.8.RELEASE.jar
-
spring-web-5.1.8.RELEASE.jar
-
spring-webmvc-5.1.8.RELEASE.jar
-
standard.jar
三. Entity
Book:
package io.zhangjia.springmvc.entity; public class Book { private Integer bookId; private String name; private String author; private Double price; @Override public String toString() { return "Book{" + "bookId=" + bookId + ", name='" + name + '\'' + ", author='" + author + '\'' + ", price=" + price + '}'; } public Integer getBookId() { return bookId; } public void setBookId(Integer bookId) { this.bookId = bookId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
四. BookDao
package io.zhangjia.springmvc.dao; import io.zhangjia.springmvc.entity.Book; import java.util.List; public interface BookDao { int doInsert(Book book); int doDelete(Integer bookId); int doUpdate(Book book); List<Book> queryAll(); Book queryById(Integer bookId); }}
BookDaoImpl:
这里不再使用xml文件配置,而是使用注解的方式
package io.zhangjia.springmvc.dao.impl; import io.zhangjia.springmvc.dao.BookDao; import io.zhangjia.springmvc.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository("bookDao") public class BookDaoImpl implements BookDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public int doInsert(Book book) { String sql = "INSERT INTO book (name, author, price) VALUES (?,?,?)"; return jdbcTemplate.update(sql,book.getName(),book.getAuthor(),book.getPrice()); } @Override public int doDelete(Integer bookId) { String sql = "DELETE FROM book WHERE book_id = ?"; return jdbcTemplate.update(sql,bookId); } @Override public int doUpdate(Book book) { String sql = "UPDATE book SET name = ?, author = ?, price = ? WHERE book_id = ?"; return jdbcTemplate.update(sql,book.getName(),book.getAuthor(),book.getPrice(),book.getBookId()); } @Override public List<Book> queryAll() { String sql = "SELECT * FROM book"; return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Book.class)); } @Override public Book queryById(Integer bookId) { String sql = "SELECT * FROM book WHERE book_id = ?"; return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(Book.class),bookId); } }
五. Service
BookService :
package io.zhangjia.springmvc.service; import io.zhangjia.springmvc.entity.Book; import java.util.List; public interface BookService { List<Book> books(); Book getBook(Integer bookId); boolean saveOrUpdate(Book book); boolean delete(Integer id); }
BookServiceImpl :
package io.zhangjia.springmvc.service.impl; import io.zhangjia.springmvc.dao.BookDao; import io.zhangjia.springmvc.entity.Book; import io.zhangjia.springmvc.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("bookService") public class BookServiceImpl implements BookService { @Autowired private BookDao bookDao; @Override public List<Book> books() { return bookDao.queryAll(); } @Override public Book getBook(Integer bookId) { return bookDao.queryById(bookId); } @Override public boolean saveOrUpdate(Book book) { int result = 0; if (book.getBookId() == null){ //添加 result = bookDao.doInsert(book); }else { //修改 result = bookDao.doUpdate(book); } return result == 1; } @Override public boolean delete(Integer id) { return bookDao.doDelete(id) == 1; } }
六. Controller
BookController :
package io.zhangjia.springmvc.; import com.alibaba.fastjson.JSON; import io.zhangjia.springmvc.entity.Book; import io.zhangjia.springmvc.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class BookController { @Autowired private BookService bookService; @GetMapping("/books") public String books(Model model){ List<Book> books = bookService.books(); System.out.println(JSON.toJSONString(books)); model.addAttribute("books",books); return "books"; } @GetMapping("/book") public String addForm(){ return "form"; } @GetMapping("/book/{id}") public String editForm(@PathVariable Integer id, Model model){ Book book = bookService.getBook(id); model.addAttribute("book",book); return "form"; } @PostMapping(value = "/book",produces = "application/json;charset=utf-8") @ResponseBody public String save(Book book){ boolean b = bookService.saveOrUpdate(book); return "{\"success\":"+b+"}"; } @PutMapping(value = "/book",produces = "application/json;charset=utf-8") @ResponseBody public String update(Book book){ System.out.println("put-book = " + book); boolean b = bookService.saveOrUpdate(book); return "{\"success\":"+b+"}"; } @DeleteMapping(value = "/book/{id}",produces = "application/json;charset=utf-8") @ResponseBody public String delete(@PathVariable Integer id){ boolean b = bookService.delete(id); return "{\"success\":"+b+"}"; } }
七. spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--配置扫描组件--> <!--在XML中配置了这个标签后,spring可以自动扫描base-package下面或者子包下面的java文件,如果扫描有@Component @Service @Controller等这些注解的类,则把这些类注册为bean。 https://www.cnblogs.com/vanl/p/5733655.html --> <context:component-scan base-package="io.zhangjia.springmvc"/> <!--读取properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!--静态资源的请求转由Web容器处理--> <mvc:default-servlet-handler/> <!--配置默认组件--> <mvc:annotation-driven/> <!--如果不配置这个,那么静态资源可以访问,Controller无法访问--> <!--配置数据库连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <!-- OGNL--> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配置jdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
八. web.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--解決中文乱码--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置hiddenHttpMethodFilter--> <!--浏览器只支持Post和get的方式,想要实现delete和put的方式,需要使用过滤器HiddenHttpMethodFilter--> <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置请求分配器开始--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置SpringMVC配置文件的路径--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!--在web容器启动时完成初始化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
九. JSP
books.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="path" value="${pageContext.request.contextPath}"/> <html> <head> <title>图书列表</title> <link rel="stylesheet" href="${path}/static/css/bootstrap.min.css"/> <script type="text/javascript" src="${path}/static/js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> function del(e) { var tr = $(e).parent().parent(); var id = tr.children(":first").text(); $.ajax({ url:"${path}/book/"+id, type:"post", data:{ _method:"delete" }, success:function (res) { if(res.success){ //删除tr tr.remove(); }else { alert("失败"); } } }); } </script> </head> <body class="container"> <h1>图书列表</h1> <a href="${path}/book" class="btn btn-success mb-2">添加</a> <table class="table table-striped"> <tr> <th>编号</th> <th>书名</th> <th>作者</th> <th>价格</th> <th>操作</th> </tr> <c:forEach items="${requestScope.books}" var="book"> <tr> <td>${book.bookId}</td> <td>${book.name}</td> <td>${book.author}</td> <td>${book.price}</td> <td> <a class="btn btn-sm btn-primary" href="${path}/book/${book.bookId}">修改</a> <a class="btn btn-sm btn-danger" href="javascript:void (0)" onclick="del(this)">删除</a> </td> </tr> </c:forEach> </table> </body> </html>
form.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="path" value="${pageContext.request.contextPath}"/> <html> <head> <c:if test="${requestScope.book == null}"> <title>添加图书</title> </c:if> <c:if test="${requestScope.book != null}"> <title>修改图书</title> </c:if> <link rel="stylesheet" href="${path}/static/css/bootstrap.min.css"/> <script type="text/javascript" src="${path}/static/js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(function () { $(":submit").click(function () { var data = $("#book-form").serialize(); $.ajax({ url:"${path}/book", type:"post", data:data, success:function (res) { if(res.success){ location = "${path}/books"; }else{ alert("失败"); } } }); return false; }); }); </script> </head> <body class="container"> <c:if test="${requestScope.book == null}"> <h1>添加图书</h1> </c:if> <c:if test="${requestScope.book != null}"> <h1>修改图书</h1> </c:if> <form id="book-form" role="form" action="" method="post"> <c:if test="${requestScope.book != null}"> <input type="hidden" name="bookId" value="${requestScope.book.bookId}"> <input type="hidden" name="_method" value="put"> </c:if> <div class="form-group"> <label for="name">名称</label> <input type="text" class="form-control" name="name" id="name" value="${requestScope.book.name}" placeholder="请输入名称"> </div> <div class="form-group"> <label for="author">作者</label> <input type="text" class="form-control" name="author" value="${requestScope.book.author}" id="author" placeholder="请输入作者"> </div> <div class="form-group"> <label for="price">价格</label> <input type="text" class="form-control" name="price" id="price" value="${requestScope.book.price}" placeholder="请输入价格"> </div> <input class="btn btn-primary" type="submit" value="提交"> </form> </body> </html>
请登录之后再进行评论