---
title: "struts2驱动模型的使用(Action类实现ModelDriven接口)"
author: "wanglihu"
date: "2012-02-13T20:35:23Z"
tags: ["Preparable", "Struts2", "modeldriven"]
categories: ["开源软件"]
slug: "struts2-action-modeldriven"
draft: false
lastmod: "2012-02-14T16:19:13Z"
id: 1404849
url: "https://wanglihu.iteye.com/blog/1404849"
---

struts2驱动模型的使用实例： 1.modelDriven.jsp \[code="jsp"]&lt;%@ page language="java" import="java.util.\*" pageEncoding="gb2312"%&gt; &lt;%@ taglib uri="/struts-tags" prefix="s"%&gt; 模型驱动类测试 \[/code] 2.modelDrivenSuccess.jsp \[code="jsp"]&lt;%@ page language="java" import="java.util.\*" pageEncoding="gb2312"%&gt; &lt;%@ taglib uri="/struts-tags" prefix="s"%&gt; 模型驱动类结果页面

username ${requestScope.username } password ${requestScope.password } repassword ${requestScope.repassword } age ${requestScope.age } birthday ${requestScope.birthday } graduation ${requestScope.graduation }

\[/code] 3.User.java(POJO) \[code="java"]package com.hitsoft.model; import java.util.Date; public class User { private String username; private String password; private String repassword; private int age; private Date birthday; private Date graduation; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Date getGraduation() { return graduation; } public void setGraduation(Date graduation) { this.graduation = graduation; } }\[/code] 4.ModelDrivenAction类 \[code="java"]package com.hitsoft.action; import com.hitsoft.model.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; //Preparable是在execute()方法调用之前执行的 @SuppressWarnings("unchecked") public class ModelDrivenAction extends ActionSupport implements ModelDriven,Preparable{ private User user = new User(); public User getModel() { return user; } public String execute(){ System.out.println("execute invoked!"); return SUCCESS; } public void prepare() throws Exception { System.out.println("prepare invoked!"); } }\[/code] 5.struts.xml \[code="xml"] /modelDrivenSuccess.jsp /modelDriven.jsp \[/code] 6.访问地址： http://localhost:8080/struts2/modelDriven.jsp