欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC 表单标签进行数据绑定(图书管理实战)

程序员文章站 2022-04-29 17:19:54
...

该篇博客主要通过一个项目Demo来演绎利用SpringMVC的表单标签进行数据绑定的过程

一、场景

  • 书籍的添加
  • 书籍信息的修改
  • 所有书籍的显示功能

二、场景分析

通过SpringMVC的表单标签进行数据绑定

1、实体类

Book类(书籍类)
Category类(书籍类别类)

2、控制器

BookController:允许用户创建新书籍、修改书籍信息、并列出所有书籍

BookController依赖BookService进行一些后台处理

3、Service类

IBookService接口和其实现类

BookServiceImpl类包含一个Book对象的List和一个Category对象的List。这两个List都是在实例化类时生成的。这个类包含了获取所有书籍、获得单个书籍、添加和更新书籍方法

4、配置文件
  • web.xml配置DispatcherServlet
  • springmvc配置文件配置(1.扫描包、2.配置视图解析器)
5、view视图
  • 修改页面
  • 添加页面
  • 显示所有书籍页面

三、解决方案

1、项目目录

SpringMVC 表单标签进行数据绑定(图书管理实战)

2、实体类(Book、Category)

Book.java
package com.linjie.pojo;

import java.io.Serializable;

/**
* @author 浅然    aaa@qq.com
* @version 创建时间:2018年5月31日 下午2:10:08
* Book实体类
*/
public class Book implements Serializable {
    private static final long serialVersionUID = 1L;
    private long id;            //书的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) {
        super();
        this.id = id;
        this.isbn = isbn;
        this.title = title;
        this.category = category;
        this.author = author;
    }
    /**
     * @return the id
     */
    public long getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(long id) {
        this.id = id;
    }
    /**
     * @return the isbn
     */
    public String getIsbn() {
        return isbn;
    }
    /**
     * @param isbn the isbn to set
     */
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }
    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }
    /**
     * @return the category
     */
    public Category getCategory() {
        return category;
    }
    /**
     * @param category the category to set
     */
    public void setCategory(Category category) {
        this.category = category;
    }
    /**
     * @return the author
     */
    public String getAuthor() {
        return author;
    }
    /**
     * @param author the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }
    /**
     * @return the serialversionuid
     */
    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Book [id=" + id + ", isbn=" + isbn + ", title=" + title + ", category=" + category + ", author="
                + author + "]";
    }
}
Category.java
package com.linjie.pojo;

import java.io.Serializable;

/**
* @author 浅然    aaa@qq.com
* @version 创建时间:2018年5月31日 下午2:13:04
* 类别实体类
*/
public class Category implements Serializable{
    private static final long serialVersionUID = 1L;
    private int id;         //类别的id
    private String name;    //类别的名称

    public Category() {}
    public Category(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the serialversionuid
     */
    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
}

3、控制器(Controller)

BookController.java

注意:BookController依赖BookService进行一些后台处理,需要利用@Autowired标注用于给BookController注入一个IBookService实现

@Autowired(required=true)

private IBookService iBookService;

package com.linjie.controller;

import java.util.List;

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.linjie.pojo.Book;
import com.linjie.pojo.Category;
import com.linjie.service.IBookService;

/**
* @author 浅然    aaa@qq.com
* @version 创建时间:2018年5月31日 下午2:20:33
* 控制器
* 添加书、修改书、保存书、更新书、列出所有书
*/
@Controller
public class BookController {

    @Autowired(required=true)
    private IBookService iBookService;

    //添加书
    @RequestMapping(value = "/book_input")
    public String inputBook(Model model) {
        List<Category> categories = iBookService.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 = iBookService.getAllCategories();
        model.addAttribute("categories",categories);
        Book book = iBookService.get(id);
        model.addAttribute("book",book);
        return "BookEditForm";  
    }

    //保存书
    @RequestMapping(value = "/book_save")
    public String saveBook(@ModelAttribute Book book) {
        Category category = iBookService.getCategory(book.getCategory().getId());
        book.setCategory(category);
        iBookService.save(book);
        return "redirect:/book_list";
    }

    //更新书
    @RequestMapping(value = "/book_update")
    public String updateBook(@ModelAttribute Book book) {
        Category category = iBookService.getCategory(book.getCategory().getId());
        book.setCategory(category);
        iBookService.update(book);
        return "redirect:/book_list";
    }

    //列出所有书
    @RequestMapping(value = "/book_list")
    public String listBooks(Model model) {
        List<Book> books = iBookService.getAllBooks();
        model.addAttribute("books",books);
        return "BookList";
    }
}

4、Service类

IBookService接口
package com.linjie.service;
/**
* @author 浅然    aaa@qq.com
* @version 创建时间:2018年5月31日 下午2:21:56
* 接口
*/

import java.util.List;

import com.linjie.pojo.Book;
import com.linjie.pojo.Category;
public interface IBookService {
    List<Category> getAllCategories();  //获取所有类别
    Category getCategory(int id);       //获取某个类别
    List<Book> getAllBooks();           //获取所有书
    Book save(Book book);               //保存某本书
    Book update(Book book);             //更新某本书
    Book get(long id);                  //获取某本书
    long getNextId();                   //添加书时获取id(获取到最后一本书的id+1)
}
BookServiceImpl实现类
package com.linjie.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.linjie.pojo.Book;
import com.linjie.pojo.Category;

/**
* @author 浅然    aaa@qq.com
* @version 创建时间:2018年5月31日 下午2:40:58
* IBookService接口实现类
* 初始化数据、获取所有书的类别、获取某个类别、获取所有书、获取某书、保存书、更新书、添加书时获取id(获取到最后一本书的id+1)
*/
@Service
public class BookServiceImpl implements IBookService{

    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,"9780232231123",
                "Servlet & JSP:A Tutorial",
                category1,"Budi Kurniawan"));
        books.add(new Book(2L,"9780232234456",
                "Effective Java:A Tutorial",
                category1,"Joshua Bolch"));
    }

    //获取所有书的类别
    @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;
    }   

    //添加书时获取id(获取到最后一本书的id+1)
    @Override
    public long getNextId() {
        long id = 0L;
        for(Book book : books) {
            long bookId = book.getId();
            if(bookId > id) {
                id = bookId;
            }
        }
        return id + 1;
    }

}

5、配置文件

web.xml(配置DispatcherServlet)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
springmvc-servlet.xml(1.扫描包、2.配置视图解析器)
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!-- 扫描 -->
    <context:component-scan base-package="com.linjie"></context:component-scan>
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

6、视图


注意:使用SpringMVC表单标签需要使用

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
BookList.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Book List</title>
</head>
<body>
    <div>
        <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>&nbsp;</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>
BookAddForm.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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 Book Form</title>
</head>
<body>
    <div>
        <form:form commandName="book" action="/Springmvc_Demo/book_save" method="post">
            <fieldset>
                <legend>Add a book</legend>
                <p>
                    <label for="category">Category:</label>
                    <!-- 绑定的items数据可以是数组、集合、或Map会根据items的内容生成select里面的option选项
                    ,当path的值和items中的某条数据值相同的时候,对应的option为选定状态,反之为不选定状态 -->
                    <form:select path="category.id" id="category"
                        items="${categories}" itemLabel="name" itemValue="id">
                    </form:select>
                </p>
                <p>
                    <label for="title">Title:</label>
                    <form:input path="title" id="title"/>
                </p>
                <p>
                    <label for="author">Author:</label>
                    <form:input path="author" id="author"/>
                </p>
                <p>
                    <label for="isbn">ISBN:</label>
                    <form:input path="isbn" id="isbn"/>
                </p>
                <p>
                    <input id="reset" type="reset" tabindex="4">
                    <input id="submit" type="submit" tabindex="5" value="Add Book">
                </p>
            </fieldset>
        </form:form>
    </div>
</body>
</html>
BookEditForm.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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 Book Form</title>
</head>
<body>
    <div>
        <form:form commandName="book" action="/Springmvc_Demo/book_update" mathod="post">
            <fieldset>
                <legend>Edit a book</legend>
                <form:hidden path="id"/>
                <p>
                    <label for="category">Category:</label>
                    <form:select path="category.id" id="category" items="${categories }"
                     itemLabel="name" itemValue="id"></form:select>
                </p>
                <p>
                    <label for="title">Title:</label>
                    <form:input path="title" id="title"/>
                </p>
                <p>
                    <label for="author">Author:</label>
                    <form:input path="author" id="author"/>
                </p>
                <p>
                    <label for="isbn">ISBN:</label>
                    <form:input path="isbn" id="isbn"/>
                </p>
                <p>
                    <input id="reset" type="reset" tabindex="4">
                    <input id="submit" type="submit" tabindex="5"
                        value="Upadate Book">
                </p>
            </fieldset>
        </form:form>
    </div>
</body>
</html>

7、jar包的话我将所有jar都导入了以备不时之需

SpringMVC 表单标签进行数据绑定(图书管理实战)

四、测试应用

地址输入:http://localhost:8080/Springmvc_Demo/book_list

如图为第一次启动应用列出所有书籍

SpringMVC 表单标签进行数据绑定(图书管理实战)

点击Add Book,添加书籍
SpringMVC 表单标签进行数据绑定(图书管理实战)

点击Edit修改书籍信息

SpringMVC 表单标签进行数据绑定(图书管理实战)

工程下载


参考

《Spring MVC学习指南》