Spring中的数据绑定

下面是一个SimpleFormController的实例,虽然有些地方显得吹毛求疵,但主要是为了表达一个完整的流程。
首先先看配置文件,web.xml就不说了,下面的是/WEB-INF/mvc-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "
http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
 <!--InternalResourceViewResolver-->
 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/jsp/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 
 <!--SimpleUrlHandlerMapping-->
 <bean id="urlHandlerMapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
   <props>
      <prop key="/user.htm">userController</prop>
   </props>
  </property>
 </bean>
</beans>

然后是/WEB-INF/controller-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "
http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  
 <bean id="userValidator" class="com.yangsq.validator.UserValidator"/>
 
 <bean id="userController"
  class="com.yangsq.controller.UserController">
  <property name="commandName">
   <value>command</value>
  </property>
  <property name="commandClass">
   <value>com.yangsq.domain.User</value>
  </property>
  <property name="validator">
   <ref bean="userValidator" />
  </property>
  <property name="formView">
   <value>user</value>
  </property>
  <property name="successView">
   <value>hello</value>
  </property>
 </bean>
</beans>

   这里需要对上面的配置文件进行说明。commandName属性的设置是为了可以在页面中使用Spring tag,对业务流程没有影响,如果不想使用Spring tag,则这个属性可以没有。commandClass指定了封装表单的类,注意,要指定完整的路径,不能只指定一个类名,也不能<ref .../>。validator的设定说明了要使用验证器。formViewsuccessView这两个属性设定了转向的页面,它们是父类所具有的,所以不需要在你的controller中再注入了。

   下面是验证器:

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.yangsq.domain.User;

public class UserValidator implements Validator{
 
 public boolean supports(Class clazz) {
     return clazz.equals(User.class);
 }
 
 public void validate(Object obj, Errors err) {
     User user = (User) obj;
     if (user.getPhone().length() < 7) {
      user.setCreateTime(null);
      err.reject("phoneErr", "电话号码位数要大于7");
     }else if (user.getAge() <= 0) {
      user.setCreateTime(null);
      err.reject("ageErr", "年龄要大于0");
     }
 }
}

验证器实现了Validator借口,supports和validate这两个方法是必须实现的。验证器的主要任务是对表单类进行验证,这时请求的数据已经封装到表单类里了。

  下面是表单类:

public class User {
 private String account;
 private String phone;
 private int age;
 private String city;
 private Date createTime;
 
 public String getAccount() {
  return account;
 }
 public void setAccount(String account) {
  this.account = account;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getPhone() {
  return phone;
 }
 public void setPhone(String phone) {
  this.phone = phone;
 }
 public Date getCreateTime() {
  return createTime;
 }
 public void setCreateTime(Date createTime) {
  this.createTime = createTime;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
}
属性包括用户名称,电话,年龄,城市和创建日期。此外,为了表达一个完成的演示,还创建了一个city类:
public class City {
 private String cityName;
 private String cityNo;
 public String getCityName() {
  return cityName;
 }
 public void setCityName(String cityName) {
  this.cityName = cityName;
 }
 public String getCityNo() {
  return cityNo;
 }
 public void setCityNo(String cityNo) {
  this.cityNo = cityNo;
 }
}

下面就是这个例子的主角,UserController:

public class UserController extends SimpleFormController {
 
 protected Map referenceData(HttpServletRequest req) throws Exception {
  Map map = new HashMap();
  
  List cityList = new ArrayList();
  City city1 = new City();
  city1.setCityName("BeiJing");
  city1.setCityNo("010");
  cityList.add(city1);
  City city2 = new City();
  city2.setCityName("ShangHai");
  city2.setCityNo("020");
  cityList.add(city2);
  
  map.put("cityList", cityList);
  return map;
 }

 protected void onBind(HttpServletRequest req, Object obj) throws Exception {
  User user = (User) obj;
  //format the infor
     user.setAccount(user.getAccount().trim());
     user.setPhone(user.getPhone().trim());
 }


 protected void onBindAndValidate(HttpServletRequest req, Object obj, BindException err) throws Exception {
  User user = (User) obj;
  user.setCreateTime(new Date());
 }

 protected ModelAndView onSubmit(Object obj) throws Exception {
  User user = (User) obj;
  return new ModelAndView(this.getSuccessView(), "user", user);
 }
}

下面是使用到的页面 user.jsp的主要部分(表单):

<FORM action="user.htm" method="post">
 <TABLE>
  <TBODY>
   <TR>
    <TD>
     <spring:bind path="command.account">
      用户名:<INPUT name="${status.expression}" type="text" value="${status.value}"/>
     </spring:bind>
    </TD>
   </TR>
   <TR>
    <TD>
     <spring:bind path="command.age">
      年龄:<INPUT name="${status.expression}" type="text" value="${status.value}"/>
     </spring:bind>
    </TD>
   </TR>
   <TR>
    <TD>
     <spring:bind path="command.phone">
      电话号码:<INPUT name="${status.expression}" type="text"  value="${status.value}"/>
     </spring:bind>
    </TD>
   </TR>
   <TR>
    <TD>
     <spring:bind path="command.city">
      城市:
      <SELECT name="${status.expression}">
       <c:forEach items="${cityList}" var="city" varStatus="loopStep">
        <OPTION value="${city.cityNo}" <c:if test="${city.cityNo == status.value}">selected</c:if>>
         <c:out value="${city.cityName}"/>
        </OPTION>
       </c:forEach>
      </SELECT>
     </spring:bind>
    </TD>
   </TR>
   <TR>
    <TD>
     <spring:bind path="command.*">
      <c:out value="${status.errorMessage}"/>
     </spring:bind>
    </TD>
   </TR>
   <TR>
    <TD align="center">
     <INPUT type="submit" value="提交" />
    </TD>
   </TR>
  </TBODY>
 </TABLE>
</FORM>

hello.jsp的主要部分:

<TABLE>
    <TBODY>
     <TR>
      <TD>
       User infor:
      </TD>
     </TR>
     <TR>
      <TD>
       <c:out value="${user.account}" />
      </TD>
     </TR>
     <TR>
      <TD>
       <c:out value="${user.age}" />
      </TD>
     </TR>
     <TR>
      <TD>
       <c:out value="${user.phone}" />
      </TD>
     </TR>
     <TR>
      <TD>
       <c:out value="${user.city}" />
      </TD>
     </TR>
     <TR>
      <TD>
       <c:out value="${user.createTime}" />
      </TD>
     </TR>
    </TBODY>
 </TABLE>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值