Java学习篇之---struts(一)
new ActionForward 和 mapping.findForward("")的区别:
1、mapping.findForward("") 得到struts-config 已经配置好的forward。
比如:
<action path="/HelloWorld" type="hello.HelloAction"
name="HelloForm" scope="request" validate="true"
redirect="false" input="/hello.jsp">
<forward name="SayHello" path="/hello.jsp" />
</action>
可以通过
mapping.findForward("SayHello") 转向hello.jsp
而
new ActionForward ("hello.jsp")
与上面的效果一样,只是第一种写法规范一点 方便配置。
2、也有人在Action中这样写:
<!-- Action中的代码 -->
ActionForward forward=mapping.findForward("SayHello");
ActionForward newForward=new ActionForward(forward);
String newPath=forward.getPath()+"&id=1"
newForward.setPath(newPath);
return newForward;
来代替
<!-- Action中的代码(第二种) -->
return new ActionForward ("hello.jsp?id=1");
从而增加Action中参数动态的效果。
3、但是有一点需要注意的是:
<span style="font-family:SimSun;">request.setAttribute("pplns", new Integer(0));</span>
<span style="font-family:SimSun;">return new ActionForward("/hello.jsp");</span>
return的时候相当于还是同一个request请求,所以可以携带参数setAttribute回去(无论struts-config文件中的redirect="false"还是redirect="true")。
<span style="font-family:SimSun;">request.setAttribute("pplns", new Integer(0));</span>
<span style="font-family:SimSun;">return mapping.findForward("/hello.jsp");</span>
return的时候,如果struts-config文件中的redirect="true",则表示另外一个请求,不可以携带参数;如果struts-config文件中的redirect="false",则表示同一个请求,可以 携带参数(struts-config文件中的redirect默认缺省值为false)
4、题外话:(以下内容摘自网络,未经验证)
无论在任何情况下使用
request.getSession().setAttribute("pplns", "sssss");都可以传递参数。
在页面处获取 <%=request.getSession().getAttribute("pplns")%>
1)、当使用mapping.findForward("/hello.jsp")的时候并且redirect是true时候效果,地址栏如 http://localhost:8080/hello.jsp
2)、当使用mapping.findForward("/hello.jsp")并且redirect是false时候
与使用new ActionForward("/hello.jsp")的时候效果一样,地址栏不会出现jsp页面。