spring mvc中使用jodd来绑定变量

spring mvc中使用jodd来绑定变量

到处都在推荐一个FORM绑定的东东jodd。不过我去官方主页上看了看,也下载了一个
发现有点复杂,也有点大。真的想springside说的那样,很多强大的东东,我们都没有用到
只是用了很少的一部分。所以我还是觉得springside上包装的那个东东好些,
先到http://sillycat.3adisk.com/上面把jodd的jar包下载过来。这个是经过springside简化过的,
比原始的jodd.jar要小很多

然后在taglibs.jsp中加入jodd的标签:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="jodd" uri="http://www.springside.org.cn/jodd_form" %>

在使用到jodd的页面上这样编写,userEdit.jsp:
<%@ include file="/template/jsp/include/taglibs.jsp"%>

<jodd:form bean="item" scope="request">
<form action="user.do?method=save" method="post">
<input type="hidden" name="id" />
<table width="300" border="0" cellspacing="0" cellpadding="0"
   align="center">
   <tr>
    <td height="32" align="right" width="107">
     name:
    </td>
    <td height="32" width="193">
     <input type="text" name="name" size="20">
    </td>
   </tr>
   <tr>
    <td height="69" align="center" colspan="2">
     <input type="submit" name="Submit" value="save">
     <input type="reset" name="Reset" value="cancel">
    </td>
   </tr>
</table>
</form>
</jodd:form>

在action中这样得到数据,参考UserController.java:
protected void onSave(HttpServletRequest request,
   HttpServletResponse response, ModelAndView mav, boolean isNew)
   throws Exception {
User user = new User();
BindingResult result = bindObject(request, user);
userManager.saveUser(user);
}

里面的bindOject(request,user)是springside上的BaseController.java里面的一个方法:
protected BindingResult bindObject(HttpServletRequest request, Object command) throws Exception {
        Assert.notNull(command);

        //创建Binder
        ServletRequestDataBinder binder = createBinder(request, command);
        //回调函数,供子类扩展对binder做出更进一步设置,并进行不能由binder自动完成的绑定
        preBind(request, command, binder);

        //绑定
        binder.bind(request);

        //校验
        Validator[] validators = getValidators();
        if (validators != null) {
            for (Validator validator : validators) {
                if (validator.supports(command.getClass())) {
                    ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
                }
            }
        }
        return binder.getBindingResult();
}

这样凡是jodd标签内部的input内容都可以绑定到action了。嘿嘿。注意数据类型哈。最好页面上都提交string过来了再动手转,
安全第一。

对了,页面回显的时候要注意:

html里面绑定的是<jodd:form bean="item" scope="request"> ,web层出来也要是这个。。。。才能正常回显

protected void onEdit(HttpServletRequest request,
   HttpServletResponse response, ModelAndView mav) throws Exception {
Integer id = new Integer(request.getParameter("id"));
User user = userManager.getUser(id);
mav.addObject("item", user);
}



你可能感兴趣的:(spring,jsp,Web,mvc,sun)