您的位置:首页 > 编程语言 > Java开发

struts2的静态参数封装及3种动态参数封装方法

2018-04-10 11:27 337 查看

1.静态参数封装用到了相应的拦截器,在struts-default.xml中查找<interceptor-ref name="staticParams"/>对应的jsp[html] view plain copy<body>  
   <form action="${pageContext.request.contextPath}/action1.action" method="post">  
    <%--表单中的name属性取值必须和动作类中数据模型的set方法后面的名称一致。 --%>  
    用户名:<input type="text" name="username" /><br/>  
    年龄:<input type="text" name="age"/><br/>  
    <input type="submit" value="提交" />  
   </form>  
对应的struts配置[html] view plain copy<action name="action1" class="com.itheima.web.action.Demo1Action" method="addUser">  
    <!-- 当我们不写任何拦截器时,默认的拦截器栈defaultStack它来为我们工作。  
         但是,只要写了任何一个拦截器,默认的就全都不起作用了 -->  
    <!-- 使用注入的方式,给动作类的中的参数赋值 -->  
    <param name="username">张三</param>  
    <param name="age">18</param>  
</action>  

对应的动作类[java] view plain copyimport com.opensymphony.xwork2.ActionSupport;  
/** 
 * 静态参数封装 
 * @author zhy 
 * 
 */  
public class Demo1Action extends ActionSupport {  
  
    private String username;  
    private int age;  
      
      
    public String addUser(){  
        System.out.println(username+","+age);  
        return null;//不返回任何结果视图   NONE常量  
    }  
  
  
    public String getUsername() {  
        return username;  
    }  
  
  
    public void setUsername(String username) {  
        this.username = username;  
    }  
  
  
    public int getAge() {  
        return age;  
    }  
  
  
    public void setAge(int age) {  
        this.age = age;  
    }  
      
      
}  

2.动态参数封装1)用到了相应的拦截器,在struts-default.xml中查找<interceptor-ref name="params">对应的jsp,与静态的一致[html] view plain copy<body>  
    <form action="${pageContext.request.contextPath}/action2.action" method="post">  
        <%--表单中的name属性取值必须和动作类中数据模型的set方法后面的名称一致。 --%>  
        用户名:<input type="text" name="username" /><br/>  
        年龄:<input type="text" name="age"/><br/>  
        <input type="submit" value="提交" />  
    </form>  
  </body>  
对应的struts配置[html] view plain copy<!-- 动态参数封装的第一种形式的配置 -->  
        <action name="action2" class="com.itheima.web.action.Demo2Action" method="addUser"></action>  
对应的动作类[java] view plain copyimport com.opensymphony.xwork2.ActionSupport;  
/** 
 * 动态参数封装,第一种情况: 
 *      数据模型与动作类写在一起 
 * @author zhy 
 * 
 */  
public class Demo2Action extends ActionSupport {  
  
    private String username;  
    private int age;  
      
      
    public String addUser(){  
        System.out.println(username+","+age);  
        return null;//不返回任何结果视图   NONE常量  
    }  
  
  
    public String getUsername() {  
        return username;  
    }  
  
  
    public void setUsername(String username) {  
        this.username = username;  
    }  
  
  
    public int getAge() {  
        return age;  
    }  
  
  
    public void setAge(int age) {  
        this.age = age;  
    }  
      
      
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: