PRG模式在Struts中的实现  2009-01-12   Web  

Post/Redirect/Get (PRG)是一种用于Web应用的设计模式,这种设计模式可以避免表单(FORM)的重复提交,并可以使浏览器的后退、前进和刷新按钮以更友好的方式来操作Web应用。

Web用户向Web服务器提交了表单,服务器通常产生一个HTML页面作为响应。在Web用户看来,这就是一个普通的网页,但是,因为它是一个HTTP POST请求发起的,所以不能加入浏览器的书签;如果试图重新刷新/加载该页面,浏览器一般会弹出一个警告窗口,而且会导致相同的数据被重新提交

为了避免点击刷新按钮弹出警告窗口重复提交这两个问题,许多Web应用使用了PRG模式,对于POST请求不再返回一个HTML页面,而是返回一个重定向(REDIRECT)命令,浏览器会以HTTP GET方式载入网页,这样一来,浏览器就可以安全的使用后退、前进和刷新按钮了。

Struts和Tiles如何实现PRG模式呢?

如果使用了Tiles,则不能直接Redirect到Tiles的definition,必须由Action再转发一次。

如果使用IE,则struts-config.xml中禁用浏览器缓存,后退、前进和刷新时都以GET方式自动刷新页面显示并不提交数据。

如果使用Firefox,则无法禁用缓存,所以后退和前进时显示的是缓存中的页面,刷新时才刷新页面。

struts-config.xml:

<action path="/order"
	type="com.order.OrderAction"
	name="OrderForm" input="Order"
	scope="session" validate="true">
	<forward name="CreateOrder" path="/order.do?DisplayOrder"
redirect="true"/>
	<forward name="DisplayOrder" path="DisplayOrder"/>
</action>

OrderAction.java:

protected final Map<String, String> getKeyMethodMap() {
	Map<String, String> map = new HashMap<String, String>();
	map.put("CreateOrder", "doCreateOrder");
	map.put("DisplayOrder", "displayOrder");
	return map;
}

public final ActionForward doCreateOrder(final ActionMapping mapping,
		final ActionForm form, final HttpServletRequest request,
		final HttpServletResponse response) throws Exception {
	//调用业务方法
	//存储数据到数据库或session

	//如果需要将数据往下传递,则:
	//String path = mapping.findForward("CreateOrder").getPath();
	//path = path + "&id=1";
	//ActionForward forward = new ActionForward(path);
	//forward.setRedirect(true);
	//return forward;

	return mapping.findForward("DisplayOrder");
}

public final ActionForward displayOrder(final ActionMapping mapping,
		final ActionForm form, final HttpServletRequest request,
		final HttpServletResponse response) throws Exception {
	//如果需要读取参数,则:
	//String id=request.getParameter("id");
	//根据id从数据库或session读取数据
    //request.setAttribute("data","test");
	return mapping.findForward("DisplayOrder");
}

 发表评论

(必填)

(必填)

评论(必填,最多字数:100):