表单标签的使用

表单标签库

表单标签库中包含了可以用在jsp页面中渲染HTML元素的标签。为了使用这些标签,必须在jsp页面中的开头出声明taglib指令。

<%@ taglib prefix="form" uri="http://springframework.org/tags/form" %>
在表单标签库中的标签
标签 描述
form 渲染表单元素
input 渲染 元素
password 渲染 元素
hidden 渲染 元素
textarea 渲染textarea元素
checkbox 渲染一个元素
checkboxes 渲染多个元素
radiobutton 渲染一个元素
radiobuttons 渲染多个元素
select 渲染一个选择元素
option 渲染一个可选元素
options 渲染一个可选元素列表
errors 在span元素中渲染字段错误



    表单标签用于渲染HTML表单。表单标签必须利用渲染表单输入字段的其他任意标签。

<form:form commandName="book" action="book_save" method="post">

form:form>
       表单标签的属性
属性 描述
acceptCharset 定义服务器接受的字符编码列表
commandName 暴露表单对象之模型属性的名称,默认为command
cssClass 定义要应用到被渲染form元素的CSS类
cssStyle 定义要应用到被渲染form元素的CSS样式
htmlEscape 接受true或者false, 表示被渲染的值是否应该进行HTML转义
modeAttribute 暴露form backing object 的模型属性名称,默认为commend

展示代码部分

@RequestMapping(value="/页面路径")
public String inputBook(Model model){
    ...
    model.addAttribute("book", new Book());
    return "要跳转的页面";
}

    在代码当中此处用book属性创建了一个Book对象,并添加到Model.如果没有Model属性,跳转的页面就会抛出异常,因为表单标签无法找到在其commandName属性中指定的dorm backing object.

input标签

    input标签渲染元素。这个标签最重要的属性是path,它将这个输入字段绑定到form backing object的一个属性。例如,若随附

标签的commandName属性值为book,并且input属性值为isbn,那么,input标签将被绑定到Book对象的isbn属性。

input标签的属性
属性 描述
cssClass 定义要应用到被渲染input元素的css类
cssStyle 定义要应用到被渲染input元素的css样式
cssErrorClass 定义要应用到被渲染input元素的css类,如果bound属性中包含错误,则覆盖cssClass属性值
htmlEscape 接受true或者false,表示十分应该对被渲染的值进行HTML转义
path 要绑定的属性路径

举个例子

他将会被渲染成下面的元素:

cssErrorClass属性不起作用,除非isbn属性中输入验证错误,并且采用同一个表单重行显示用户输入,在这种情况下,input标签就会被渲染成下面这个input元素。

input标签也可以绑定到嵌套对象的属性。例如,下列的input标签绑定到form backing object的category属性的id属性。

剩下的标签就不一一介绍,如果读者感兴趣看文档会更详细。

一个小的例子

表单标签的使用_第1张图片
domain里面的bean

package domain;

import java.io.Serializable;

public class Book implements Serializable{
    private static final long serialVersionUID = 7461688389112847430L;

    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 catgory, String author){
        this.id = id;
        this.isbn = isbn;
        this.title = title;
        this.category = catgory;
        this.author = author;
    }

    //get and set method
    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 domain;

import java.io.Serializable;

public class Category implements Serializable{
    private static final long serialVersionUID = -6019865946011659102L;
    private int id;
    private String name;
    public Category(){}//无参
    //Constructor with arguments
    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;
    }

    //get and set method

}

控制器的相关类

package controller;

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 domain.Book;
import domain.Category;

import java.util.List;

import 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 = bookService.getAllcategories();
        model.addAttribute("book", new Book());
        model.addAttribute("category", category);
        return "BookAddForm";
    }

    @RequestMapping(value="/book_edit/{id}")
    public String editBook(Model model, @PathVariable long id){
        List category = bookService.getAllcategories();
        model.addAttribute("category", category);
        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 books = bookService.getAllBooks();
        model.addAttribute("books", books);
//      System.out.println("进入");
        return "BookList";
    }
}

实现的方法以及接口servlet

package service;

import java.util.List;

import domain.Book;
import domain.Category;

public interface BookService {
    List getAllcategories();
    Category getCategory(int id);
    List getAllBooks();
    Book save(Book book);
    Book update(Book book);
    Book get(long id);
    long getNextId();
}

package service;

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

import org.springframework.stereotype.Service;

import domain.Book;
import domain.Category;
@Service
public class BookServiceImpl implements BookService{
    /*
     * this implementation is not thread-safe
     */
    private List category;
    private List books;

    public BookServiceImpl() {
        category = new ArrayList<>();
        Category category1 = new Category(1, "Computing");
        Category category2 = new Category(2, "Travel");
        Category category3 = new Category(3, "Health");
        category.add(category1);
        category.add(category2);
        category.add(category3);

        books = new ArrayList<>();
        books.add(new Book(1L, "9780980839623", "servlet & jsp: a tutorial", category1, "Budi Kurniawan"));
        books.add(new Book(2L, "9780980839620", "c# A Beginner's Tutorial", category1, "Jayden Ky"));
    }

    @Override
    public List getAllcategories() {
        return category;
    }

    @Override
    public Category getCategory(int id) {
        for(Category category1 : category)
            if(id == category1.getId())
                return category1;
        return null;
    }

    @Override
    public List getAllBooks() {
        return books;
    }

    //执行添加操作
    @Override
    public Book save(Book book) {
        book.setId(getNextId());
        books.add(book);
        return book;
    }

    //执行更新操作
    @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 Book get(long id) {
        for(Book book : books){
            if(id == book.getId())
                return book;
        }
        return null;
    }

    @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;
    }

}

jsp片段



<html>
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Book Formtitle>
<style type="text.css">@import url(""/>");style>
head>
<body>

<div id="global">
    <form:form commandName="book" action="book_save" method="post">
        <fieldset>
            <legend>Add a booklegend>
            <p>
                <label for="category">Category:label>
                <form:select id="category" path="category.id" items="${category}"
                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 path="author" id="author"/>
            p>
            <p>
                <label for="isbn">ISBN:label>
                <form:input path="isbn" id="isbn"/>
            p>
            <p id="buttons">
                <input id="reset" type="reset" tabindex="4" value="reset"/>
                <input id="submit" type="submit" tabindex="5" value="Add Book"/>
            p>
        fieldset>
    form:form>
div>
body>
html>



<html>
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit Book Formtitle>
<style type="text.css">@import url(""/>");style>
head>
<body>

<div id="global">
    <form:form commandName="book" action="book_update" method="post">
        <fieldset>
            <legend>Edit Book Formlegend>
            <form:hidden path="id"/>
            <p>
                <label for="category">Category:label>
                <form:select id="category" path="category.id" items="${category}"
                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 path="author" id="author"/>
            p>
            <p>
                <label for="isbn">ISBN:label>
                <form:input path="isbn" id="isbn"/>
            p>
            <p id="buttons">
                <input id="reset" type="reset" tabindex="4" value="reset"/>
                <input id="submit" type="submit" tabindex="5" value="Update Book">
            p>
        fieldset>
    form:form>
div>
body>
html>



<html>
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Listtitle>
<style type="text.css">@import url(""/>");style>
head>
<body>
<div id="global">
    <h1>Book Listh1>
    <a href="book_input"/>">Add Booka>
    <table>
        <tr>
            <th>Categoryth>
            <th>Titleth>
            <th>ISBNth>
            <th>Authorth>
            <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}">Edita>td>
            tr>
        c:forEach>
    table>
div>
body>
html>

xml的基本配置



<web-app version="2.5" 
    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_2_5.xsd">
    <servlet>
        <servlet-name>springservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/config/spring-config.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springservlet-name>
        
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>



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

你可能感兴趣的:(spring-mvc)