`

Handling Forms in Spring 3.0 MVC

阅读更多

Welcome to the Part 3 of Spring 3.0 MVC Series. In previous article we created a Hello World application in Spring MVC. We leaned how to configure Spring MVC in web.xml and how to use different annotations like @Controller, @RequestMapping etc. In this article let us see how to handle forms in Spring 3.0 MVC.

 

Spring 3.0 MVC Series

We will use the framework that we created in previous article as a base reference and add up the functionality of form in it. Also the application that we create will be a Contact Manager application.

Our Goal

Our goal is to create basic Contact Manager application. This app will have a form to take contact details from user. For now we will just print the details in logs. We will learn how to capture the form data in Spring 3 MVC.
spring-3-contact-manager-form

Getting Started

Let us add the contact form to our Spring 3 MVC Hello World application. Open the index.jsp file and change it to following:

File: WebContent/index.jsp

1
<jsp:forward page="contacts.html"></jsp:forward>

The above code will just redirect the user to contacts.html page.

The View- contact.jsp

Create a JSP file that will display Contact form to our users.
File: /WebContent/WEB-INF/jsp/contact.jsp

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">
  
    <table>
    <tr>
        <td><form:label path="firstname">First Name</form:label></td>
        <td><form:input path="firstname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Last Name</form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Email</form:label></td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Telephone</form:label></td>
        <td><form:input path="telephone" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Add Contact"/>
        </td>
    </tr>
</table>  
  
</form:form>
</body>
</html>

Here in above JSP, we have displayed a form. Note that the form is getting submitted to addContact.html page.

Adding Form and Controller in Spring 3

We will now add the logic in Spring 3 to display the form and fetch the values from it. For that we will create two java files. First the Contact.java which is nothing but the form to display/retrieve data from screen and second the ContactController.java which is the spring controller class.
contact-form-package-spring-mvc

File: net.viralpatel.spring3.form.Contact

01
02
03
04
05
06
07
08
09
10
11
package net.viralpatel.spring3.form;
  
public class Contact {
    private String firstname;
    private String lastname;
    private String email;
    private String telephone;
  
    //.. getter and setter for all above fields.
  
}

The above file is the contact form which holds the data from screen. Note that I haven’t showed the getter and setter methods. You can generate these methods by pressiong Alt + Shift + S, R.

File: net.viralpatel.spring3.controller.ContactController

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package net.viralpatel.spring3.controller;
  
import net.viralpatel.spring3.form.Contact;
  
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.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
  
@Controller
@SessionAttributes
public class ContactController {
  
    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
                            Contact contact, BindingResult result) {
  
        System.out.println("First Name:" + contact.getFirstname() +
                    "Last Name:" + contact.getLastname());
  
        return "redirect:contacts.html";
    }
  
    @RequestMapping("/contacts")
    public ModelAndView showContacts() {
  
        return new ModelAndView("contact", "command", new Contact());
    }
}

In above controller class, note that we have created two methods with Request Mapping /contacts and /addContact. The method showContacts() will be called when user request for a url contacts.html. This method will render a model with name “contact”. Note that in the ModelAndView object we have passed a blank Contact object with name “command”. The spring framework expects an object with name command if you are using
in your JSP file.

Also note that in method addContact() we have annotated this method with RequestMapping and passed an attribute method=”RequestMethod.POST”. Thus the method will be called only when user generates a POST method request to the url /addContact.html. We have annotated the argument Contact with annotation @ModelAttribute. This will binds the data from request to the object Contact. In this method we just have printed values of Firstname and Lastname and redirected the view to cotnacts.html.

That’s all folks

The form is completed now. Just run the application in eclipse by pression Alt + Shift + X, R. It will show the contact form. Just enter view values and press Add button. Once you press the button, it will print the firstname and lastname in sysout logs.
spring-3-contact-manager-form

Download Source Code

Click here to download source code (7.43kb)

Moving on

In this article we learn how to create a form using Spring 3 MVC and display it in JSP. Also we learn how to retrieve the form values using ModelAttribute annotation. In next section we will go through form validations and different data conversion methods in Spring 3 MVC.

 

转自: 写道
http://viralpatel.net/blogs/2010/07/spring-3-mvc-handling-forms.html

 

分享到:
评论

相关推荐

    Spring 2.0 MVC的应用

    在这个"FirstSpringWebApp"项目中,我们将深入探讨Spring MVC的核心概念和它在实际开发中的应用。 1. **Spring MVC概述** Spring MVC是Spring框架的一部分,专门用于构建Web应用程序。它遵循Model-View-Controller...

    Spring mvc 教程

    - **Servlet 3.0 下的 MultipartResolver**:对于 Servlet 3.0 及以上版本,Spring MVC 提供了内置的文件上传支持。 - **处理表单中的文件上传**:通过控制器方法来接收和处理上传的文件。 #### 异常处理 ...

    spring mvc

    7. **Form Handling**: Spring MVC 提供了强大的表单处理能力,包括自动数据绑定、数据校验等功能。通过@Valid可以进行数据验证,@RequestParam和@PathVariable用于获取请求参数。 8. **Interceptors**: 拦截器是...

    spring-mvc-error-handling-example:Spring MVC错误处理示例

    Spring Boot & Spring MVC 异常处理的N种方法 参考文档: Spring Boot 1.5.4.RELEASE Spring framework 4.3.9.RELEASE 默认行为 根据Spring Boot官方文档的说法: For machine clients it will produce a JSON ...

    Spring &Web; &MVC;外文翻译.zip

    9. **Form Handling and Data Binding**: Spring MVC提供强大的表单处理和数据绑定功能。它可以自动将HTTP请求参数绑定到Java对象的属性上,反之亦然。 10. **Validation**: Spring MVC集成Hibernate Validator,...

    spring mvc demo

    Spring MVC 的设计目的是简化开发,提高可测试性,并与其他Spring框架无缝集成,如Spring Core、Spring Beans和Spring AOP。在这个"spring mvc demo"中,我们可以期待学习到关于如何设置和运行一个基本的Spring MVC...

    spring3.1 mvc入门讲解代码

    Spring MVC 是一款强大的Java Web应用程序开发框架,是Spring框架的一部分,专为构建Web应用程序而设计。在Spring 3.1版本中,它引入了若干改进和新特性,以提升开发效率和性能。在这个入门讲解中,我们将深入理解...

    Spring的mvc

    **Spring MVC 框架详解** Spring MVC 是 Spring 框架的重要组成部分,它是一个用于构建 Web 应用程序的模型-视图-控制器(MVC)架构。Spring MVC 提供了一个灵活、可扩展的机制,使开发者可以方便地处理 HTTP 请求...

    spring MVC .docx

    **Spring MVC 框架详解** Spring MVC 是 Spring 框架的重要组成部分,它是一个用于构建 Web 应用程序的模型-视图-控制器(MVC)架构。Spring MVC 提供了灵活的处理请求和响应的方式,使得开发者可以更专注于业务...

    spring mvc入门小例子

    6. **Form Handling**:Spring MVC提供了强大的表单处理能力,包括数据绑定和验证。`@RequestParam`用于从请求参数中获取数据,`@Valid`用于进行数据校验。 7. **Interceptor**:拦截器允许我们在请求处理前后执行...

    Spring MVC简单样例

    Spring MVC 是一个基于Java的轻量级Web应用框架,它为构建MVC(Model-View-Controller)架构的Web应用程序提供了强大的支持。本教程将深入探讨Spring MVC的基础知识及其在实际开发中的应用。 首先,Spring MVC的...

    夏昕老师spring _mvc的例子原代码part1

    标题中的“Spring MVC”是指Spring框架的一个核心模块,用于构建Web应用程序的模型-视图-控制器(MVC)架构。Spring MVC提供了一种组织后端业务逻辑、处理HTTP请求、呈现用户界面的方法。在这个例子中,“part1”...

    Spring MVC 简单的小例子

    Spring MVC 是一个强大的Java Web开发框架,由Spring社区开发,用于构建高效、模块化和可测试的Web应用程序。在这个简单的例子中,我们将深入探讨Spring MVC的基本组成部分和它们如何协同工作。 首先,让我们从核心...

    Spring MVC 框架学习总结

    **Spring MVC 框架学习总结** Spring MVC 是 Spring 框架的重要组成部分,它是一个用于构建 Web 应用程序的轻量级、模型-视图-控制器(MVC)框架。Spring MVC 提供了优雅的编程模型和高度模块化的架构,使得开发者...

    spring mvc学习视频相关资料

    8. **Form Handling(表单处理)**:Spring MVC提供了便捷的表单绑定和验证机制,通过@ModelAttribute注解将表单数据绑定到Java对象。 9. **AJAX集成**:Spring MVC支持与jQuery、AngularJS等库进行AJAX通信,使用@...

    spring api

    此外,3.2版还对Spring MVC进行了优化,包括支持Partial Model Updates和Async Request Handling,从而提升了Web应用的响应速度。 Spring API文档详细阐述了这些版本中包含的各个模块和接口,如Core Container...

    spring mvc注释文档

    ### Spring MVC注释文档知识点详解 #### 概述 ...2. [Spring MVC教程](https://spring.io/guides/gs/handling-form-submission/) 3. [Spring MVC实战](https://www.baeldung.com/spring-mvc-tutorial)

    SPRING MVC

    **Spring MVC 知识点详解** Spring MVC 是一个基于 Java 的 Model-View-Controller(MVC)架构模式的轻量级 Web 开发框架。它属于 Spring 框架的一部分,旨在简化开发,提供一个用于构建可维护性高、灵活性强的 Web...

    spring MVC 3.23版本 Demo(包含jar包、可直接运行)

    Spring MVC 是一个基于Java的轻量级Web应用框架,它为构建模型-视图-控制器(MVC)架构的应用程序提供了强大的支持。Spring MVC 3.23版本是该框架的一个较旧但仍然广泛使用的版本,它包含了丰富的特性和改进,以提升...

Global site tag (gtag.js) - Google Analytics