您的当前位置:首页正文

Spring MVC的标签库

来源:花图问答

Spring 2.0开始,提供了一组功能强大的标签库。该标签可以访问控制器处理命令对象和绑定数据。

1.表单标签库

1.1 form标签

Spring form标签的作用:

  • 自动绑定Model中的一个属性值到当前form对应的实体对象,默认为command属性。
  • 支持提交form表单除get,post的其他额外操作。如:delete、put等

form标签的两个重要属性

  • commandName

form绑定的模型属性名称,默认为command

  • modelAttribute

form绑定的模型属性名称,默认为command

上面的两个属性的功能是一致的。在前端jsp页面,使用Spring的form表单标签的时候。比如绑定属性的path的时候,需要后端传入一个command对象。

前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form"  %>
<html>
<head>
    <title>Sign Up</title>
</head>
<body>
<form:form>
    <table>
        <tr>
            <td>用户名:</td>
            <td><form:input path="name"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><form:input path="password"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <form:button value="提交"/>
            </td>
        </tr>
    </table>
</form:form>
</body>
</html>
@RequestMapping("signup")
public String signUp(Model model){
   model.addAttribute("command",new User());
   return "signup";
}

生成后的代码





<html>
<head>
    <title>Sign Up</title>
</head>
<body>
<form id="command" action="/user/signup" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input id="name" name="name" type="text" value=""/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input id="password" name="password" type="text" value=""/></td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit" value="提交"></button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

使用modelAttribute表示

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form"  %>
<html>
<head>
    <title>Sign Up</title>
</head>
<body>
<form:form modelAttribute="user">
    <table>
        <tr>
            <td>用户名:</td>
            <td><form:input path="name"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><form:input path="password"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <form:button value="提交"/>
            </td>
        </tr>
    </table>
</form:form>
</body>
</html>
@RequestMapping("signup")
public String signUp(Model model){
   model.addAttribute("user",new User());
   return "signup";
}




<html>
<head>
    <title>Sign Up</title>
</head>
<body>
<form id="user" action="/user/signup" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input id="name" name="name" type="text" value=""/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input id="password" name="password" type="text" value=""/></td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit" value="提交"></button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

1.2 input标签

input标签会被渲染成一个类型为text普通的HTML input标签。通过path属性来绑定的Model中的值。

<form:input path="name"/>

1.3 password标签

password标签会被渲染成一个类型为passoword的普通的HTML。但是它多了一个属性showPassword。表示是否应该显示或遮盖密码。默认为false。

1.4 hidden标签

hidden标签会被渲染成一个类型为hidden的普通input标签。

1.5 textarea标签

textarea标签会被渲染成一个类型为textarea的普通HTML。

1.6 checkbox标签

checkbox标签会被渲染成一个类型为checkbox的普通的HTML。checkbox的属性label作为复选框的值。

  • 绑定boolean属性

当绑定一个boolean值时候,checkbox的状态跟被绑定的boolean数据类型状态是一样的。

@RequestMapping("signup")
public String signUp(Model model) {
    User user = new User();
    user.setRead(true);
    model.addAttribute("user", user);
    return "signup";
}
<td><form:checkbox path="read"/></td>
<td>已经阅读相关协议</td>
  • 绑定列表数据

当checkbox标签的value属性在我们绑定的列表数据中存在时,该checkbox的状态为选中状态。

@RequestMapping("signup")
public String signUp(Model model) {
    User user = new User();
    user.setRead(true);
    List<String> hobyys = new ArrayList<>();
    hobyys.add("健身");
    hobyys.add("写代码");
    hobyys.add("读书");
    user.setHobbys(hobyys);
    model.addAttribute("user", user);
    return "signup";
}
<tr>
<td>兴趣:</td>
<td>
    <form:checkbox path="hobbys" value="健身" label="健身"/>
    <form:checkbox path="hobbys" value="写代码" label="写代码"/>
    <form:checkbox path="hobbys" value="读书" label="读书"/>
</td>
</tr>
<tr>
    <td>兴趣:</td>
    <td>
        <input id="hobbys1" name="hobbys" type="checkbox" value="健身" checked="checked"/><label for="hobbys1">健身</label><input type="hidden" name="_hobbys" value="on"/>
        <input id="hobbys2" name="hobbys" type="checkbox" value="写代码" checked="checked"/><label for="hobbys2">写代码</label><input type="hidden" name="_hobbys" value="on"/>
        <input id="hobbys3" name="hobbys" type="checkbox" value="读书" checked="checked"/><label for="hobbys3">读书</label><input type="hidden" name="_hobbys" value="on"/>
    </td>
</tr>

1.7 checkboxes标签

checkboxes标签会渲染为多个类型为checkbox的普通HTML input 标签

@RequestMapping("signup")
public String signUp(Model model) {
    User user = new User();
    user.setRead(true);
    List<String> hobyys = new ArrayList<>();
    hobyys.add("健身");
    hobyys.add("写代码");
    hobyys.add("读书");
    user.setHobbys(hobyys);

    List<String> allHobyys = new ArrayList<>();
    allHobyys.add("泡妞");
    allHobyys.add("开车");
    allHobyys.add("健身");
    allHobyys.add("写代码");
    allHobyys.add("读书");
    model.addAttribute("user", user);

    model.addAttribute("allHobyys", allHobyys);
    return "signup";
}
<tr>
    <td>兴趣:</td>
    <td>
        <form:checkboxes path="hobbys" items="${allHobyys}"/>
    </td>
</tr>

上面的使用的Array作为数据源。labelyu value的值是一样的。那么需要不一致的时候,则数据源使用Map类型。这时候,Map的Key为checkboxes的value。Map的value对应的label。

当使用Array或者集合作为数据源,里面的元素是一个domain对象的时候,还可以使用标签的itemLabel和itemValue属性表示。

@RequestMapping("signup")
public String signUp(Model model) {
    User user = new User();
    user.setRead(true);

    Department department=new Department(1,"研发部");
    List<Department> departments = new ArrayList<>();
    departments.add(department);
    user.setDepartments(departments);

    List<Department> allDepartments = new ArrayList<>();
    allDepartments.add(department);
    allDepartments.add(new Department(2, "销售部"));
    allDepartments.add(new Department(3, "测试部"));
    allDepartments.add(new Department(4, "财务部"));

    model.addAttribute("user", user);
    model.addAttribute("allDepartments", allDepartments);
    return "signup";
}
<tr>
    <td>部门:</td>
    <td><form:checkboxes path="departments" items="${allDepartments}" itemValue="id" itemLabel="name"/></td>
</tr>

注意,user里面的department必须与allDepartments的对象是同一个对象,才有效。

1.8 radiobutton标签

radiobutton的标签的使用方法与checkbox用法一致。

1.9 radiobuttons标签

radiobuttons的标签的使用方法与checkeboxes用法一致。

user.setSex("女");

List<String> sexList = new ArrayList<>();
sexList.add("男");
sexList.add("女");

model.addAttribute("sexList", sexList);
<form:radiobuttons path="sex" items="${sexList}"/>

1.10 select标签

select 标签会渲染成一个HTML的select 标签。被渲染元素的选项可能来自其item属性的一个Collection、Map、Array。

user.setDepId(1);
allDepartments.add(new Department(1, "研发部"));
allDepartments.add(new Department(2, "销售部"));
allDepartments.add(new Department(3, "测试部"));
allDepartments.add(new Department(4, "财务部"));
<tr>
<td>部门:</td>
<td><form:select path="depId">
    <form:options items="${allDepartments}" itemValue="id" itemLabel="name"/>
</form:select>
</td>
</tr>

1.11 error标签

error标签对应于Spring MVC的Error对象,它的作用是用于显示Error对象中的包含的错误信息。如果Error不为null,则会渲染一个HTML的span元素,用于显示错误信息。

public class UserValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors,"name",null,"用户名不能为空");
        ValidationUtils.rejectIfEmpty(errors,"password",null,"密码不能为空");
    }
}

@InitBinder
public void initBinder(DataBinder binder) {
    binder.setValidator(new UserValidator());
}
@RequestMapping(value = "register", method = RequestMethod.POST)
public String register(@Validated User user, Errors errors) {
    if (errors.hasErrors())
        return "signup";
    return "";
}
<tr>
    <td>用户名:</td>
    <td><form:input path="name"/></td>
    <td><form:errors path="name"/></td>
</tr>