/WEB-INF/jsp/contact.jsp
<%@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>
在上面这个jsp页面中,我们展示了一个表单。注意表单是提交到addContact.html上的
contact.java
package net.viralpatel.spring3.form;
public class Contact {
private String firstname;
private String lastname;
private String email;
private String telephone;
public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
ContactController.java
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());
}
}
在上述这个控制类中,请注意我们用RequestMapping的/contacts 和 /addContact创建了2个方法。
showContacts()方法在用户请求contacts.html这个url是被调用。这个方法返回一个model对象contact.
注意在ModelAndView对象中,我们传递了一个空白Contact对象,名为"command". 如果你要使用<form:form>在jsp文件中,spring框架需要一个叫command的对象
我们用@ModelAttribute注释了Contact参数。这将把来自请求的数据绑定到Contact对象上。
本程序运行后在console窗口打印firstname和lastname.
原文:http://viralpatel.net/blogs/spring-3-mvc-handling-forms/
含库源代码:http://pan.baidu.com/share/link?shareid=408436&uk=3878681452