您的位置:首页 > 编程语言 > Java开发

Struts2的ValueStack工作原理

2015-06-18 20:10 696 查看


***struts.xml***
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<!--设置默认后缀名  -->
<constant name="struts.action.extension" value="action,do"/>
<constant name="struts.configuration.xml.reload" value="true"></constant>
<package name="default" namespace="/" extends="struts-default">
<action name="*_*" class="org.zttc.itat.action.{1}Action" method="{2}">
<result>/WEB-INF/{1}/{2}.jsp</result>
<!-- 客户端跳转 -->
<result type="redirect" name="r_list">/{1}_list.action</result>
</action>
</package>
</struts>


***UserAction.java***
package org.zttc.itat.action;
import org.apache.struts2.ServletActionContext;
import org.zttc.itat.model.User;
import com.opensymphony.xwork2.ActionContext;
public class UserAction {
private String username;
private String password;

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 addInput(){
System.out.println(username+","+password);
return "success";
}

public String add(){
System.out.println("add");
return "r_list";
}

public String list(){
//valueStack中的actionContext部分
ActionContext.getContext().put("aaa", 12345);
ActionContext.getContext().put("bbb", 23456);
ActionContext.getContext().put("ccc", "abc");
ServletActionContext.getRequest().setAttribute("ddd", "123");
//valueStack中的CompoundRoot部分
User u = new User("1","laozhang","老张");
ActionContext.getContext().getValueStack().push(u);
return "success";
}
}


***list.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>Insert title here</title>
</head>
<body>
<h1>User list</h1>
<!-- 此处是获取actionContext中内容 -->
<s:property value="#aaa"/>
<!-- 此处是获取CompoundRoot中内容 -->
<s:property value="#root[0].username"/>
<s:property value="#root[0].password"/>
<s:debug/>
</body>
</html>


验证步骤:
1.输入http://localhost:8090/struts2/User_list.do?username=张三&password=password
2.由于<s:property value="#root[0].password"/>中没有password所以从UserAction中获取
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struts