一.使用ModelDriven Action
在Struts2中提供另一种直接使用领域对象的方法,就是Action实现com.opensymphony.xwork2.ModelDriven接口,可以让你直接操作应用程序中的领域对象.
ModelDriven接口中只有一个方法,如:
public T getModel();
该方法返回一个用于接收用户输入数据的模型对象,在页面中,这个模型对象中的属性可以直接通过属性名来访问(如name),而不需要 user.name .在Action也不需要提供类的get/set方法.
LoginAction.java
package com.action;
import com.entity.User;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;
public class LoginAction implements Action, ModelDriven<User> {
public LoginAction() {
System.out.println("in LoginAction");
}
private User user = new User();//直接实例化
@Override
public User getModel() {
System.out.println(" in getModel");
return user;
}
@Override
public String execute() throws Exception {
System.out.println(" in execute");
if ("mgc".equalsIgnoreCase(user.getName()) && "mgc".equals(user.getPassword()))
return SUCCESS;
else
return ERROR;
}
}
声明User对象时,直接将基实例化,然后通过 getModel方法返回.
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆页面</title>
</head>
<body>
<form action="loginAction.action" method="post">
<table>
<tr>
<td>name:</td>
<td><input name="name" /></td>
</tr>
<tr>
<td>password:</td>
<td><input name="password" type="password"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登陆" /></td>
</tr>
</table>
</form>
</body>
</html>
在login.jsp页面,不需要在user.name 这样的格式了.
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>欢迎页面</title>
</head>
<body>
欢迎您 : <s:property value="name"/>
</body>
</html>
不需要在user.name 这样的格式了.
项目完成
控制台输出
in User
in LoginAction
in getModel
in getModel
in execute
为什么先进入了User类? 不应该先进入LoginAction吗?
为什么执行了2次 getModel方法 ?
更新中...