一、引言
虽然知道Struts1在项目中已经很少使用了,但最近接触了Struts1,不甘心不实现demo,愿意把最近了解到的进行一下总结。
二、如何使用ActionForward
ActionForward是 Struts的核心类之一。在基于Struts的Web应用程序开发过程中,Action操作完毕后程序会通过Struts的配置文件struts- config.xml链接到指定的ActionForward,传到Struts的核心类ActionServlet,ActionServlet使用 ActionForward提供的路径,将控制传递给下一个步骤。ActionForward控制接下来程序的走向。
if(request.getSession().getAttribute("username")==null){
return mapping.findForward("login");
}
return mapping.findForward("success");
struts- config.xml中的代码,根据forward中的name就可以找到对应的jsp了
<action-mappings>
<action path="/login"
type="com.bjpowernode.struts.LoginAction"
name="loginForm"
scope="request"
>
<forward name="success" path="/login_success.jsp"/>
<forward name="success" path="/login_error.jsp"/>
</action>
<action path="/must_login"
type="com.bjpowernode.struts.MustLoginAction">
<forward name="login" path="/login.jsp"/>
<forward name="success" path="/must_login.jsp"/>
</action>
</action-mappings>
三、ActionForward的使用
1.转发和重定向
封装转发路径,通俗点说就是说完成页面的跳转和转向。默认情况下,actionForward采用的是转发的方式进行页面跳转的(redirect默认为false)。转发的时候,页面的url地址不变,而重定向的时候页面的url地址会发生变化。因为转发的时候是采用的同一个request(请求),既然页面跳转前后是同一个request,页面url不会变;而重定向采用的是2个request,因为是二次转发页面跳转,前后的url会不同。
如果使用ActionForward进行重定向,只需要把redirect改为true就可以了。
<forward name="success" path="/must_login.jsp" redirect="true"/>
2.动态ActionForward:
如果需要做很多转向,那么会在struts-config.xml里配置很多的forward,这样就会比较麻烦。为了防止这种情况的发生,需要使用动态的ActionForward。
public class MustLoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
int page=Integer.parseInt(request.getParameter("page"));
ActionForward af = new ActionForward();
af.setPath("/page"+page+".jsp");
return af;
}
}
四、写在后面
刚开始了解这个地方的时候想这是个什么东西嘛,敲了几个demo后发现挺好理解的,重在实践吧,即使代码也很简单。只看理论是没意思的。