现在的位置: 首页 > 综合 > 正文

在Action中转到其它url的三种方法对比。

2013年05月25日 ⁄ 综合 ⁄ 共 1775字 ⁄ 字号 评论关闭

首先我就想到了,response.sendRedirect("/u2bman.do"); 结果出现异常,
java.lang.IllegalStateException: Cannot forward after response has been committed
org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1063)
org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:386)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:229)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
cn.sintal.common.filter.LogFilter.doFilter(LogFilter.java:89)
cn.sintal.common.filter.EncodingFilter.doFilter(EncodingFilter.java:51)
这个方法泡汤了,隐约记得这个方法只能用在页面(xx.jsp)来回转。

然后就想到了,
RequestDispatcher rd = request
      .getRequestDispatcher("/u2bmanurl.do?url="+URLEncoder.encode(url));
    rd.forward(request, response);
这个方法可行,但是Action必须返回一个ActionForward对象,所以还必须不伦不类地写上一句:return mapping.findForward("");很不雅观。

最后方法,
ActionForward forward = new ActionForward(); // return value
  forward.setPath("/u2bmanurl.do?url="+URLEncoder.encode(url));//set path
  return (forward);  //forward

简单明了,切实可行。可以用来跳转到其它Action,补充一点,在struts中的控制页面调转都应改是ActionServlet来做的,自己写一个跳转的Action并不好,但是在某些特殊情况下又必须这样是用,例如,
ActionAAA需要一个参数channelId ,但是我的页面无法提供此channelId , 只能提供cityId ,typeid .我要想
利用已经写好的ActionAAAA,就必须使用cityId,tyid获得channelId ,

   int channelId = bo.getChannelId( cityid , typeid ) ;

之后就只需要调用ActionAAA的功能就可以了,我又不想写ActionBBB把AciontAAA的代码拷贝过来,所以
我就在此后直接写:
  ActionForward forward = new ActionForward(); // return value
  forward.setPath("/ActionAAA.do?channelid="+URLEncoder.encode(channelId));
  return (forward);  //转向了ActionAAA

这样就相当于在ActionAAA的外面又加了一层。
复用了并且节省了代码,减少了bug出现的机会,和维护的成本。特别是当ActionAAA比较复杂,并且
还需要一定修改的时候。另外责任人又分得比较清楚了。

抱歉!评论已关闭.