设为首页 加入收藏

TOP

Spring MVC Flash Attribute 的讲解与使用示例(二)
2014-11-23 23:57:08 来源: 作者: 【 】 浏览:23
Tags:Spring MVC Flash Attribute 讲解 使用 示例
户信息。


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






















Firstname
Lastname
Age
Email





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
spring-mvc-flash-attribute-demo-form


spring-mvc-flash-attribute-demo-success


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


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇OpenCV入门教程之十 视频的处理 下一篇Spring MVC入门使用实例详解

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: