Spring MVC下拉框示例

在Spring MVC中,表单标签– <form:select /><form:option /><form:options />用于呈现HTML下拉框。 请参阅以下示例:

//SimpleFormController
protected Map referenceData(HttpServletRequest request) throws Exception {
	Map referenceData = new HashMap();
	Map<String,String> country = new LinkedHashMap<String,String>();
	country.put("US", "United Stated");
	country.put("CHINA", "China");
	country.put("SG", "Singapore");
	country.put("MY", "Malaysia");
	referenceData.put("countryList", country);
}

1. <form:select />

用$ {countryList}生成一个保管箱。

<form:select path="country" items="${countryList}" />

HTML代码

<select id="country" name="country">
   <option value="US">United Stated</option>
   <option value="CHINA">China</option>
   <option value="SG">Singapore</option>
   <option value="MY">Malaysia</option>
</select>

2. <form:options />

<form:options />必须包含在select标记中。

<form:select path="country">
    <form:options items="${countryList}" />
</form:select>

HTML代码

<select id="country" name="country">
   <option value="US">United Stated</option>
   <option value="CHINA">China</option>
   <option value="SG">Singapore</option>
   <option value="MY">Malaysia</option>
</select>

3. <form:option />

<form:option />也必须包含在select标记中,并呈现单个select选项,请参见以下组合。

<form:select path="country">
   <form:option value="NONE" label="--- Select ---"/>
   <form:options items="${countryList}" />
</form:select>

HTML代码

<select id="country" name="country">
   <option value="NONE">--- Select ---</option> 
   <option value="US">United Stated</option>
   <option value="CHINA">China</option>
   <option value="SG">Singapore</option>
   <option value="MY">Malaysia</option>
</select>

4.清单框

要渲染列表框,只需在select标签中添加“ multiple = true ”属性。

<form:select path="country" items="${countryList}" multiple="true" />

HTML代码 ,具有用于处理国家/地区选择的隐藏值。

<select id="country" name="country" multiple="multiple"> 
    <option value="US">United Stated</option>
    <option value="CHINA">China</option>
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option> 
</select>
<input type="hidden" name="_country" value="1"/>

选择一个下拉框值
对于下拉框,列表框或“选择”选项,只要“ 路径 ”或“ 属性 ”等于“ 选择选项键值 ”,就会自动选择这些选项。

完整下拉框示例

我们来看一个完整的Spring MVC下拉框示例:

1.型号

用于存储下拉框值的客户模型类。

文件:Customer.java

package com.mkyong.customer.model;

public class Customer{

	String country;
	String javaSkills;
	
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public String getJavaSkills() {
		return javaSkills;
	}
	public void setJavaSkills(String javaSkills) {
		this.javaSkills = javaSkills;
	}	
}

2.控制器

一个用于处理表单下拉框值的SimpleFormController 。 将Java技能的“ Spring ”作为默认下拉框的选定值。

文件:DropDownBoxController.java

package com.mkyong.customer.controller;

import java.util.HashMap;
import java.util.LinkedHashMap;
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 DropDownBoxController extends SimpleFormController{
	
	public DropDownBoxController(){
		setCommandClass(Customer.class);
		setCommandName("customerForm");
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
		throws Exception {
		
		Customer cust = new Customer();
		
		//make "Spring" as the default java skills selection
		cust.setJavaSkills("Spring");
		
		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);
	
	}
	
	protected Map referenceData(HttpServletRequest request) throws Exception {
		
		Map referenceData = new HashMap();
		
		Map<String,String> country = new LinkedHashMap<String,String>();
		country.put("US", "United Stated");
		country.put("CHINA", "China");
		country.put("SG", "Singapore");
		country.put("MY", "Malaysia");
		referenceData.put("countryList", country);
		
		Map<String,String> javaSkill = new LinkedHashMap<String,String>();
		javaSkill.put("Hibernate", "Hibernate");
		javaSkill.put("Spring", "Spring");
		javaSkill.put("Apache Wicket", "Apache Wicket");
		javaSkill.put("Struts", "Struts");
		referenceData.put("javaSkillsList", javaSkill);
		
		return referenceData;
	}
}

3.验证者

一个简单的表单验证器,以确保选中“ 国家 ”和“ javaSkills ”下拉框。

文件:DropDownBoxValidator.java

package com.mkyong.customer.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.mkyong.customer.model.Customer;

public class DropDownBoxValidator 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;
	
	   ValidationUtils.rejectIfEmptyOrWhitespace(errors, "javaSkills", "required.javaSkills");
		
	   if("NONE".equals(cust.getCountry())){
		errors.rejectValue("country", "required.country");
	   }
	}
}

文件:message.properties

required.country = Please select a country!
required.javaSkills = Please select a java Skill!

4.查看

一个JSP页面,显示Spring的表单标签<form:select /><form:option /><form:options />的用法。

文件: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 select, option, options example</h2>

	<form:form method="POST" commandName="customerForm">
		<form:errors path="*" cssClass="errorblock" element="div" />
		<table>

			<tr>
				<td>Country :</td>
				<td><form:select path="country">
					  <form:option value="NONE" label="--- Select ---" />
					  <form:options items="${countryList}" />
				       </form:select>
                                </td>
				<td><form:errors path="country" cssClass="error" /></td>
			</tr>
			<tr>
				<td>Java Skills :</td>
				<td><form:select path="javaSkills" items="${javaSkillsList}"
					multiple="true" /></td>
				<td><form:errors path="javaSkills" cssClass="error" /></td>
			</tr>

			<tr>
				<td colspan="3"><input type="submit" /></td>
			</tr>
		</table>
	</form:form>

</body>
</html>

使用JSTL显示提交的值。

文件:CustomerSuccess.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<body>
	<h2>Spring's form select, option, options example</h2>

	Country : ${customer.country}
	<br /> Java Skills : ${customer.javaSkills}
	<br />

</body>
</html>

5. Spring Bean配置

全部链接〜

<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.DropDownBoxController">
		<property name="formView" value="CustomerForm" />
		<property name="successView" value="CustomerSuccess" />

		<!-- Map a validator -->
		<property name="validator">
			<bean class="com.mkyong.customer.validator.DropDownBoxValidator" />
		</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.演示

访问页面– http:// localhost:8080 / SpringMVCForm / dropdownbox.htm

SpringMVC-DropDownBox-Example-1

如果用户在提交表单时未选择任何下拉框值,则显示并突出显示错误消息。

SpringMVC-DropDownBox-Example-2

如果表单提交成功,则只显示提交的下拉框值。

SpringMVC-DropDownBox-Example-3

下载源代码

下载它– SpringMVCForm-DropDownBox-Example.zip (10KB)

翻译自: https://mkyong.com/spring-mvc/spring-mvc-dropdown-box-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值