Struts 1.2笔记:ActionForward

一、只有登录才能显示的页面
    这是一个很平常的问题,在访问某些网页的时候,只有登录才可以访问,以此保证安全。
    实现原理也很简单,就是将一个属性设置在session中。在访问的时候进行判断即可。
    例:request.getSession().setAttribute("user", username);
    这样就可以根据session进行判断了
1.MustLoginAction.java
 
package com;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class MustLoginAction extends Action {
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  
  if(request.getSession().getAttribute("user") == null) {
   
   return mapping.findForward("login");
  }
  return mapping.findForward("success");
 }
}
 
在转向时,如果没有做重定向,浏览器地址栏显示的地址会是“.do”的形式,如果要避免这种情况发生,则需要在struts-config.xml中的forward配置里做重定向。
例:<forward name="login" path="/login.jsp" redirect="true"/>
 
二、动态ActionForward
    如果需要做很多转向,那么会在struts-config.xml里配置很多的forward,这样就会比较麻烦。为了防止这种情况的发生,需要使用动态的ActionForward。
1.DynaActionForwardTestAction.java
 
package com;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DynaActionForwardTestAction extends Action {
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  
  ActionForward af = new ActionForward();
  af.setPath("/page"+request.getParameter("page")+".jsp");
  return af;
 }
}
 
如上所示,这个action在做转向的时候就使用了动态ActionForward

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/shipeng22022/p/4614184.html