第17讲 struts2设置全局

全局变量是一个包内所有action都可能用到的,首先检查自己的<action>标签内是否有匹配的result字符串,如果没有去去全局变量中找
1在HeadFirstStruts2chapter02_07中,新建HelloAction,error属性,设置逻辑代码。返回值"error"

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport{
    
    private String error ;
    
    public String getError() {
       return error;
    }

    public void setError(String error) {
       this.error = error;
    }

    public String error(){
       return "error2";
    }
}
2在struts.xml中,设置error的全局变量,
<?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">
    <global-results>
       <result name="error2">error.jsp</result>
    </global-results>
    <action name="hello" class="com.cruise.action.HelloAction" >
       <result name="redirectAction2" type="redirectAction" >hello2</result>
    </action>
</package>
</struts>

3index.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!error?error=您点击的页面有误!!" target="_blank">全局变量</a>
</body>
</html>
4error.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>
错误提示:${error}
</body>
</html>
5在struts.xml中,现在中找的name为error,如果找不到,再去全局变量中找name为"error"的标签
6测试

http://localhost:8080/HeadFirstStruts2chapter02_07/

猜你喜欢

转载自blog.csdn.net/u010393325/article/details/83928672