Spring框架的标签使用

来源:互联网 发布:tf家族官网淘宝 编辑:程序博客网 时间:2024/05/02 00:28

Spring框架中提供了它自己的标签库,可以和相关的组建相结合,可以提供页面表单组件、错误信息的数据绑定等功能。

如果要想使用spring标签,要将dist目录下的spring.tld复制到你web应用程序下的/WEB-INF/下,并在web.xml中加入

<taglib>  <taglib-uri>/spring</taglib>  <taglib-location>/WEB-INF/spring.tld</taglib-location></taglib>

页面

<%@taglib prefix="spring" uri="/spring"%><%@page contentType="text/html;charset=Big5"%><html><head><title>Login</title></head><body>    <spring:bind path="command.*"> //组件所有相关数据        <font color="red"><b>${status.errorMessage}</b></font><br>    </spring:bind>       输入帐号密码:<p>    <form name="loginform" action="/springapp/login.do" method="post">           <spring:bind path="command.username">        帐号 <input type="text" name="${status.expression}" value="${status.value}"/><br>        </spring:bind>           <spring:bind path="command.password">        密码 <input type="password" name="${status.expression}" value="${status.value}"/><br>        </spring:bind>   //status的expression显示绑定的属性名称 value存储的组建值            <input type="submit" value="确定"/>    </form>    </body></html> 

使用标签需要一个BindException对象,所以用另一个onSumit(),当验证失败时候,可以用BindException对象的regect()方法,意思是表示拒绝这个输入的数据,reject()方法接受两个参数,第一个是error code 。当然需要MessageResourceSource ,设置好你的properties资源文件中的error code为key 写好相应的错误信息。

如果没有MessageResourceSource可以用第二个参数。

如:

errors.reject("loginfail","you password is wrong");

errors.getModel()方法返回一个Map集合,之前的存储的错误信息就在这里面。可以设定给ModelAndView。这样就会在页面的标签上显示错误信息了。