Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29943759
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2009-12-08 16:38:35

 
       

       
       
       
       
   
 

问题是这样的:页面上有多个按钮,我需要当点击这些按钮时全部进入到同一个action中,但是这个action中有不同的方法.比如insert() delete()等,我点击不同按钮时怎么能够让它找到相应的方法呢?
不用JavaScript、DispatchAction就可以来做:


       
       
       
       

假如用户点了“插入”按钮,这时:
request.getParameter("insert")=="插入";
request.getParameter("delete")==null;
request.getParameter("modify")==null;
request.getParameter("list")==null;
以此类推!也就是说无论多少submit类型的按钮,只有一个不为空。这时在Struts1的Action中以用反射方法来做:
 


public class MyAction extends Action{//注意,这里并不需要继承DispatchAction

    public ActionForward execute(ActionMapping mapping, ActionForm from, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String func = {"insert","delete","modify","list"};
        String methodName = null;
        for(String f : func){
                if(request.getParameter(f) != null){
                    methodName = request.getParameter(f);
                    break;
                }
        }
        try {
            //利用反射技术让程序自动找到要处理的方法并执行之,注意methodName参数

            Method method = this.clazz.getDeclaredMethod(methodName, ActionMapping.class, ActionForm.class, HttpServletRequest.class, HttpServletResponse.class);
            return (ActionForward)method.invoke(this, mapping, from, request, response);
        } catch (Exception e) {
            request.setAttribute("message", e.getMessage());
            return mapping.findForward("message");
        }
    }
    public ActionForward insert(ActionMapping mapping, ActionForm from, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //todo

    }
    public ActionForward delete(ActionMapping mapping, ActionForm from, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //todo

    }
    public ActionForward modify(ActionMapping mapping, ActionForm from, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //todo

    }
    public ActionForward list(ActionMapping mapping, ActionForm from, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //todo

    }


阅读(1995) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~