web中的checkbox以及strtus2的CheckboxInterceptor

来源:互联网 发布:单片机正弦波 编辑:程序博客网 时间:2024/06/06 12:27

checkbox标签可以创建一个checkbox

当这个checkbox标签没有指定value属性的时候:<input type="checkbox" name="math"/>:

如果提交表单时没有被选中,那么req.getParameter("math")得到的值为null。

如果提交表单时被选中,那么req.getParameter("math")得到的值为on。

当这个checkbox标签指定value属性的时候:<input type="checkbox" name="math" value="true"/>:

如果提交表单时没有被选中,那么req.getParameter("math")得到的值为null。

如果提交表单时被选中,那么req.getParameter("math")得到的值为true。

我们可以在后台判断checkbox的值是不是null来确定其是否选中,但是struts2的checkbox标签和CheckboxInterceptor提供了便利。

查看struts2的checkbox标签的源代码:

<input type="checkbox"name="intresting"value="true"id="intresting"/>

<inputtype="hidden"id="__checkbox_intresting"name="__checkbox_intresting"value="true" />

注意,它多加了一个隐藏域。

CheckboxInterceptor的处理:

public String intercept(ActionInvocation ai) throws Exception {
        Map parameters = ai.getInvocationContext().getParameters();
        Map<String, String[]> newParams = new HashMap<String, String[]>();
        Set<Map.Entry> entries = parameters.entrySet();
        for (Iterator<Map.Entry> iterator = entries.iterator(); iterator.hasNext();) {
            Map.Entry entry = iterator.next();
            String key = (String)entry.getKey();


            if (key.startsWith("__checkbox_")) {
                String name = key.substring("__checkbox_".length());


                Object values = entry.getValue();
                iterator.remove();
                if (values != null && values instanceof String[] && ((String[])values).length > 1) {
                    LOG.debug("Bypassing automatic checkbox detection due to multiple checkboxes of the same name: #1", name);
                    continue;
                }


                // is this checkbox checked/submitted?
                if (!parameters.containsKey(name)) {
                    // if not, let's be sure to default the value to false
                    newParams.put(name, new String[]{uncheckedValue});
                }
            }
        }


        parameters.putAll(newParams);


        return ai.invoke();
    }

隐藏域的值总是提交的,它将获取隐藏域的name,并删除此name-value,然后查看在parameters是否包含此name,如果是,那么该checkbox是选中的,其值为true。不必处理,如果parameters中不包含此name,那么该checkbox没有被选中,那么添加name和false到parameters中。

这样,如果checkbox是选中的那么在后台得到的值为true。

如果是非选中的那么在后台得到的值为false。

 

radio和checkbox是一样的,需要注意的是,只需在创建radio的时候将其中一个radio设置为选中,那么在后台得到的值总不为null。

原创粉丝点击