户信息。
Customer.java
package net.viralpatel.spring;
public class Customer {
private String firstname;
private String lastname;
private int age;
private String email;
//getter, setter methods
}
CustomerController 类有3个方法。showForm 方法对应 URL /form ,用来显示 Add New Customer 表单。addCustomer 方法对应 URL /addcustomer ,用来处理 POST 请求。
CustomerController.java
package net.viralpatel.controller;
import net.viralpatel.spring.Customer;
import org.springframework.stereotype.Controller;
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.servlet.mvc.support.RedirectAttributes;
@Controller
public class CustomerController {
@RequestMapping(value="showform", method=RequestMethod.GET)
public String showForm(@ModelAttribute("customer") Customer customer) {
return "add_customer";
}
@RequestMapping(value="addcustomer", method=RequestMethod.POST)
public String addCustomer(@ModelAttribute("customer") Customer customer,
final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("customer", customer);
redirectAttributes.addFlashAttribute("message","Added successfully.");
return "redirect:showcustomer.html";
}
@RequestMapping(value="showcustomer", method=RequestMethod.GET)
public String showCustomer(@ModelAttribute("customer") Customer customer) {
System.out.println("cust:" + customer.getFirstname());
return "show_customer";
}
}
注意我们在 addCustomer 方法中是如何使用 redirectAttributes 参数来添加 flash attribute 的。并且,我们是用 addFlashAttribute 方法来设置新的参数为 flash attribute。
add customer.JSP 文件显示一个 Add New Customer(添加新客户)表单。
add_customer.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
Add New Customer
show_customer.jsp 简单地显示客户的名和姓,以及用 flash attributes 设置的成功信息。
show_customer.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
${message}
${customer.lastname}, ${customer.firstname} added successfully..
执行这个 web 项目即可。
URL: http://localhost:8080/SpringMVC_Flash_Attribute_Maven_example/form.html


具体下载目录在 /2014年资料/4月/12日/Spring MVC Flash Attribute 的讲解与使用示例