In Spring MVC, <form:checkbox /> is used to render a HTML checkbox field, the checkbox values are hard-coded inside the JSP page; While the <form:checkboxes /> is used to render multiple checkboxes, the checkbox values are generated at runtime.

In this tutorial, we show you 3 different ways of render HTML checkbox fields:

1. <form:checkbox /> – Single Checkbox

Generate a classic single checkbox, with a boolean value.

public class Customer{
boolean receiveNewsletter;
//...
}
<form:checkbox path="receiveNewsletter" />
Checked by default…
If you set the “receiveNewsletter” boolean value to true, this checkbox will be checked. For example :

public class Customer{
boolean receiveNewsletter = true;
//...
}
 

2. <form:checkbox /> – Multiple Checkboxes

Generate multiple checkboxes and hard-coded the value.

public class Customer{
String [] favLanguages;
//...
}
<form:checkbox path="favLanguages" value="Java"/>Java
<form:checkbox path="favLanguages" value="C++"/>C++
<form:checkbox path="favLanguages" value=".Net"/>.Net
Checked by default…
If you want to make the checkbox with value “Java” is checked by default, you can initialize the “favLanguages” property with value “Java”. For example :

        //SimpleFormController...
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
 
Customer cust = new Customer();
cust.setFavLanguages(new String []{"Java"});
 
return cust;
 
}

3. <form:checkboxes /> – Multiple Checkboxes

Generate a runtime list for the checkboxes value, and link it to Spring’s form tag <form:checkboxes>.

        //SimpleFormController...
protected Map referenceData(HttpServletRequest request) throws Exception {
 
Map referenceData = new HashMap();
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
referenceData.put("webFrameworkList", webFrameworkList);
 
return referenceData;
}
<form:checkboxes items="${webFrameworkList}" path="favFramework" />
Checked by default…
If you want to make 2 checkboxes with value “Spring MVC” and “Struts 2″ are checked by default, you can initialize the “favFramework” property with value “Spring MVC” and “Struts 2″. Fro example :

         //SimpleFormController...
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
 
Customer cust = new Customer();
cust.setFavFramework(new String []{"Spring MVC","Struts 2"});
 
return cust;
}
Note

<form:checkboxes items="${dynamic-list}" path="property-to-store" />

For multiple checkboxes, as long as the “path” or “property” value is equal to any of the “checkbox values – ${dynamic-list}“, the matched checkbox will be checked automatically.

Full checkbox example

Let’s go thought a complete Spring MVC checkbox example :

1. Model

A customer model class to store the checkbox value.

File : Customer.java

package com.mkyong.customer.model;
 
public class Customer{
 
//checkbox
boolean receiveNewsletter = true; //checked it
String [] favLanguages;
String [] favFramework;
 
public String[] getFavFramework() {
return favFramework;
}
public void setFavFramework(String[] favFramework) {
this.favFramework = favFramework;
}
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getFavLanguages() {
return favLanguages;
}
public void setFavLanguages(String[] favLanguages) {
this.favLanguages = favLanguages;
}
}

2. Controller

A SimpleFormController to handle the form checkbox value.

File : CheckBoxController.java

package com.mkyong.customer.controller;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.mkyong.customer.model.Customer;
 
public class CheckBoxController extends SimpleFormController{
 
public CheckBoxController(){
setCommandClass(Customer.class);
setCommandName("customerForm");
}
 
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
 
Customer cust = new Customer();
 
//Make "Spring MVC" and "Struts 2" as default checked value
cust.setFavFramework(new String []{"Spring MVC","Struts 2"});
 
//Make "Java" as default checked value
cust.setFavLanguages(new String []{"Java"});
 
return cust;
 
}
 
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
 
Customer customer = (Customer)command;
return new ModelAndView("CustomerSuccess","customer",customer);
 
}
 
//Generate the data for web framework multiple checkboxes
protected Map referenceData(HttpServletRequest request) throws Exception {
 
Map referenceData = new HashMap();
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
referenceData.put("webFrameworkList", webFrameworkList);
 
return referenceData;
 
}
}

3. Validator

A simple form validator make sure the “favLanguages” property is not empty.

File : CheckBoxValidator.java

package com.mkyong.customer.validator;
 
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.mkyong.customer.model.Customer;
 
public class CheckBoxValidator implements Validator{
 
@Override
public boolean supports(Class clazz) {
//just validate the Customer instances
return Customer.class.isAssignableFrom(clazz);
}
 
@Override
public void validate(Object target, Errors errors) {
 
Customer cust = (Customer)target;
 
if(cust.getFavLanguages().length==0){
errors.rejectValue("favLanguages", "required.favLanguages");
}
}
}

File : message.properties

required.favLanguages = Please select at least a favorite programming language!

4. View

A JSP page to show the use of Spring’s form tag <form:checkbox /> and <form:checkboxes />.

File : CustomerForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
color: #ff0000;
}
 
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
 
<body>
<h2>Spring's form checkbox example</h2>
 
<form:form method="POST" commandName="customerForm">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td>Subscribe to newsletter? :</td>
<td><form:checkbox path="receiveNewsletter" /></td>
<td><form:errors path="receiveNewsletter" cssClass="error" /></td>
</tr>
<tr>
<td>Favourite Languages :</td>
<td>
<form:checkbox path="favLanguages" value="Java" />Java
<form:checkbox path="favLanguages" value="C++" />C++
<form:checkbox path="favLanguages" value=".Net" />.Net
</td>
<td><form:errors path="favLanguages" cssClass="error" />
</td>
</tr>
<tr>
<td>Favourite Web Frameworks :</td>
<td><form:checkboxes items="${webFrameworkList}"
path="favFramework" /></td>
<td><form:errors path="favFramework" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
 
</body>
</html>

Use JSTL to loop over the submitted checkboxes value, and display it.

File : CustomerSuccess.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 
<html>
<body>
<h2>Spring's form checkbox example</h2>
 
Receive Newsletter : ${customer.receiveNewsletter}
<br />
 
Favourite Languages :
<c:forEach items="${customer.favLanguages}" var="current">
[<c:out value="${current}" />]
</c:forEach>
<br />
 
Favourite Web Frameworks :
<c:forEach items="${customer.favFramework}" var="current">
[<c:out value="${current}" />]
</c:forEach>
<br />
</body>
</html>

5. Spring Bean Configuration

Link it all ~

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
 
<bean class="com.mkyong.customer.controller.CheckBoxController">
<property name="formView" value="CustomerForm" />
<property name="successView" value="CustomerSuccess" />
 
<!-- Map a validator -->
<property name="validator">
<bean class="com.mkyong.customer.validator.CheckBoxValidator" />
</property>
</bean>
 
<!-- Register the Customer.properties -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message" />
</bean>
 
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
 
</beans>

6. Demo

Access the page – http://localhost:8080/SpringMVCForm/checkbox.htm

If the user did not select any language checkboxes value while submitting the form, display and highlight the error message.

If the form is submitted successfully, just display the submitted checkboxes value.

Spring MVC Checkbox And Checkboxes Example的更多相关文章

  1. Spring MVC遭遇checkbox的问题解决方式

    Spring MVC遭遇checkbox的问题是:当checkbox全不选时候,则该checkbox域的变量为null,不能动态绑定到spring的controller方法的入參上,并抛出异常. 解决 ...

  2. Spring MVC遭遇checkbox的问题解决方案

    转:http://lavasoft.blog.51cto.com/62575/1407213 Spring MVC遭遇checkbox的问题是:当checkbox全不选时候,则该checkbox域的变 ...

  3. Spring MVC 学习总结(四)——视图与综合示例

    一.表单标签库 1.1.简介 从Spring2.0起就提供了一组全面的自动数据绑定标签来处理表单元素.生成的标签兼容HTML 4.01与XHTML 1.0.表单标签库中包含了可以用在JSP页面中渲染H ...

  4. spring mvc:复选框(多选)

    以user为例,user下有 username用户,password密码, address地址, receivePaper是否订阅, favotireFramework兴趣爱好, user.java ...

  5. spring mvc:常用标签库(文本框,密码框,文本域,复选框,单选按钮,下拉框隐藏于,上传文件等)

    在jsp页面需要引入:<%@taglib uri="http://www.springframework.org/tags/form" prefix="form&q ...

  6. 视图框架:Spring MVC 4.0(1)

    目录 一.表单标签库 1.1.简介 1.2.常用属性 1.3.form标签与input标签 1.4.checkbox标签 1.5.radiobutton标签 1.6.password标签 1.7.se ...

  7. Spring MVC列表多选框

    以下示例显示如何在使用Spring Web MVC框架的表单中使用列表框(Listbox).首先使用Eclipse IDE来创建一个WEB工程,实现一个让用户可选择自己所善长的技术(多选)的功能.并按 ...

  8. Spring MVC下拉选项(Select)

    以下示例显示如何在使用Spring Web MVC框架的表单中使用下拉选项(Dropdown).首先使用Eclipse IDE来创建一个WEB工程,实现一个让用户可选择自己所在的国家的功能.并按照以下 ...

  9. Spring MVC多项单选按钮

    以下示例显示如何在使用Spring Web MVC框架的表单中使用多选按钮(RadioButton).首先使用Eclipse IDE来创建一个WEB工程,实现一个让用户可选择自己喜欢的数字的功能.并按 ...

随机推荐

  1. PHP学习笔记 - 入门篇(4)

    PHP学习笔记 - 入门篇(4) 什么是运算符 PHP运算符一般分为算术运算符.赋值运算符.比较运算符.三元运算符.逻辑运算符.字符串连接运算符.错误控制运算符. PHP中的算术运算符 算术运算符主要 ...

  2. (转)设置Win7防火墙规则 顺畅访问局域网

    在Windows 7系统的电脑上搭建WAMP环境后,发现在局域网中其他电脑不能访问.有朋友告诉小强,这可能是因为当时Windows 7自带的防火墙屏蔽了80端口,只需要重新设置规则就可以了. 点击Wi ...

  3. 谈谈css中的before和after

    css中的伪元素before和after,其实有很多小的妙用. 一.基础用法 w3c中的基础用法:用来给元素的内容前面(对应:before)或者后面(对应:after)插入新内容. <p> ...

  4. oracle经典操作sql

    分页: SELECT * FROM ( SELECT A.*, ROWNUM RN FROM (SELECT * FROM TABLE_NAME) A WHERE ROWNUM <= 40)WH ...

  5. java计时器

    //用于计时,要求xx秒后开始发送短信,短信之间间隔xx秒 public static Date dateOperateBySecond(Date date,int second){ Calendar ...

  6. C++ 的template

    vector的标准模板是:template<template<typename X, class allocator<X> > class T>而普通模板则是tem ...

  7. OD常用断点

    OD常用断点 很全很全 常用断点 拦截窗口: bp CreateWindow 创建窗口 bp CreateWindowEx(A) 创建窗口 bp ShowWindow 显示窗口 bp UpdateWi ...

  8. ThinkPHP3.2 加载过程(二)

    回顾: 上次介绍了 ThinkPHP 的 Index.PHP入口文件.但只是TP的入口前面的入口(刷boss总是要过好几关才能让你看到 ,不然boss都没面子啊),从Index.PHP最后一行把我们引 ...

  9. mysql查询区分大小写与自定义排序

    mysql查询区分大小写: SELECT id,developer FROM products WHERE developer != '' and developer = binary('LYNN') ...

  10. (转)[Erlang 0080] RabbitMQ :VHost,Exchanges, Queues,Bindings and Channels

    和RabbitMQ这个项目的缘分好奇怪,很长一段时间内是只关注源代码,真的是Erlang开源项目中的典范;现在要在项目中应用RabbitMQ,从新的视角切入,全新的感觉.仿佛旧情人换了新衣,虽是熟稔却 ...