1. 程式人生 > >第15講 struts2標籤巢狀

第15講 struts2標籤巢狀

鏈條方式指,struts.xml中,在一個result結果直接跳轉到另外一個action中,資料可以共享,
1在HeadFirstStruts2chapter02_07中,新建HelloAction2,name2屬性,get() set()方法,在預設的execute()方法中給 name2賦值,

package com.cruise.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction2 extends ActionSupport{
    
    private

 String name2 ;
    
    public String getName2() {
       return name2;
    }

    public void setName2(String name2) {
       this
.name2 = name2;
    }

    @Override
    public String execute() throws Exception {
       this.name2="love Ashley";
       return SUCCESS;
    }
}
2修改HelloAction,寫方法chain()方法,返回字串"chain2"

package com.cruise.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport{
    
    private String name ;
    

    public String getName() {
       return name;
    }

    public void setName(String name) {
       this.name = name;
    }
    public String chain(){
       return "chain2";
    }
}
3配置struts.xml檔案,配置新的
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
<package name="manage" namespace="/" extends="struts-default">
    <action name="hello" class="com.cruise.action.HelloAction" >
       <result name="chain2" type="chain" >hello2</result>
    </action>
    <action name="hello2" class="com.cruise.action.HelloAction2" >
       <result name="success" type="dispatcher" >success.jsp</result>
    </action>
</package>
</struts>
4修改success.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>Insert title here</title>
</head>
<body>
name:${name}<br>
naem2:${name2}
</body>
</html>
5index.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>Insert title here</title>
</head>
<body>
<a href="hello!chain?name=cruise" target="_blank">內部轉發</a>
</body>
</html>
5測試-執行,檢視${name}和${name2}是否取到值-資料共享
http://localhost:8080/HeadFirstStruts2chapter02_07/