Attribute

http://www.oschina.net/translate/spring-mvc-flash-attribute-example


1.session.setAttribute()和session.getAttribute()配对使用,作用域是整个会话期间,在所有的页面都使用这些数据的时候使用。

2.request.setAttribute()和request.getAttribute()配对使用,作用域是请求和被请求页面之间。request.setAttribute()是只在此action的下一个forward需要使用的时候使用;request.getAttribute()表示从request范围取得设置的属性,必须要先setAttribute设置属性,才能通过getAttribute来取得,设置与取得的为Object对象类型。其实表单控件中的Object的 name与value是存放在一个哈希表中的,所以在这里给出Object的name会到哈希表中找出对应它的value。setAttribute()的参数是String和Object。

3.request.getParameter()表示接收参数,参数为页面提交的参数。包括:表单提交的参数、URL重写(就是xxx?id=1中的id)传的参数等,因此这个并没有设置参数的方法(没有setParameter()),而且接收参数返回的不是Object,而是String类型。

举例:

session.setAttribute("kindresult", result);    //result 为StringBuffer类型对象

response.sendRedirect("../manage_kind.jsp");


在manage_kind.jsp中:

<%   
 StringBuffer kindresult=new StringBuffer();
 kindresult=(StringBuffer)session.getAttribute("kindresult");
 %>

<%=kindresult%>

##################################################################

我在servlet中使用了request.setAttribute()存储信息。
 语法如下:request.setAttribute("user","1234");
 然后 response.sendRedirect("/hello.jsp");
 但是在我的hello.jsp中 request.getAttribute("user");
 返回值为null,为什么没有取到String "1234"?

在这里就要注意了,sendRedirect不能传递request对象。使用request.setAttribute时不能使redirect而是forward。即是将请求转发而不是重定向。

你可以使用getServletContext().getRequestDispatcher("/hello.jsp").forward(request,response)转到hello.jsp页面,对客户端而言它意识不到是hello.jsp页面响应它。
 request对象和response对象是一样的,当然你的参数就可以传递过去了。

你使用response.sendRedirect("/hello.jsp");转到hello.jsp之后,request对象是新建的,你的属性值自然没有了。但是如果你使用session代替request就还是可以的。
 session.setAttribute("user","1234");
 session.getAttribute("user");

#####################################################################################

4.request.getParameter() 和request.getAttribute() 区别

(1)request.getParameter()取得是通过容器的实现来取得通过类似post,get等方式传入的数据,request.setAttribute()和getAttribute()只是在web容器内部流转,仅仅是请求处理阶段。

(2)request.getParameter()方法传递的数据,会从Web客户端传到Web服务器端,代表HTTP请求数据。request.getParameter()方法返回String类型的数据。

request.setAttribute()和getAttribute()方法传递的数据只会存在于Web容器内部

还有一点就是,HttpServletRequest类有setAttribute()方法,而没有setParameter()方法。

拿一个例子来说一下吧,假如两个WEB页面间为链接关系时,就是说要从1.jsp链接到2.jsp时,被链接的是2.jsp可以通过getParameter()方法来获得请求参数.

假如1.jsp里有

<form name="form1" method="post" action="2.jsp">
 请输入用户姓名:<input type="text" name="username">
 <input type="submit" name="Submit" value="提交">
 </form>

的话在2.jsp中通过request.getParameter("username")方法来获得请求参数username:

< % String username=request.getParameter("username"); %>

但是如果两个WEB间为转发关系时,转发目的WEB可以用getAttribute()方法来和转发源WEB共享request范围内的数据,也还是说一个例子吧。

有1.jsp和2.jsp

1.jsp希望向2.jsp传递当前的用户名字,如何传递这一数据呢?先在1.jsp中调用如下setAttribute()方法:

<%
 String username=request.getParameter("username");
 request.setAttribute("username",username);
 %>

<jsp:forward page="2.jsp" />

在2.jsp中通过getAttribute()方法获得用户名字:
 <% String username=(String)request.getAttribute("username"); %>

5.request.getAttribute()与request.setAttribute()

request.getAttribute("nameOfObj")可得到JSP页面一表单中控件的Value。其实表单控件中的Object的 name与value是存放在一个哈希表中的,所以在这里给出Object的name会到哈希表中找出对应它的value。

而不同页面间传值使用request.setAttribute(position, nameOfObj)时,只会从a.jsp到b.jsp一次传递,之后这个request就会失去它的作用范围,再传就要再设一个 request.setAttribute()。而使用session.setAttribute()会在一个过程中始终保有这个值。

P.S:JavaScript与JSP中不能相互传值,因为JavaScript运行在客户端,而JSP运行在服务器端。若想使它们之间可以相互传递参数,可以在JSP中设置一个hidden控件,用它的value结合上面所说的用法来传递所需的数值。









虽然这一方法看起来很完美,并且解决了表单多次提交的问题,但是它又引入了一个获取请求参数和属性的难题. 通常当我们生成一次http重定向请求的时候,被存储到请求数据会丢失,使得下一次GET请求不可能访问到这次请求中的一些有用的信息.

Flash attributes 的到来就是为了处理这一情况. Flash attributes 为一个请求存储意图为另外一个请求所使用的属性提供了一条途径. Flash attributes 在对请求的重定向生效之前被临时存储(通常是在session)中,并且在重定向之后被立即移除.

spring-mvc-flash-map-manager

为了这样做, Flash 特性使用了两个集合. FlashMap 被用来管理 flash attributes 而 FlashMapManager 则被用来存储,获取和管理 FlashMap 实体.

对于每一次请求一个 “input” flash map 会被创建,来存储来自任何之前请求的 flash attribute 还有一个 “output” flash map 会被创建,来存储任何我们存储在这个请求中的,之后的请求参数.

LeoXu
LeoXu
翻译于 4年前
3人顶
 翻译得不错哦!

使用

要想在你的 Spring MVC 应用中使用 Flash attribute,要用 3.1 版本或以上。并且要在 spring-servlet.xml 文件中加入 mvc:annotation-driven。

<mvc:annotation-driven />

这些都完成之后,Flash attribute 就会自动设为“开启”,以供使用了。只需在你的 Spring controller 方法中加入RedirectAttributes redirectAttributes。

import org.springframework.web.servlet.mvc.support.RedirectAttributes;
//...

	@RequestMapping(value="addcustomer", method=RequestMethod.POST)
	public String addCustomer(@ModelAttribute("customer") Customer customer,
			final RedirectAttributes redirectAttributes) {
	//...
		redirectAttributes.addFlashAttribute("message""Successfully added..");
	//...

		return "redirect:some_other_request_name";
	}

addFlashAttribute 方法会自动向 output flash map 中添加给定的参数,并将它传递给后续的请求。

我们来看看一个使用 Flash attribute 来完成 POST/Redirect/GET 并传递一些信息的完整实例吧。

Flash Attribute 实例

下面的应用向用户显示一个表单。当用户填完数据,并提交表单之后,页面会重定向到另一个显示成功信息的页面。在这个重定向的新页面中,会显示用户刚才输入的信息。

戴仓薯
戴仓薯
翻译于 4年前
4人顶
 翻译得不错哦!

第1步: 需要的 JAR 和项目结构

如果你用 Maven 来做依赖管理,用下面的 dependencies 来添加 Spring 3.1 MVC 的支持。

	<dependencies>
		<!-- Spring 3.1 MVC  -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<!-- JSTL for c: tag -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>

或者,你可以下载以下 JAR 文件,然后把它们放在 /WEB-INF/lib 文件夹下。

spring-mvc-flash-attribute-jar-files

第2步: Spring 配置

要为 web 项目添加 Spring 支持,需要在 web.xml 中添加 DispatcherServlet 。
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

	id="WebApp_ID" version="2.5">
	
	<display-name>Spring MVC Flash attribute example</display-name>
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
    	<servlet-name>default</servlet-name>
    	<url-pattern>/index.html</url-pattern>
	</servlet-mapping>	
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
</web-app>

然后,spring-servlet 使用 mvc:annotation-driven 来支持 mvc ,并且会扫描项目中的 context:component-scan 标签。

spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc.xsd">
		
	
	<bean id="jspViewResolver"
	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	 </bean>
	
	<context:component-scan base-package="net.viralpatel.controller" />
	<mvc:annotation-driven />
 
</beans>

第3步: Spring Controller – RedirectAttributes

Controller 的代码使用 Customer.java 对象作为 bean 来保存客户信息。

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。

戴仓薯
戴仓薯
翻译于 4年前
4人顶
 翻译得不错哦!

第4步: View 层

add customer.JSP 文件显示一个 Add New Customer(添加新客户)表单。
add_customer.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
	<h1>Add New Customer</h1>
	<form:form action="addcustomer.html" method="post" commandName="customer">
	<table>
		<tr>
			<td><form:label path="firstname">Firstname</form:label></td>
			<td><form:input path="firstname" /> </td>
		</tr>
		<tr>
			<td><form:label path="lastname">Lastname</form:label></td>
			<td><form:input path="lastname" /> </td>
		</tr>
		<tr>
			<td><form:label path="age">Age</form:label></td>
			<td><form:input path="age" /> </td>
		</tr>
		<tr>
			<td><form:label path="email">Email</form:label>
			<td><form:input path="email" /> </td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="Add Customer" />
			</td>
		</tr>
	</table>
	</form:form>
</body>
</html>

show_customer.jsp 简单地显示客户的名和姓,以及用 flash attributes 设置的成功信息。

show_customer.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
<h1>${message}</h1>
	${customer.lastname}, ${customer.firstname} added successfully..
</body>
</html>

Demo:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值