我的网站之struts2笔记3

2017-08-08  本文已影响0人  星与星的连接

废话不多说,单刀直入,总结一下action获取表单提交数据的几种方式。

方式一:使用ActionContext类获取,先获取到ActionContext对象,接着获取所有表单Map集合,key为参数名称,value为对象值。

   public String execute() throws Exception {
        // 获取ActionContext对象
        ActionContext context = ActionContext.getContext();
        // 获取参数Map对象
        Map<String, Object> map = context.getParameters();
        // 遍历Map集合
        Set<String> set = map.keySet();
        for (String key : set) {
            // 表单value值是Object数组,因为存在表单中多值的情况
            Object[] values = (Object[]) map.get(key);
            System.out.println(Arrays.toString(values));
        }
        return NONE;
    }

方式二:采用ServletActionContext对象的方式,先获取到request对象,再根据request.getParameter()方法获取对应值。

    public String execute() throws Exception {
        // 通过ServletActionContext对象得到HttpServletRequest对象
        HttpServletRequest request = ServletActionContext.getRequest();
        // 取值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String address = request.getParameter("address");
        return NONE;
    }

方式三:采用接口注入的方式,也是先得到request对象,然后操作数据。

public class TestAction3 extends ActionSupport implements ServletRequestAware {
    private HttpServletRequest request = null;
    public void setServletRequest(HttpServletRequest request) {
        // TODO Auto-generated method stub
        this.request = request;
    }

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String address = request.getParameter("address");
        System.out.println(username + ":" + password + ":" + address);
        return NONE;
    }

方式四:采用属性封装表单数据 。
1:在action成员变量位置定义变量(变量名称和表单输入项的name属性值一样)
2:生成变量的set方法(set和get方法)

方式五:模型驱动封装表单数据(重点),直接将笔记截图,步骤比较清晰

我的网站基本上就使用了上面的几种方式,另外还有几种方式没有总结:使用表达式封装、list集合封装、map集合封装。如果感兴趣可以搜索,网上有很多资料。下一篇将会总结值栈对象的使用。

上一篇 下一篇

猜你喜欢

热点阅读