`

基于Spring MVC的Web应用开发(12) - Form

 
阅读更多

本节介绍SpringMVC中的表单,demo演示访问一个表单提交页面,填写表单的内容后使用jQuery的Ajax提交表单,将返回的文本信息显示出来。

记得在Struts1中有个FormBean的东西封装表单内容,在SpringMVC中也有,只不过SpringMVC更松耦合,只要写一个POJO就可以了,而不需要继承框架关联的类,看一下这个FormBean(只列出了主要属性):

 

public class FormBean {
	
	@NotEmpty
	private String name;
	
	@Min(21)
	private int age;

	@DateTimeFormat(iso=ISO.DATE)
	@Past
	private Date birthDate;

	@MaskFormat("(###) ###-####")
	private String phone;

	@NumberFormat(pattern="$###,###.00")
	private BigDecimal currency;

	@NumberFormat(style=Style.PERCENT)
	private BigDecimal percent;
	
	private InquiryType inquiry;
	
	private String inquiryDetails;
	
	private boolean subscribeNewsletter;
	
	private Map<String, String> additionalInfo;
...
}

 

 需要一个Controller,FormController:

 

package org.springframework.samples.mvc.form;

import javax.validation.Valid;

import org.springframework.mvc.extensions.ajax.AjaxUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/form")
@SessionAttributes("formBean")
public class FormController {

	// Invoked on every request

	@ModelAttribute
	public void ajaxAttribute(WebRequest request, Model model) {
		model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));
	}

	// Invoked initially to create the "form" attribute
	// Once created the "form" attribute comes from the HTTP session (see @SessionAttributes)

	@ModelAttribute("formBean")
	public FormBean createFormBean() {
		return new FormBean();
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public void form() {
	}

	@RequestMapping(method=RequestMethod.POST)
	public String processSubmit(@Valid FormBean formBean, BindingResult result, 
								@ModelAttribute("ajaxRequest") boolean ajaxRequest, 
								Model model, RedirectAttributes redirectAttrs) {
		if (result.hasErrors()) {
			return null;
		}
		// Typically you would save to a db and clear the "form" attribute from the session 
		// via SessionStatus.setCompleted(). For the demo we leave it in the session.
		String message = "Form submitted successfully.  Bound " + formBean;
		// Success response handling
		if (ajaxRequest) {
			// prepare model for rendering success message in this request
			model.addAttribute("message", message);
			return null;
		} else {
			// store a success message for rendering on the next request after redirect
			// redirect back to the form to render the success message along with newly bound values
			redirectAttrs.addFlashAttribute("message", message);
			return "redirect:/form";			
		}
	}
	
}

 

 FormController只有一个@RequestMapping,通过GET,POST来区分是访问表单页面(GET),还是提交表单(POST)。在这个类中有:

 

	@ModelAttribute("formBean")
	public FormBean createFormBean() {
		return new FormBean();
	}

 

 它表示访问"http://localhost:8080/web/form/"时,就初始化一个叫formBean名字的属性放在Model中。在类的开头有:

 

@SessionAttributes("formBean")

 

 它表示Model中的这个formBean在session的范围内有效,想一下,session是跟浏览器窗口关联的,窗口关闭,session就失效,所以每次打开一个新的表单页面都会生成一个新的formBean,另外填写完表单内容以POST方式提交后,formBean会根据提交的参数自动设置FormBean的值。

 

	@ModelAttribute
	public void ajaxAttribute(WebRequest request, Model model) {
		model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));
	}

 

 该配置会导致每次访问"http://localhost:8080/web/form/",都会设置一个ajaxRequest值(因为没有象formBean一样设置ajaxRequest的范围,默认的范围为Request级,每次请求都执行)。之前说过填好表单后通过jQuery的Ajax提交表单,通过这个配置,就知道请求是否是Ajax请求。

 

	@RequestMapping(method=RequestMethod.GET)
	public void form() {
	}

访问"http://localhost:8080/web/form/",返回到"webapp/WEB-INF/views/form.jsp"。

 

	@RequestMapping(method=RequestMethod.POST)
	public String processSubmit(@Valid FormBean formBean, BindingResult result, 
								@ModelAttribute("ajaxRequest") boolean ajaxRequest, 
								Model model, RedirectAttributes redirectAttrs) {
		if (result.hasErrors()) {
			return null;
		}
		// Typically you would save to a db and clear the "form" attribute from the session 
		// via SessionStatus.setCompleted(). For the demo we leave it in the session.
		String message = "Form submitted successfully.  Bound " + formBean;
		// Success response handling
		if (ajaxRequest) {
			// prepare model for rendering success message in this request
			model.addAttribute("message", message);
			return null;
		} else {
			// store a success message for rendering on the next request after redirect
			// redirect back to the form to render the success message along with newly bound values
			redirectAttrs.addFlashAttribute("message", message);
			return "redirect:/form";			
		}
	}

processSubmit第一个参数formBean封装了页面提交的表单参数,注意到它前面有一个@Valid,因此有第二个参数BindingResult result, 该参数可以知道表单是否验证通过。第三个参数获取Model中的属性值"ajaxRequest",在方法体中,判断ajaxRequest,如果是,将返回"webapp/WEB-INF/views/form.jsp",如果不是,将它重定向到一个jsp,当然,这个条件在本例子中没有使用到。

 

最后看看非常复杂的form.jsp,该jsp使用了大量的SpringMVC的标签:

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<c:if test="${!ajaxRequest}">
<html>
<head>
	<title>forms | mvc-showcase</title>
	<link href="<c:url value="/resources/form.css" />" rel="stylesheet"  type="text/css" />		
	<script type="text/javascript" src="<c:url value="/resources/jquery/1.6/jquery.js" />"></script>
</head>
<body>
</c:if>
	<div id="formsContent">
		<h2>Forms</h2>
		<p>
			See the <code>org.springframework.samples.mvc.form</code> package for the @Controller code	
		</p>
		<form:form id="form" method="post" modelAttribute="formBean" cssClass="cleanform">
			<div class="header">
		  		<h2>Form</h2>
		  		<c:if test="${not empty message}">
					<div id="message" class="success">${message}</div>	
		  		</c:if>
		  		<s:bind path="*">
		  			<c:if test="${status.error}">
				  		<div id="message" class="error">Form has errors</div>
		  			</c:if>
		  		</s:bind>
			</div>
		  	<fieldset>
		  		<legend>Personal Info</legend>
		  		<form:label path="name">
		  			Name <form:errors path="name" cssClass="error" />
		 		</form:label>
		  		<form:input path="name" />
	
		  		<form:label path="age">
		  			Age <form:errors path="age" cssClass="error" />
		 		</form:label>
		  		<form:input path="age" />
		  		
		  		<form:label path="birthDate">
		  			Birth Date (in form yyyy-mm-dd) <form:errors path="birthDate" cssClass="error" />
		 		</form:label>
		  		<form:input path="birthDate" />
		  		 
		  		<form:label path="phone">
		  			Phone (in form (###) ###-####) <form:errors path="phone" cssClass="error" />
		  		</form:label>
		  		<form:input path="phone" />
	
		  		<form:label path="currency">
		  			Currency (in form $#.##) <form:errors path="currency" cssClass="error" />
		  		</form:label>
		  		<form:input path="currency" />
	
		  		<form:label path="percent">
		  			Percentage (in form ##%) <form:errors path="percent" cssClass="error" />
		  		</form:label>
		  		<form:input path="percent" />
	
		  	</fieldset>
	
			<fieldset>
				<legend>Inquiry</legend>
				<form:label path="inquiry">
					Type (select one)
				</form:label>
				<form:select path="inquiry">
					<form:option value="comment">Comment</form:option>
					<form:option value="feedback">Feedback</form:option>
					<form:option value="suggestion">Suggestion</form:option>
				</form:select>
				
		  		<form:label path="inquiryDetails">
		  			Details
		  		</form:label>
		  		<form:textarea path="inquiryDetails" />
		  	</fieldset>
	
			<fieldset class="checkbox">
				<legend>Request Additional Info</legend>
				<label><form:checkbox path="additionalInfo[mvc]" value="true" />on Spring MVC</label>
				<label><form:checkbox path="additionalInfo[java]" value="true" />on Java (4-ever)</label>				
			</fieldset>
		  		  	
			<fieldset class="radio">
				<legend>Subscribe to Newsletter?</legend>
				<label><form:radiobutton path="subscribeNewsletter" value="true" />Yes</label>
				<label><form:radiobutton path="subscribeNewsletter" value="false" /> No</label>
			</fieldset>
	
			<p><button type="submit">Submit</button></p>
		</form:form>
		<script type="text/javascript">
			$(document).ready(function() {
				$("#form").submit(function() {  
					$.post($(this).attr("action"), $(this).serialize(), function(html) {
						$("#formsContent").replaceWith(html);
						$('html, body').animate({ scrollTop: $("#message").offset().top }, 500);
					});
					return false;  
				});			
			});
		</script>
	</div>
<c:if test="${!ajaxRequest}">
</body>
</html>
</c:if>
 

 

 

 

分享到:
评论

相关推荐

    Ajax-Spring-MVC-CRUD-form-submit-and-ajax.zip

    Ajax-Spring-MVC-CRUD-form-submit-and-ajax.zip,spring mvc crud应用程序(springmvc、hibernate 4.x、bootstrap 3.x、jquery、mysql),ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json...

    Spring.MVC.A.Tutorial.2nd.Edition.1771970316

    This is a tutorial on Spring MVC, a module in the Spring Framework for rapidly developing web applications. The MVC in Spring MVC stands for Model-View-Controller, a design pattern widely used in ...

    Spring web MVC和spring 2.0 form tag解说

    Spring web MVC和spring 2.0 form tag的解说,里面的内容可以当作平时的工具书查看

    一个简单的spring mvc实例.docx

    基于 Spring 的 Web 应用程序接收到 http://localhost:8080/hello.do(事实上请求路径是 /hello.do) 的请求后, Spring 将这个请求交给一个名为 helloController 的程序进行处理, helloController 再调用 一个名为 ...

    org.springframework.web.servlet-3.1.0.RELEASE

    是源代码,不是jar文件!!!!! /** * Holder for both Model and View in the web MVC framework. * Note that these are entirely ... * @see org.springframework.web.servlet.mvc.Controller#handleRequest */

    Pivotal Certified Spring Web Application Developer Exam(Apress,2015)

    Spring MVC programming model essentials, Spring MVC views and form processing, Spring Web Flow essentials, and Spring Web Flow actions and configuration. The Pivotal Certified Spring Web Application ...

    开源WEB框架-Portal-Basic使用手册

    Portal-Basic Java Web应用开发框架(简称 Portal-Basic)是一套功能完备的高性能Full-Stack Web应用开发框架,内置稳定高效的MVC基础架构和DAO框架(已内置Hibernate、MyBatis和JDBC支持),集成 Action拦截、Form ...

    spring-tags.zip

    在做springmvc开发时,使用spring的tag较为方便, 部署时容易出现tld文件缺失的问题。本文件是spring-tag的tld文件,文件可以在spring-webmvc.jar的META-INF中获取,放到web项目WEB-INF即可

    Toyota-Projesi:Spring Mvc Web项目

    Spring Mvc Web项目 为什么要这个项目? 首先,我要感谢我的老师莱文·埃尔古德(LeventErgüder)在这个项目中给予我的训练和努力。 这个项目是我的第一个Spring项目,为了创建这个项目,它不是我以前一直按照自己...

    Spring-Reference_zh_CN(Spring中文参考手册)

    13.1.2. Spring Web MVC框架的特点 13.2. DispatcherServlet 13.3. 控制器 13.3.1. AbstractController 和 WebContentGenerator 13.3.2. 其它的简单控制器 13.3.3. MultiActionController 13.3.4. 命令控制器 13.4. ...

    spring_MVC源码

    14. &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&gt; 15. 16. &lt;!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --&gt; 17. &lt;bean class="org....

    JessMA Java Web 应用开发框架 (v3.2.2-20130815).pdf

    JessMA Java MVC & REST应用开发框架(简称 JessMA)是一套功能完备的高性能Full-Stack Web应用开发框架,内置稳定高效的MVC基础架构和DAO框架(已内置Hibernate、MyBatis和JDBC支持),集成 Action拦截、Form Bean ...

    Spring 2.0 开发参考手册

    13.1.2. Spring Web MVC框架的特点 13.2. DispatcherServlet 13.3. 控制器 13.3.1. AbstractController 和 WebContentGenerator 13.3.2. 其它的简单控制器 13.3.3. MultiActionController 13.3.4. 命令控制器 ...

    spring security 参考手册中文版

    12. Spring MVC测试集成 104 12.1设置MockMvc和Spring Security 104 12.2 SecurityMockMvcRequestPostProcessors 105 12.2.1使用CSRF保护进行测试 105 12.2.2在Spring MVC测试中以用户身份运行测试 106 12.2.3使用...

    Spring.Essentials.178398

    Build lightning-fast web applications and REST APIs using Spring MVC and its asynchronous processing capabilities with the view technologies of your choice Explore simplified but powerful data access ...

    SpringMVC实现文件上传.docx

    文件上传是Web应用程序中常见的功能之一,Spring MVC提供了方便的机制来处理文件上传。下面是关于Spring MVC实现文件上传的详细描述: Spring MVC文件上传的实现步骤如下: 准备MultipartResolver: 在Spring MVC...

    spring2.0技术手册

    《Spring 2.0技术手册》内容全面深入,主要包括Spring入门、Bean/消息/事件、Spring AOP、JDBC/事物支持、Spring与Hibernate的整合、Spring Web MVC框架、View层方案/Web框架整合、API封装、Spring在线书签完整...

    spring chm文档

    13.1.2. Spring Web MVC框架的特点 13.2. DispatcherServlet 13.3. 控制器 13.3.1. AbstractController 和 WebContentGenerator 13.3.2. 其它的简单控制器 13.3.3. MultiActionController 13.3.4. 命令控制器 ...

    Spring2.0技术手册

    \r\n 本书内容全面深入,主要包括Spring入门、Bean/消息/事件、Spring AOP、JDBC/事物支持、Spring与Hibernate的整合、Spring Web MVC框架、View 层方案/Web框架整合、API封装、Spring在线书签完整项目示例等内容。

    Spring-MVC技术体系介绍(二)

    强大而直接的配置方式:将框架类和应用程序类都能作为JavaBean配置,支持跨多个context的引用,例如,在web控制器中对业务对象和验证器(validator)的引用。 可适配、非侵入:可以根据不同的应用场景,选择合适的...

Global site tag (gtag.js) - Google Analytics