1.有了数据绑定,类型总是为了String的HTTP请求参数,可用于填充不同的类型的对象属性

 

2.表单标签库

为了使用这些标签,必须在jsp页面开头处声明这个taglib指令

<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

form,input,password,hidden,textarea,checkbox,checkboxs,radiobutton,radiobuttons

select,option,options,errors渲染元素

 

表单标签

 1 <form:form commandName="book" action="book_save" method="post">
 2 </form>
 3 
 4 commandName它定义了模型属性的名称,其属性用于填充所生成的表单
 5 
 6 @RequestMapping("/book_input")
 7 public String inputBook(Model model){
 8 
 9      model.addAttribute("book",new Book());       
10 }
11 
12 如果没有Model属性,jsp会报错,无法找到commandName属性

 

input标签:

 1 <form:input id="isbn" path="isbn" cssErrorClass="errorBox">

 2 </form>


path:属性,它将这个输入的字段绑定到book的一个属性,绑定到book的isbn属性 5  

 

数据绑定范例:

 

 

1.Domain

 1 package app05a.domain;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Book implements Serializable {
 6     
 7     private static final long serialVersionUID = 1520961851058396786L;
 8     private long id;
 9     private String isbn;
10     private String title;
11     private Category category;
12     private String author;
13     
14     public Book() {
15     }
16     
17     public Book(long id, String isbn, String title, 
18             Category category, String author) {
19         this.id = id;
20         this.isbn = isbn;
21         this.title = title;
22         this.category = category;
23         this.author = author;
24     }
25 
26     public long getId() {
27         return id;
28     }
29     public void setId(long id) {
30         this.id = id;
31     }
32     public String getIsbn() {
33         return isbn;
34     }
35     public void setIsbn(String isbn) {
36         this.isbn = isbn;
37     }
38     public String getTitle() {
39         return title;
40     }
41     public void setTitle(String title) {
42         this.title = title;
43     }
44     public Category getCategory() {
45         return category;
46     }
47     public void setCategory(Category category) {
48         this.category = category;
49     }
50     public String getAuthor() {
51         return author;
52     }
53     public void setAuthor(String author) {
54         this.author = author;
55     }
56 }

 

 1 package app05a.domain;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Category implements Serializable {
 6     private static final long serialVersionUID = 5658716793957904104L;
 7     private int id;
 8     private String name;
 9     
10     public Category() {
11     }
12     
13     public Category(int id, String name) {
14         this.id = id;
15         this.name = name;
16     }
17     
18     public int getId() {
19         return id;
20     }
21     public void setId(int id) {
22         this.id = id;
23     }
24     public String getName() {
25         return name;
26     }
27     public void setName(String name) {
28         this.name = name;
29     }
30 }

 

3.Controller

 1 package app05a.controller;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.commons.logging.Log;
 6 import org.apache.commons.logging.LogFactory;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.ui.Model;
10 import org.springframework.web.bind.annotation.ModelAttribute;
11 import org.springframework.web.bind.annotation.PathVariable;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 
14 import app05a.domain.Book;
15 import app05a.domain.Category;
16 import app05a.service.BookService;
17 
18 @Controller
19 public class BookController {
20 
21     @Autowired
22     private BookService bookService;
23 
24     private static final Log logger = LogFactory.getLog(BookController.class);
25 
26     @RequestMapping(value = "/book_input")
27     public String inputBook(Model model) {
28         List<Category> categories = bookService.getAllCategories();
29         model.addAttribute("categories", categories);
30         model.addAttribute("book", new Book());
31         return "BookAddForm";
32     }
33 
34     @RequestMapping(value = "/book_edit/{id}")
35     public String editBook(Model model, @PathVariable long id) {
36         List<Category> categories = bookService.getAllCategories();
37         model.addAttribute("categories", categories);
38         Book book = bookService.get(id);
39         model.addAttribute("book", book);
40         return "BookEditForm";
41     }
42 
43     @RequestMapping(value = "/book_save")
44     public String saveBook(@ModelAttribute Book book) {
45         Category category = bookService.getCategory(book.getCategory().getId());
46         book.setCategory(category);
47         bookService.save(book);
48         return "redirect:/book_list";
49     }
50 
51     @RequestMapping(value = "/book_update")
52     public String updateBook(@ModelAttribute Book book) {
53         Category category = bookService.getCategory(book.getCategory().getId());
54         book.setCategory(category);
55         bookService.update(book);
56         return "redirect:/book_list";
57     }
58 
59     @RequestMapping(value = "/book_list")
60     public String listBooks(Model model) {
61         logger.info("book_list");
62         List<Book> books = bookService.getAllBooks();
63         model.addAttribute("books", books);
64         return "BookList";
65     }
66 }

 

 

4.Service

 1 package app05a.service;
 2 
 3 import java.util.List;
 4 
 5 import app05a.domain.Book;
 6 import app05a.domain.Category;
 7 
 8 public interface BookService {
 9     
10     List<Category> getAllCategories();
11     Category getCategory(int id);
12     List<Book> getAllBooks();
13     Book save(Book book);
14     Book update(Book book);
15     Book get(long id);
16     long getNextId();
17 
18 }

 

 

5.

  1 package app05a.service;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 import org.springframework.stereotype.Service;
  7 
  8 import app05a.domain.Book;
  9 import app05a.domain.Category;
 10 
 11 @Service
 12 public class BookServiceImpl implements BookService {
 13     
 14     /*
 15      * this implementation is not thread-safe
 16      */
 17     private List<Category> categories;
 18     private List<Book> books;
 19     
 20     public BookServiceImpl() {
 21         categories = new ArrayList<Category>();
 22         Category category1 = new Category(1, "Computing");
 23         Category category2 = new Category(2, "Travel");
 24         Category category3 = new Category(3, "Health");
 25         categories.add(category1);
 26         categories.add(category2);
 27         categories.add(category3);
 28         
 29         books = new ArrayList<Book>();
 30         books.add(new Book(1L, "9780980839623", 
 31                 "Servlet & JSP: A Tutorial", 
 32                 category1, "Budi Kurniawan"));
 33         books.add(new Book(2L, "9780980839630",
 34                 "C#: A Beginner's Tutorial",
 35                 category1, "Jayden Ky"));
 36     }
 37 
 38     @Override
 39     public List<Category> getAllCategories() {
 40         return categories;
 41     }
 42     
 43     @Override
 44     public Category getCategory(int id) {
 45         for (Category category : categories) {
 46             if (id == category.getId()) {
 47                 return category;
 48             }
 49         }
 50         return null;
 51     }
 52 
 53     @Override
 54     public List<Book> getAllBooks() {
 55         return books;
 56     }
 57 
 58     @Override
 59     public Book save(Book book) {
 60         book.setId(getNextId());
 61         books.add(book);
 62         return book;
 63     }
 64 
 65     @Override
 66     public Book get(long id) {
 67         for (Book book : books) {
 68             if (id == book.getId()) {
 69                 return book;
 70             }
 71         }
 72         return null;
 73     }
 74     
 75     @Override
 76     public Book update(Book book) {
 77         int bookCount = books.size();
 78         for (int i = 0; i < bookCount; i++) {
 79             Book savedBook = books.get(i);
 80             if (savedBook.getId() == book.getId()) {
 81                 books.set(i, book);
 82                 return book;
 83             }
 84         }
 85         return book;
 86     }
 87     
 88     @Override
 89     public long getNextId() {
 90         // needs to be locked
 91         long id = 0L;
 92         for (Book book : books) {
 93             long bookId = book.getId();
 94             if (bookId > id) {
 95                 id = bookId;
 96             }
 97         }
 98         return id + 1;
 99     }
100 }

 

5.配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans.xsd
10         http://www.springframework.org/schema/mvc
11         http://www.springframework.org/schema/mvc/spring-mvc.xsd     
12         http://www.springframework.org/schema/context
13         http://www.springframework.org/schema/context/spring-context.xsd">
14         
15     <context:component-scan base-package="app05a.controller"/>
16     <context:component-scan base-package="app05a.service"/>
17      
18     <mvc:annotation-driven/>
19     <mvc:resources mapping="/css/**" location="/css/"/>
20     <mvc:resources mapping="/*.html" location="/"/>
21     
22     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
23         <property name="prefix" value="/WEB-INF/jsp/"/>
24         <property name="suffix" value=".jsp"/>
25     </bean>
26     
27 </beans>

 

6.视图

 1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 2 <!DOCTYPE HTML>
 3 <html>
 4 <head>
 5 <title>Book List</title>
 6 <style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
 7 </head>
 8 <body>
 9 
10 <div id="global">
11 <h1>Book List</h1>
12 <a href="<c:url value="/book_input"/>">Add Book</a>
13 <table>
14 <tr>
15     <th>Category</th>
16     <th>Title</th>
17     <th>ISBN</th>
18     <th>Author</th>
19     <th>&nbsp;</th>
20 </tr>
21 <c:forEach items="${books}" var="book">
22     <tr>
23         <td>${book.category.name}</td>
24         <td>${book.title}</td>
25         <td>${book.isbn}</td>
26         <td>${book.author}</td>
27         <td><a href="book_edit/${book.id}">Edit</a></td>
28     </tr>
29 </c:forEach>
30 </table>
31 </div>
32 </body>
33 </html>

 

 1 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <!DOCTYPE HTML>
 4 <html>
 5 <head>
 6 <title>Add Book Form</title>
 7 <style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
 8 </head>
 9 <body>
10 
11 <div id="global">
12 <form:form commandName="book" action="book_save" method="post">
13     <fieldset>
14         <legend>Add a book</legend>
15         <p>
16             <label for="category">Category: </label>
17              <form:select id="category" path="category.id" 
18                 items="${categories}" itemLabel="name" 
19                 itemValue="id"/>
20         </p>
21         <p>
22             <label for="title">Title: </label>
23             <form:input id="title" path="title"/>
24         </p>
25         <p>
26             <label for="author">Author: </label>
27             <form:input id="author" path="author"/>
28         </p>
29         <p>
30             <label for="isbn">ISBN: </label>
31             <form:input id="isbn" path="isbn"/>
32         </p>
33         
34         <p id="buttons">
35             <input id="reset" type="reset" tabindex="4">
36             <input id="submit" type="submit" tabindex="5" 
37                 value="Add Book">
38         </p>
39     </fieldset>
40 </form:form>
41 </div>
42 </body>
43 </html>

 

 

 1 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <!DOCTYPE HTML>
 4 <html>
 5 <head>
 6 <title>Edit Book Form</title>
 7 <style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
 8 </head>
 9 <body>
10 
11 <div id="global">
12 <form:form commandName="book" action="/book_update" method="post">
13     <fieldset>
14         <legend>Edit a book</legend>
15         <form:hidden path="id"/>
16         <p>
17             <label for="category">Category: </label>
18              <form:select id="category" path="category.id" items="${categories}"
19                 itemLabel="name" itemValue="id"/>
20         </p>
21         <p>
22             <label for="title">Title: </label>
23             <form:input id="title" path="title"/>
24         </p>
25         <p>
26             <label for="author">Author: </label>
27             <form:input id="author" path="author"/>
28         </p>
29         <p>
30             <label for="isbn">ISBN: </label>
31             <form:input id="isbn" path="isbn"/>
32         </p>
33         
34         <p id="buttons">
35             <input id="reset" type="reset" tabindex="4">
36             <input id="submit" type="submit" tabindex="5" 
37                 value="Update Book">
38         </p>
39     </fieldset>
40 </form:form>
41 </div>
42 </body>
43 </html>

 

7.测试应用

http://localhost:8080/app05a/book_list

 

posted on 2016-03-22 22:54  Sharpest  阅读(498)  评论(0编辑  收藏  举报