- 浏览: 268334 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
hongxingyaru_d5b032:
但是其中“这个Accept和Request Headers中的 ...
基于Spring MVC的Web应用开发(7) - Headers -
hongxingyaru_d5b032:
学习到了,感谢分享!
基于Spring MVC的Web应用开发(7) - Headers -
bo_hai:
总结的不错。
基于Spring MVC的Web应用开发(7) - Headers -
fendou3754:
那你也说一下spring-asm重新打包以后的源码怎么获取,尽 ...
spring将spring-asm重新打包原因 -
di1984HIT:
谢谢啊~学习了~~
JMS、AMQP实例讲解
本节介绍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>
发表评论
-
《Pro Spring Integration》读书笔记
2012-06-02 11:30 0a -
基于Spring MVC的Web应用开发(11) - Views
2012-03-31 13:13 8737在FileUpload一文中,我们初步了解了SpringMVC ... -
基于Spring MVC的Web应用开发(10) - Validation
2012-03-31 11:36 3120本文介绍SpringMVC的验证(validation),在C ... -
基于Spring MVC的Web应用开发(9) - Exceptions
2012-03-31 10:55 1717本文介绍SpringMVC中的异常处理,@Controller ... -
基于Spring MVC的Web应用开发(8) - Convert
2012-03-31 09:25 3612本文介绍SpringMVC中的Convert,Convert是 ... -
基于Spring MVC的Web应用开发(7) - Headers
2012-03-30 15:01 27273本文接上一篇文章,介 ... -
基于Spring MVC的Web应用开发(6) - Response
2012-03-30 10:56 36010本文讲解Spring MVC的Response,深入了解一下@ ... -
基于Spring MVC的Web应用开发(5) - Redirect
2012-03-26 15:10 17449本文介绍Spring MVC中的重定向(Redirect),先 ... -
基于Spring MVC的Web应用开发(4) - FileUpload
2012-03-20 21:17 35680上一篇文章介绍了Spring MVC如何处理静态资源文件,本文 ... -
基于Spring MVC的Web应用开发(3) - Resources
2012-03-20 16:22 6553上一篇介绍了在基于Spring MVC的Web项目中加入日志, ... -
基于Spring MVC的Web应用开发(2) - Log
2012-03-19 11:55 3536上一篇文章我们使用SpringMVC搭建了一个简单WEB项目 ... -
基于Spring MVC的Web应用开发(1) - HelloWorld
2012-03-16 07:21 18229MVC架构 MVC是模型(model),视图(view),控 ... -
spring-oxm中unmashaller疑似bug
2012-03-08 10:21 2495spring-integration中测试XML Transf ... -
spring将spring-asm重新打包原因
2012-03-06 13:41 8195以前就发现通过eclipse上面的m2e插件不能将spring ... -
Spring底层使用SAX解析XML配置文件
2012-02-29 01:28 6056最近在研究Spring源代码,在梳理spring-beans时 ... -
在Spring 3.1.0 M2中配置Hibernate事务失效?
2011-10-22 00:38 2126SpringSource与2011年6月8号发布了Spring ...
相关推荐
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...
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 应用程序接收到 http://localhost:8080/hello.do(事实上请求路径是 /hello.do) 的请求后, Spring 将这个请求交给一个名为 helloController 的程序进行处理, helloController 再调用 一个名为 ...
是源代码,不是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 */
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 ...
Portal-Basic Java Web应用开发框架(简称 Portal-Basic)是一套功能完备的高性能Full-Stack Web应用开发框架,内置稳定高效的MVC基础架构和DAO框架(已内置Hibernate、MyBatis和JDBC支持),集成 Action拦截、Form ...
在做springmvc开发时,使用spring的tag较为方便, 部署时容易出现tld文件缺失的问题。本文件是spring-tag的tld文件,文件可以在spring-webmvc.jar的META-INF中获取,放到web项目WEB-INF即可
Spring Mvc Web项目 为什么要这个项目? 首先,我要感谢我的老师莱文·埃尔古德(LeventErgüder)在这个项目中给予我的训练和努力。 这个项目是我的第一个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. ...
14. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 15. 16. <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> 17. <bean class="org....
JessMA Java MVC & REST应用开发框架(简称 JessMA)是一套功能完备的高性能Full-Stack Web应用开发框架,内置稳定高效的MVC基础架构和DAO框架(已内置Hibernate、MyBatis和JDBC支持),集成 Action拦截、Form Bean ...
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. 命令控制器 ...
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使用...
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 ...
文件上传是Web应用程序中常见的功能之一,Spring MVC提供了方便的机制来处理文件上传。下面是关于Spring MVC实现文件上传的详细描述: Spring MVC文件上传的实现步骤如下: 准备MultipartResolver: 在Spring MVC...
《Spring 2.0技术手册》内容全面深入,主要包括Spring入门、Bean/消息/事件、Spring AOP、JDBC/事物支持、Spring与Hibernate的整合、Spring Web MVC框架、View层方案/Web框架整合、API封装、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. 命令控制器 ...
\r\n 本书内容全面深入,主要包括Spring入门、Bean/消息/事件、Spring AOP、JDBC/事物支持、Spring与Hibernate的整合、Spring Web MVC框架、View 层方案/Web框架整合、API封装、Spring在线书签完整项目示例等内容。
强大而直接的配置方式:将框架类和应用程序类都能作为JavaBean配置,支持跨多个context的引用,例如,在web控制器中对业务对象和验证器(validator)的引用。 可适配、非侵入:可以根据不同的应用场景,选择合适的...