struts使用ModelDriven获得页面数据

input.jsp中可以直接使用User对象的属性:

  <body>
    <s:form action="AddUserModelAction">
    <s:textfield name="userName" label="Your name" />
    <s:textfield name="address.address" label="Your address" />
    <s:textfield name="address.zipCode" label="Your zipCode" />
    <s:textfield name="address.phone" label="Your phone" />
    <s:submit/>
   </s:form>
  </body> 

 

success.jsp中可以直接访问User对象的属性:

  <body>
    <h4>User: <s:property value="userName" /> add success(by Model).</h4>
    <h4>Address:<s:property value="address.address" /></h4>
    <h4>zipCode:<s:property value="address.zipCode" /></h4>
    <h4>phone  :<s:property value="address.phone" /></h4>
  </body>

 

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.jaeson.hibernatestudy.bean.User;
import com.jaeson.springstudy.service.CommonService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("all")
@Scope("prototype")
@Controller("userModelAction")
public class UserModelAction extends ActionSupport implements ModelDriven<User> {

	/**
	 * 在执行execute时,ValueStack已经获得模型对象的引用,在整个请求过程中框架一直使用该引用。
	 * 如果在execute内部改变了模型字段,框架不会察觉,这可能会导致数据不一致的问题。
	 */
	@Override
	public String execute() {
		
		this.getCommonService().saveOrUpdate(this.user);
		//throw new RuntimeException("throw in UserAction");
		return "success";
	}
	
	@Override
	public void validate() {
		
		if (this.user.getUserName().length() == 0) {
			this.addFieldError("userName", "userName is required.");
		}
	}
	
	private User user = new User();
	@Resource(name = "commonService")
	private CommonService commonService;
	
	@Override
	public User getModel() {
		
		return this.user;
	}

	public CommonService getCommonService() {
		return this.commonService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值