【笔记】Spring MVC学习指南(五)数据绑定和表单标签库

来源:互联网 发布:mysql表空间不足 编辑:程序博客网 时间:2024/05/17 02:46

这一章纯粹是介绍标签的使用,需要注意的地方就是如何将属性与标签正确地绑定在一起,其他的,没什么可说的了,把代码贴出来,方便温习。




package app05a.controller;import java.util.List;import org.apache.commons.logging.Log;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 app05a.domain.Book;import app05a.domain.Category;import app05a.service.BookService;@Controllerpublic class BookController {    @Autowired    private BookService bookService;    private static final Log logger = LogFactory.getLog(BookController.class);    @RequestMapping(value = "/book_input")    public String inputBook(Model model) {        List<Category> categories = bookService.getAllCategories();        model.addAttribute("categories", categories);        model.addAttribute("book", new Book());        return "BookAddForm";    }    @RequestMapping(value = "/book_edit/{id}")    public String editBook(Model model, @PathVariable long id) {        List<Category> categories = bookService.getAllCategories();        model.addAttribute("categories", categories);        Book book = bookService.get(id);        model.addAttribute("book", book);        return "BookEditForm";    }    @RequestMapping(value = "/book_save")    public String saveBook(@ModelAttribute Book book) {        Category category = bookService.getCategory(book.getCategory().getId());        book.setCategory(category);        bookService.save(book);        return "redirect:/book_list";    }    @RequestMapping(value = "/book_update")    public String updateBook(@ModelAttribute Book book) {        Category category = bookService.getCategory(book.getCategory().getId());        book.setCategory(category);        bookService.update(book);        return "redirect:/book_list";    }    @RequestMapping(value = "/book_list")    public String listBooks(Model model) {        logger.info("book_list");        List<Book> books = bookService.getAllBooks();        model.addAttribute("books", books);        return "BookList";    }}

package app05a.domain;import java.io.Serializable;public class Book implements Serializable {    private static final long serialVersionUID = 1520961851058396786L;    private long id;    private String isbn;    private String title;    private Category category;    private String author;    public Book() {    }    public Book(long id, String isbn, String title, Category category, String author) {        this.id = id;        this.isbn = isbn;        this.title = title;        this.category = category;        this.author = author;    }    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;    }}

package app05a.domain;import java.io.Serializable;public class Category implements Serializable {    private static final long serialVersionUID = 5658716793957904104L;    private int id;    private String name;        public Category() {    }        public Category(int id, String name) {        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;    }}

package app05a.service;import java.util.List;import app05a.domain.Book;import app05a.domain.Category;public interface BookService {        List<Category> getAllCategories();    Category getCategory(int id);    List<Book> getAllBooks();    Book save(Book book);    Book update(Book book);    Book get(long id);    long getNextId();}

package app05a.service;import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Service;import app05a.domain.Book;import app05a.domain.Category;@Servicepublic class BookServiceImpl implements BookService {    /*     * this implementation is not thread-safe     */    private List<Category> categories;    private List<Book> books;    public BookServiceImpl() {        categories = new ArrayList<Category>();        Category category1 = new Category(1, "Computing");        Category category2 = new Category(2, "Travel");        Category category3 = new Category(3, "Health");        categories.add(category1);        categories.add(category2);        categories.add(category3);        books = new ArrayList<Book>();        // 启动应用时,会执行一次这个构造器        books.add(new Book(1L, "9780980839623", "Servlet & JSP: A Tutorial", category1, "Budi Kurniawan"));        books.add(new Book(2L, "9780980839630", "C#: A Beginner's Tutorial", category1, "Jayden Ky"));    }    @Override    public List<Category> getAllCategories() {        return categories;    }    @Override    public Category getCategory(int id) {        for (Category category : categories) {            if (id == category.getId()) {                return category;            }        }        return null;    }    @Override    public List<Book> getAllBooks() {        return books;    }    @Override    public Book save(Book book) {        book.setId(getNextId());        books.add(book);        return book;    }    @Override    public Book get(long id) {        for (Book book : books) {            if (id == book.getId()) {                return book;            }        }        return null;    }    @Override    public Book update(Book book) {        int bookCount = books.size();        for (int i = 0; i < bookCount; i++) {            Book savedBook = books.get(i);            if (savedBook.getId() == book.getId()) {                books.set(i, book);                return book;            }        }        return book;    }    @Override    public long getNextId() {        // needs to be locked        long id = 0L;        for (Book book : books) {            long bookId = book.getId();            if (bookId > id) {                id = bookId;            }        }        return id + 1;    }}

<?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:p="http://www.springframework.org/schema/p"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd             http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd">            <context:component-scan base-package="app05a.controller"/>    <context:component-scan base-package="app05a.service"/>         <mvc:annotation-driven/>    <mvc:resources mapping="/css/**" location="/css/"/>    <mvc:resources mapping="/*.html" location="/"/>        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/"/>        <property name="suffix" value=".jsp"/>    </bean>    </beans>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%--使用spring提供的标签库--%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML><html><head>    <title>Add Book Form</title>    <style type="text/css">@import url("<c:url value="/css/main.css"/>");</style></head><body><div id="global">    <form:form commandName="book" action="book_save" method="post">        <fieldset>            <legend>Add a book</legend>            <p>                <label for="category">Category: </label>                    <%--path设置为category.id 与 Book.Category.id绑定, items与集合绑定,itemLabel、itemValue与集合中单个元素的某个属性绑定--%>                <form:select id="category" path="category.id"                             items="${categories}" itemLabel="name"                             itemValue="id"/>            </p>                <%--使用options标签,和上一个select实现相同的效果--%>                <%--<p>                    <label for="category">Category: </label>                    <form:select path="category.id" id="category">                        <form:options items="${categories}" itemValue="id" itemLabel="name"></form:options>                    </form:select>                </p>--%>            <p>                <label for="title">Title: </label>                <form:input id="title" path="title"/>            </p>            <p>                <label for="author">Author: </label>                <form:input id="author" path="author"/>            </p>            <p>                <label for="isbn">ISBN: </label>                <form:input id="isbn" path="isbn"/>            </p>            <p id="buttons">                <input id="reset" type="reset" tabindex="4">                <input id="submit" type="submit" tabindex="5"                       value="Add Book">            </p>        </fieldset>    </form:form></div></body></html>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML><html><head><title>Edit Book Form</title><style type="text/css">@import url("<c:url value="/css/main.css"/>");</style></head><body><div id="global"><form:form commandName="book" action="/book_update" method="post">    <fieldset>        <legend>Edit a book</legend>        <form:hidden path="id"/>        <p>            <label for="category">Category: </label>             <form:select id="category" path="category.id" items="${categories}"                itemLabel="name" itemValue="id"/>        </p>        <p>            <label for="title">Title: </label>            <form:input id="title" path="title"/>        </p>        <p>            <label for="author">Author: </label>            <form:input id="author" path="author"/>        </p>        <p>            <label for="isbn">ISBN: </label>            <form:input id="isbn" path="isbn"/>        </p>                <p id="buttons">            <input id="reset" type="reset" tabindex="4">            <input id="submit" type="submit" tabindex="5"                 value="Update Book">        </p>    </fieldset></form:form></div></body></html>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE HTML><html><head><title>Book List</title><style type="text/css">@import url("<c:url value="/css/main.css"/>");</style></head><body><div id="global"><h1>Book List</h1><a href="<c:url value="/book_input"/>">Add Book</a><table><tr>    <th>Category</th>    <th>Title</th>    <th>ISBN</th>    <th>Author</th>    <th> </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><a href="book_edit/${book.id}">Edit</a></td>    </tr></c:forEach></table></div></body></html>

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0"         xmlns="http://java.sun.com/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">    <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>


0 1
原创粉丝点击