第17講 struts2設定全域性
阿新 • • 發佈:2018-11-11
全域性變數是一個包內所有action都可能用到的,首先檢查自己的<action>標籤內是否有匹配的result字串,如果沒有去去全域性變數中找
1在HeadFirstStruts2chapter02_07中,新建HelloAction,error屬性,設定邏輯程式碼。返回值"error"
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport{
private
public String getError() {
return error;
}
public void setError(String error) {
this
}
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"
<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/