Struts2初级教程02 登陆demo ModelDriven

一.使用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方法 ?



更新中...









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值