Spring MVC Checkbox And Checkboxes Example

자바 스프링 mvc 체크박스 샘플

Spring MVC Checkbox And Checkboxes Example

 
 

In this example, we will learn how to create checkbox in a Simple Spring MVC Form using Spring tag library. We will learn how to use the <form:checkbox> and <form:checkboxes> and the difference between those two. Here we will create a Spring MVC form with a checkbox through which we will get the users favoritesport and we will add validation support to check if the user is selecting at-least 1 checkbox.

In Spring MVC we will use <form:checkboxes> tag to render multiple check boxes

<form:checkboxes items="${favouriteList}" path="favourite"/>

Which produces the below HTML code.

 <span><input id="favourite1" name="favourite" type="checkbox" value="Football"/><label for="favourite1">Football</label></span>
<span><input id="favourite2" name="favourite" type="checkbox" value="Cricket"/><label for="favourite2">Cricket</label></span>
<span><input id="favourite3" name="favourite" type="checkbox" value="Hockey"/><label for="favourite3">Hockey</label></span>

Folder Structure :

  1. Create a Dynamic Web Project SpringMVCFormHandling and create a package for our src files com.javainterviewpoint
  2. Place the Spring 3 jar files under WEB-INF/Lib 

    commons-logging-1.1.1.jar
    log4j-1.2.16.jar
    slf4j-api-1.7.5.jar
    slf4j-log4j12-1.7.5.jar
    hibernate-validator-4.2.0.Final.jar
    spring-aspects-3.2.4.RELEASE.jar
    spring-beans-3.2.4.RELEASE.jar
    spring-context-3.2.4.RELEASE.jar
    spring-core-3.2.4.RELEASE.jar
    spring-expression-3.2.4.RELEASE.jar
    spring-web-3.2.4.RELEASE.jar
    spring-webmvc-3.2.4.RELEASE.jar
    validation-api-1.1.0.Final.jar
    jstl-1.1.2.jar

  3. Create the Java classes Checkbox_Controller.java and CheckboxBean.java under com.javainterviewpoint folder.
  4. Place the SpringConfig-servlet.xml and web.xml  under the WEB-INF directory
  5. View files SpringMVC_CheckboxExample.jsp and checkbox_Success.jsp are put under the sub directory under WEB-INF/Jsp

Controller

Checkbox_Controller.java

  • The DispatcherServlet mapping which we make in the web.xml will delegate the all the request to our Checkbox_Controller as we have annotated it with @Controller annotation.
  • We use the @RequestMapping annotation to map each of the requests which we get to individual methods. Our controller has three methods getFavouriteSports(),initializeForm() and  processForm()
  • The getFavouriteSports() method returns a list of sports which will be used by view for populating the favorite sports checkboxes.
  • The initializeForm() will take the user to the “SpringMVC_CheckboxExample” which is our view component with form backing object CheckboxBean.
  •  The processForm() method will get called when the user submits the form. The CheckboxBean object “cb”  will be validated as we have annotated it with @Valid annotationand the validation results will be added to the BindingResult. Based on the result we will re-direct the user back to the “SpringMVC_CheckboxExample” or “checkbox_Success” page.

Now lets see the difference between <form:checkbox> and <form:checkboxes>

If we use <form:checkbox> then we have to hard-code each value for example

<form:checkbox path="favourite" value="Football"/>Football
<form:checkbox path="favourite" value="Cricket"/>Cricket
<form:checkbox path="favourite" value="Hockey"/>Hockey

Where as when we use <form:checkboxes> we can dynamically pass in a list to populate the checkboxes.

 
<form:checkboxes items="${favouriteList}" path="favourite"/>

Here we have passed in a list “favouriteList” which gets the value from the controller class.

package com.javainterviewpoint;

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

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class Checkbox_Controller 
{
	ModelAndView mav = null;
	@ModelAttribute("favouriteList")
	public List getFavouriteSports()
	{
		List favouriteList = new ArrayList();
		favouriteList.add("Football");
		favouriteList.add("Cricket");
		favouriteList.add("Hockey");
		return favouriteList;
	}
	
	@RequestMapping("/CheckboxExample")
	public String initializeForm(Map model)
	{
		CheckboxBean cb = new CheckboxBean();
		model.put("cb",cb);
		return "SpringMVC_CheckboxExample";
		
	}
	@RequestMapping("/processCheckbox")
	public String processForm(@Valid @ModelAttribute("cb") CheckboxBean cb,BindingResult result)
	{
		if(result.hasErrors())
		{
			System.out.println("Validation Failed");
			
			System.out.println(">>>>"+cb.getFavourite());
			return "SpringMVC_CheckboxExample";
		}
		else
		{
			System.out.println("Validated Successfully");
			System.out.println(">>>>"+cb.getFavourite());
			return "checkbox_Success";
		}
	}
}

Model

CheckboxBean.java

Here CheckboxBean acts as a Model which has a favorite property. We have added the annotation @NotEmpty to validate if the user has at least selected one of his favorite sports. The custom validation messages are added in the props.properties file.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

package com.javainterviewpoint;

import java.util.List;

import org.hibernate.validator.constraints.NotEmpty;

public class CheckboxBean 
{
	@NotEmpty
	private List favourite;

	
	public List getFavourite() {
		return favourite;
	}

	public void setFavourite(List favourite) {
		this.favourite = favourite;
	}
}

View

SpringMVC_CheckboxExample.jsp

Our view component has multiple checkboxes generated using the Spring form tag library. The checkboxes gets its value from our controller class. @ModelAttribute(“favouriteList”) of our controller will be called and it will return a list of favourite sports when  <form:checkboxes items=”${favouriteList}” path=”favourite”/>  is called.<form:errors> tag displays the error message which occurs during the validation

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
<style>
.error {
 color: #ff0000;
}
 
.commonerrorblock {
 color: #000;
 background-color: #ffEEEE;
 border: 3px solid #ff0000;
 
}
</style>
</head>
<body>
 <form:form method="post" action="processCheckbox" commandName="cb">
 <form:errors path="*" element="div" cssClass="commonerrorblock"/>
 <table>
 <tr>
 <td>Favourite Sports</td>
 <td>
 <form:checkboxes items="${favouriteList}" path="favourite"/>
 </td>
 <td>
 <form:errors path="favourite" cssStyle="error"/>
 </td>
 </tr>
 <tr>
 <td></td><td><input type="submit"></td>
 </tr>
 </table>
 </form:form>
</body>
</html>

props.properties

NotEmpty.cb.favourite = Please select atleast on sports!!

checkbox_Success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
 <%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Favourite Sports selected : 
 <c:forEach items="${cb.favourite}" var="fav">
 <p><c:out value="${fav}"></c:out></p>
 </c:forEach>
</body>
</html>

Configurations

web.xml

The web.xml has everything about the application that a server needs to know, which is placed under the WEB-INF directory. <servlet-name> contains the name of the SpringConfiguration, when the DispatcherServlet is initialized the framework will try to load a configuration file [servlet-name]-servlet.xml” under the WEB-INF directory.

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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">
	<display-name>SpringMVCFormHandling</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>SpringConfig</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringConfig</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

SpringConfig-servlet.xml

  • The SpringConfig-servlet.xml is also placed under the WEB-INF directory.
  • <context:component-scan> will let the Spring Container to search for all the annotation under the package “com.javainteriviewpoint”. 
  • <mvc:annotation-driven/> annotation will activate the @Controller, @RequestMapping, @Validetc annotations.
  • The view is resolved through “org.springframework.web.servlet.view.InternalResourceViewResolver” which searches for the jsp files under the /WEB-INF/Jsp/ directory.
  • Resource Bundle is accessed through the “org.springframework.context.support.ResourceBundleMessageSource”  through its property “basename” which has the value “props”and hence our property file should “props.properties”
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd
 	http://www.springframework.org/schema/context	http://www.springframework.org/schema/context/spring-context-3.0.xsd
 	http://www.springframework.org/schema/mvc	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="com.javainterviewpoint" />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/Jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="props"></property>
	</bean>
</beans>

Lets run our application

Now lets run our application, do a clean build and deploy the application in the Server

Hit on the url “http://localhost:8080/SpringMVCFormHandling/CheckboxExample”

SpringMVC_CheckBoxExample

Submit the form without selecting any checkbox

SpringMVC_CheckBoxExample_Validation

Upon successful validation, success page will be rendered to the user

SpringMVC_CheckBoxExample_Success

[출처] http://www.javainterviewpoint.com/spring-mvc-checkbox-checkboxes-example/

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
106 Spring MVC Dropdown Box Example file 졸리운_곰 2018.03.26 188
105 SpringBoot JPA 예제 졸리운_곰 2018.03.13 304
104 스프링 CKEditor 적용 - 에디터 졸리운_곰 2018.03.07 2555
103 spring ckeditor 파일업로드 예제 (file upload) file 졸리운_곰 2018.03.07 1996
102 CKEditor 사용 및 파일 업로드 적용 졸리운_곰 2018.03.07 119
» Spring MVC Checkbox And Checkboxes Example 자바 스프링 mvc 체크박스 샘플 file 졸리운_곰 2018.03.07 50
100 SPRING MVC - CHECKBOXES EXAMPLE 자바 스프링 mvc 체크박스 예제 file 졸리운_곰 2018.03.07 147
99 Spring MVC Dropdown Box Example 스프링 웹 개발 [콤보 선택 박스] file 졸리운_곰 2018.03.07 217
98 SPRING과 ANGULAR2 연동해서 실행하기 file 졸리운_곰 2018.02.12 163
97 두번째, 스프링 배치보다 간편한 스프링 Quartz 졸리운_곰 2018.02.08 74
96 첫번째, 스프링 배치보다 간편한 스프링 Quartz 졸리운_곰 2018.02.08 72
95 JAVA] Quartz (쿼츠)를 사용하여 자바 스케줄링(scheduling) 하기 졸리운_곰 2018.02.08 577
94 Spring Batch를 이용한 기본적인 Batch Application 졸리운_곰 2018.02.08 43
93 Quartz + Spring Batch 조합하기 file 졸리운_곰 2018.02.08 1931
92 스프링 web MVC와 앵귤러의 통합 How to configure AngularJs with Spring MVC | SpringBoot file 졸리운_곰 2018.01.28 156
91 스프링 부트와 앵귤러의 통합 : Spring Boot and AngularJS Integration Tutorial file 졸리운_곰 2018.01.28 451
90 mybatis에서 selectKey 사용법 졸리운_곰 2018.01.24 352
89 Spring form:form 태그 설명 졸리운_곰 2018.01.24 158
88 java spring form 태그 졸리운_곰 2018.01.24 114
87 Spring MVC - 값 전달 file 졸리운_곰 2018.01.24 39
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED