1 案例功能
案例实现了列出书目、添加新书、编辑书目的功能
2 案例导入的Jar包
3 案例程序目录
4 代码
4.1 Domain类
4.1.1 Book
package com.springmvc.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;}
}
4.1.2 Category
package com.springmvc.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;}
}
4.2 Controller类
package com.springmvc.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 com.springmvc.domain.Book;
import com.springmvc.domain.Category;
import com.springmvc.service.BookService;
@Controller
public 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";
}
}
4.3 Service
4.3.1 BookService
package com.springmvc.service;
import java.util.List;
import com.springmvc.domain.Book;
import com.springmvc.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();
}
4.3.2 BookServiceImpl
package com.springmvc.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.springmvc.domain.Book;
import com.springmvc.domain.Category;
@Service
public 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;
}
}
4.4 Spring MVC配置文件
<?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="com.springmvc.controller"/>
<context:component-scan base-package="com.springmvc.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"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp">
</bean>
</beans>
4.5 View层
4.5.1 BookList.jsp
<%@ 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>
4.5.2 BookAddFom.jsp
<%@ 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>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>
<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="Add Book">
</p>
</fieldset>
</form:form>
</div>
</body>
</html>
4.5.3 BookEditForm.jsp
<%@ 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>
4.5.4 main.css
#global {
text-align: left; border: 1px solid #dedede; background: #efefef;
width: 560px; padding: 20px; margin: 100px auto;
}
form {font:100% verdana; min-width: 500px; max-width: 600px; width: 560px;
}
form fieldset { border-color: #bdbebf; border-width: 3px; margin: 0;}
legend { font-size: 1.3em;}
form label { width: 250px; display: block; float: left; text-align: right; padding: 2px;}
table td { border: 1px solid #dedede; background: MistyRose;}
#buttons { text-align: right;}
#errors, li { color: red;}
.error { color: red; font-size: 9pt; }
4.6 Web配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>YJYSpring_MVC_DataBind_PaulDeckCH05</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
5 运行测试
http://localhost:8080/YJYSpring_MVC_DataBind_PaulDeckCH05/book_list
进入新增页面
显示新增的结果
进入编辑