数据绑定:
数据绑定是将用户输入绑定到领域对象模型的一种特性。
数据绑定的好处:
1.帮助解析字符串,转换成相应的数据类型
2.另一个好处,在进行输入验证时(数据绑定与数据验证知识点结合使用):当输入验证失败时,它会重新生成一个HTML表单。手工编写HTML代码时,必须记住之前输入的值,重新填入输入的字段。有了Spring的数据绑定和表单标签库后,他们就会替你完成这些工作。
下面只是展示数据绑定部分:
1.目录结构
2.domain类
Book类
package domain; public class Book { //书的id号 private long id; //书的国际编号 private String isbn; //书的名称 private String title; //书的类别 private Category category; //书的作家 private String author; //书的价格 private double price; public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Book() { super(); } public Book(long id, String isbn, String title, Category category, String author, double price) { super(); this.id = id; this.isbn = isbn; this.title = title; this.category = category; this.author = author; this.price = price; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
Category类:(注:category 意思:类别)
package domain; //类别类 public class Category { private int id; private String name; public Category() { super(); // TODO Auto-generated constructor stub } public Category(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3.Controller类:
package Controller; import java.util.List; import org.apache.commons.logging.Log; /* * <!-- 书的作家 --> <!-- <td>${book.Author }</td>--> */ import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import domain.Book; import domain.Category; import service.BookService; @Controller public class bookController { //通过依赖注入 @Autowired private BookService bookservice; private static final Log logger=LogFactory.getLog(bookController.class); //--------------------------图书展示部分--------------------- /* * 图书表单展示 */ @RequestMapping(value="/listBook") String bookList(Model model) { model.addAttribute("books",bookservice.getBooks()); model.addAttribute("book",new Book()); return "BookList"; } //------------------------图书表单添加部分--------------------- /* * 图书添加表单 */ @RequestMapping(value="/inputBook") String addBook(Model model){ model.addAttribute("categorys", bookservice.getAllCategorys()); model.addAttribute("book",new Book()); return "BookAddForm"; } /* * 图书保存 */ @RequestMapping(value="/bookSave") String bookSave(@ModelAttribute Book book) { //获取图书类别 Category category=bookservice.getCategoryById(book.getCategory().getId()); //添加图书类别 book.setCategory(category); //获取当前最大编号 long num=bookservice.getnum()+1; //设置图书编号 book.setId(num); //保存图书 bookservice.save(book); return "redirect:/listBook"; } //-------------------------图书更新部分---------------------- /* * 图书编辑 */ @RequestMapping(value="/edit/{id}") String edit(Model model,@PathVariable Long id) { //获取图书类别 List<Category> categorys=bookservice.getAllCategorys(); model.addAttribute("categorys",categorys); //获取图书 Book book=bookservice.getBookById(id); model.addAttribute("book",book); return "BookEditForm"; } /* * 图书更新 */ @RequestMapping(value="/edit/update") String update(@ModelAttribute Book book) { //通过浏览器传来的类型编号获取图书类型编号 int n=book.getCategory().getId(); Category category=bookservice.getCategoryById(n); book.setCategory(category); //进行图书更新 System.out.println("ojidgjkgm"); System.out.println(book.getId()); bookservice.update(book); //设置图书类型 return "redirect:/listBook"; } }
4.Service类:
接口:
package service; import java.util.List; import domain.Book; import domain.Category; /* * 接口为表单提书籍服务 * 包括增删改查 */ public interface BookServiceInf { //---------书籍类别------------- //获取所有书籍类型对象 List<Category> getAllCategorys(); //获取Category Category getCategoryById(int n); //--------- 书籍 ---------------- //获取所有书籍 List<Book> getBooks(); //书籍添加 Book save(Book book); //获取当前编号 Long getnum(); //书籍更新 Book update(Book book); //获取书籍编号 int getId(); //通过编号获取书籍 Book getBookById(Long id); }
BookService类:
package service; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; import domain.Book; import domain.Category; @Service public class BookService implements BookServiceInf{ //目录表 List<Category> categorys=new ArrayList<Category>(); //书籍表 List<Book> bookList=new ArrayList<Book>(); public BookService() { Category c1=new Category(1, "computer"); Category c2=new Category(2, "economics"); Category c3=new Category(3,"law"); categorys.add(c1); categorys.add(c2); categorys.add(c3); bookList.add(new Book(1, "9780980839623", "jsp", c1, "budi",56.9)); bookList.add(new Book(2, "9780980839624", "spring mvc", c1, "moke",45)); bookList.add(new Book(3, "9780980839625", "IBM", c2, "chaozong",78)); bookList.add(new Book(4, "9780980839626", "manage", c2, "yangzong",89)); } @Override public List<Category> getAllCategorys() { return categorys; } @Override public List<Book> getBooks() { return bookList; } @Override public Book save(Book book) { bookList.add(book); return book; } @Override public Book update(Book book) { Long bookNumber=book.getId(); for (int i = 0; i < bookList.size(); i++) { if(bookList.get(i).getId()==book.getId()) { bookList.set(i, book); } } // for (Book book2 : bookList) { // if(book2.getId()==bookNumber) { // System.out.println("匹配成功!!!"); // bookList.set((int)bookNumber, book); // } // } return null; } @Override public int getId() { // TODO Auto-generated method stub return 0; } @Override public Category getCategoryById(int n) { for (Category category : categorys) { if(category.getId()==n) { return category; } } return null; } @Override public Long getnum() { return (long) bookList.size(); } @Override public Book getBookById(Long n) { System.out.println(n); for (Book book : bookList) { if(book.getId()==n) { return book; } } return null; } }
4.配置
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" metadata-complete="true"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springmvc-config.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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <context:component-scan base-package="Controller"/> <context:component-scan base-package="service"/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/"></property> <!-- 后缀 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
5.JSP页面
BookList页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!-- JSTL声明 --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ page isELIgnored="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Book List</title> </head> <body> <h1>Book List</h1> <a href="<c:url value="/inputBook"/>">Add a book</a> <table> <!--表头 --> <tr> <!-- 书的类别 --> <th>Category</th> <!-- 书的名称 --> <th>Title</th> <!-- 书的国际编号 --> <th>Isbn</th> <!--书的作家 --> <th>Author</th> </tr> <c:forEach items="${books }" var="book"> <tr> <!-- 书的类名 --> <td>${book.category.name}</td> <!-- 书的名称 --> <td>${book.title }</td> <!-- 书的国际编号 --> <td>${book.isbn }</td> <!-- 书的作家 --> <td>${book.author }</td> <!-- 书的价格 --> <td>${book.price }</td> <td><a href="edit/${book.id }">Edit</a></td> </tr> </c:forEach> </table> </body> </html>
BookAddForm页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Add a book</title> </head> <!--书的属性包括:书的类别,书的名称,书的国际编码,书的作家 --> <body> <form:form commandName="book" action="bookSave" method="post"> <fieldset> <legend>Add a book</legend> <table> <!-- 书的类别 --> <tr> <td><label>category:</label></td> <!-- 书的类别进行选择输入 --> <td><form:select id="category" path="category.id" items="${categorys }" itemLabel="name" itemValue="id" /> </td> </tr> <!-- 书的名称 --> <tr> <td><label>Title:</label></td> <td><form:input id="title" type="text" path="title"/></td> </tr> <!-- 书的国际编码 --> <tr> <td><label>Isbn:</label></td> <td><form:input id="isbn" type="text" path="isbn"/></td> </tr> <!-- 书的作家 --> <tr> <td><label>Author:</label></td> <td><form:input id="author" type="text" path="author"/></td> </tr> <!-- 书的价格 --> <tr> <td><label>Price:</label></td> <td><form:input id="price" type="text" path="price"/></td> </tr> </table> <input type="reset"/> <input type="submit"/> </fieldset> </form:form> </body> </html>
BookEditForm页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Edit a book</title> </head> <!--书的属性包括:书的类别,书的名称,书的国际编码,书的作家 --> <body> <form:form commandName="book" action="update" method="post"> <fieldset> <legend>Edit a book</legend> <form:hidden id="id" path="id"/> <table> <!-- 书的类别 --> <tr> <td><label>category:</label></td> <!-- 书的类别进行选择输入 --> <td><form:select path="category.id" items="${categorys }" itemLabel="name" itemValue="id" /></td> </tr> <!-- 书的名称 --> <tr> <td><label>title:</label></td> <td><form:input id="title" type="text" path="title"/></td> </tr> <!-- 书的国际编码 --> <tr> <td><label>Isbn:</label></td> <td><form:input id="isbn" type="text" path="isbn"/></td> </tr> <!-- 书的作家 --> <tr> <td><label>Author:</label></td> <td><form:input id="author" type="text" path="author"/></td> </tr> <!-- 书的价格 --> <tr> <td><label>Price:</label></td> <td><form:input type="text" id="price" path="price"/></td> </tr> </table> <input type="reset"/> <input type="submit"/> </fieldset> </form:form> </body> </html>
6.结果截图:
图书列表:
图书添加列表:
图书添加完成列表:
图书编辑列表:
编辑之后: