zoukankan      html  css  js  c++  java
  • Struts2之一个action中多个方法的实现

    本篇文章为大家讲述一下Struts2中一个action里有多个方法的处理

    1.首先我们可以看到这个自定义action中有4个方法

    public class FirstAction extends ActionSupport{
        public String list(){
            return "list";
        }
        public String add(){
            return "add";
        }
        public String upd(){
            return "upd";
        }
        public String del(){
            return "del";
        }
    }

    这个action没有实现Action接口而是继承了ActionSupport类,而ActionSupport实现了Action接口并且对execute方法进行了实现,所以在这个自定义类中不需要实现execute方法。这个方法中定义了4个常见的方法,增删改查,那么如何在struts.xml中正确配置呢,有如下几种方法。

    方法一:配置多个action

    <action name="firstActionlist" class="cn.happy.day03.controller.FirstAction" method="list">
                <result name="list">day03/list.jsp</result>
    </action>
    
    <action name="firstActionadd" class="cn.happy.day03.controller.FirstAction" method="add">
                <result name="add">day03/add.jsp</result>
    </action>

    要注意:使用这种方法一定要在action节点里面指定对应的方法,method中必须指定方法。

    那么我们想访问哪个action只需要输入对应的地址

    例如:

    缺点:代码过于冗余

    方法二:配置一个action

    1 <action name="firstAction" class="cn.happy.day03.controller.FirstAction">
    2             <result name="list">day03/list.jsp</result>
    3             <result name="add">day03/add.jsp</result>
    4             <result name="del">day03/del.jsp</result>
    5             <result name="upd">day03/upd.jsp</result>
    6 </action>

    但此时我们如何访问呢?

    需要使用!分割action名称和方法名称

    例如:

     

    这种方法比较推荐,其代码冗余性不会很差,相比较第一种来说。

    方法三:通配符配置

    <action name="*_*" class="cn.happy.day04pattern.controller.{1}" method="{2}">
                <result name="{2}">day04/{2}.jsp</result>
    </action>

    解析:name="*_*" ,相当于把action名称和具体的方法名称用_分隔,例如firstAction_list,firstAction_add,secondAction_list,然后用{1}占位表示具体的action类,后面的method则表示具体方法的占位,例如firstAction_list则被拆分成

    <action name="firstAction_list" class="cn.happy.day04pattern.controller.firstAction" method="list">
                <result name="list">day04/list.jsp</result>
    </action>

    此方法同样能实现

    而我们在访问的时候只需注意用_分隔就行

     优点:代码简洁

     缺点:可读性较差,难以理解,受其他一些因素干扰(以后我们会提到)

     总结:我个人比较推荐第二种解决方法,第一种代码量较大,第三种虽然代码简洁却不稳定,而且可读性较差。

      

  • 相关阅读:
    torch.nn.functional中softmax的作用及其参数说明
    from __future__ import包的作用
    python textwrap的使用
    深度学习框架PyTorch一书的学习-第五章-常用工具模块
    python实现命令行解析的argparse的使用
    pytorch visdom可视化工具学习—2—详细使用-1—基本使用函数
    pytorch visdom可视化工具学习—2—详细使用-3-Generic Plots和Others
    pytorch visdom可视化工具学习—2—详细使用-2-plotting绘图
    硬盘没有显示
    Eclipse中syso 快捷键 Alt + / 不能使用的问题
  • 原文地址:https://www.cnblogs.com/liuhonglihahaha/p/8473974.html
Copyright © 2011-2022 走看看