Struts2 ( 二 )

Result結果配置

全局結果

package標籤中配置global-results標籤java

<package name="xxx" namespace="/" extends="struts-default">
	<global-results>
		<result name="xxx">xxx.jsp</result>
	</global-results>
</package>

做用是爲package中配置的全部action提供全局的返回結果頁面web

局部結果

action標籤中配置result標籤json

<action name="xxx" method="xxx"
	class="xxx">
	<result>xxx.jsp</result>
</action>

做用是爲當前action配置結果頁面緩存

結果類型

結果類型是在父類配置struts-default中定義的,struts框架默認實現了絕大多數的。
經常使用的結果類型有:服務器

  1. dispatcher:轉發。爲result標籤的默認值。app

    <result type="dispatcher">xxx.jsp</result>

    由action轉發到jsp。框架

    result標籤中配置的結果必須是jsp頁面jsp

  2. chain:轉發。ide

    <result type="chain">
    	<param name="actionName">xxx.action</param>
    </result>

    由action轉發到action。函數

    result標籤中配置的結果必須是action

  3. redirect:重定向。

    <result type="redirect">
    	<param name="location">xxx.jsp</param>
    </result>

    由action重定向到jsp。

    result標籤中配置的結果必須是jsp頁面

  4. redirectAction:重定向。

    <result type="redirectAction">
    	<param name="actionName">xxx.action</param>
    </result>

    由action重定向到action。

    result標籤中配置的結果必須是action

  5. stream: 結果爲文件流。文件下載

    <result name="success" type="stream">
    	<param name="contentType">image/jpeg</param>
    	<param name="inputName">imageStream</param>
    	<param name="contentDisposition">attachment;filename="document.pdf"</param>
    	<param name="bufferSize">1024</param>
    </result>

    contentType:下載文件類型

    contentDisposition:下載到客戶端時,客戶端文件名稱

    bufferSize:讀文件的緩存大小

    inputName:對應要輸出到客戶端流聲明的名稱

  6. json:轉發。

    <package name="xxx" namespace="/xxx" extends="json-default">
    	<action name="json" method="xxx"
    		class="org.itpx.struts.action.JsonAction">
    		<result name="success" type="json">
    			<param name="encoding">utf-8</param>
    			<param name="root">jsonObject</param>
    		</result>
    	</action>	
    </package>

    由action轉發到json結果

    encoding:配置編碼格式

    root:配置對象。action類中必須提供一個和root值相同的屬性名稱,且須要提供getter方法。

  7. jsonActionRedirect: 重定向。

    <action name="xxx" method="xxx"
    		class="org.ithpx.struts.action.JsonAction">
    		<result name="success" type="jsonActionRedirect">
    			xxx.action
    		</result>
    </action>

    由action重定向到json結果。

json Plugin的加載

  1. 拷貝struts2-json-plugin-xxx.jar
  2. 讓package繼承json-default

Struts與Servlet交互對接

解決的問題

客戶端與服務端交互時,一般會帶參數過來,服務器也會回寫數據給客戶端。在此過程當中,參與着請求,和響應,以及會話。servlet在此過程當中提供了HttpServletRequest做爲獲取請求數據的方案,HttpServletResponse做爲響應的方案,HttpSession負責了會話方案。Struts實際上是基於servlet實現的web框架,他須要遵循規則提供請求,響應和會話的API供開發人員使用,所以Struts針對這一問題提供了本身的一套API封裝,提供了多種方式的訪問。

ActionContext

  1. ActionContext對象實例獲取

    ActionContext context = ActionContext.getContext();

    ActionContext是綁定在當前線程中的。框架在請求線程開啓時,將ActionContext實例對象就綁定上來了,所以咱們能夠經過靜態方法直接獲取

  2. 請求參數的得到

    Map<String, Object> parameters = context.getParamters();

    至關於Servlet中的request.getParamters()方法

  3. 數據回顯到頁面

    context.put(key, value);

    至關於Servlet中的request.setAttribute()方法

ServletActionContext

  1. Servlet繼承子ActionContext,所以具有ActionContext的一切功能。
  2. ServletActionContext是對ActionContext功能的擴展,提供了多個靜態方法。
  3. 請求得到
    HttpServletRequest request = ServletActionContext.getRequest();
  4. 響應得到
    HttpServletResponse response = ServletActionContext.getResponse();

接口實現類得到

  • ServletContextAware
  • ServletRequestAware
  • ServletResponseAware
  • ParameterAware
  • SessionAware
  • ApplicationAware
  • PrincipalAware

Struts數據的封裝

靜態參數封裝

  1. 頁面表單
    <input type="text" name="name">
    <input type="text" name="password">
  2. action標籤中配置param標籤
    <param name="name" />
    <param name="password" />
  3. action類
    private String name;
    private String password;
    public void setName(String name) {
    this.name = name;
    }
    public void setPassword(String password) {
    this.password = password;
    }
    1. 要求頁面表單中的key和param標籤中name一致
    2. 要求頁面表單中的key和aciotn類中的屬性名一致
    3. action類中的屬性須要提供setter方法

屬性驅動:基本數據類型封裝

  1. 頁面表單
    <input type="text" name="name">
    <input type="text" name="password">
  2. action類
    private String name;
    private String password;
    public void setName(String name) {
    this.name = name;
    }
    public void setPassword(String password) {
    this.password = password;
    }
    1. 要求頁面中提供的key和action類中屬性名稱必須一致
    2. action類中必須提供屬性的setter方法

頁面表達式:對象封裝

  1. 頁面表單
    <input type="text" name="user.name">
    <input type="text" name="user.password">
  2. action類
    private User user;
    public void setUser(User user) {
    this.user = user;
    }
    public User getUser() {
    return user;
    }
    1. 頁面中的key至關於對象.屬性
    2. action中的對象名稱須要要和頁面中key的對象名稱相同
    3. action中的對象中的屬性名稱要和頁面中key的對象的屬性相同
    4. action中的對象必須提供無參構造函數
    5. action中的對象必須提供getter和setter

模型驅動:對象封裝

  1. 頁面表單
    <input type="text" name="name">
    <input type="text" name="password">
  2. Aciton類須要實現ModelDriven接口,而且實現接口方法
    public class Action03 extends ActionSupport implements ModelDriven<User> {
    private User user;
    @Override
    public User getModel() {
    	if (user == null) {
    		user = new User();
    	}
    	return user;
    }
    }

    頁面中的key的名稱須要和模型對象的名稱一致

List數據

  1. 頁面表單
    <input type="text" name="list[0].name">
    <input type="text" name="list[0].age">
    <input type="text" name="list[1].name">
    <input type="text" name="list[1].age">
  2. action類
    public class DataAction05 extends ActionSupport {
    	private List<User> list;
    	public List<User> getList() {
    		return list;
    	}
    	public void setList(List<User> list) {
    		this.list = list;
    	}
    	public String test() {
    		System.out.println(list);
    		return SUCCESS;
    	}
    }

Map數據

  1. 頁面表單
    <input type="text" name="map['a'].name">
    <input type="text" name="map['a'].age">
    <input type="text" name="map['b'].name">
    <input type="text" name="map['b'].age">
  2. action類
    public class DataAction05 extends ActionSupport {
    	private Map<String, User> map;
    	public Map<String, User> getMap() {
    		return map;
    	}
    	public void setMap(Map<String, User> map) {
    		this.map = map;
    	}
    }

類型轉換器

解決的問題

客戶端傳輸過程當中傳輸特定類型的字符串時,到action類中須要轉換爲對應的對象時,中間的轉換的問題。
主要解決的是對象類型的轉換

配置方案

  1. 新建一個類繼承StrutsTypeConverter,實現內部方法
    public class DateConversion extends StrutsTypeConverter {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
    	if (values != null && values.length > 0) {
    		String dateString = values[0];
    		try {
    			return sdf.parse(dateString);
    		} catch (ParseException e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
    	return null;
    }
    @Override
    public String convertToString(Map context, Object o) {
    	if (o != null && o instanceof Date) {
    		return sdf.format(o);
    	}
    	return null;
    }
    }
  2. 在項目的src下新建xwork-conversion.properties,在其中配置要轉換的類型
    java.util.Date=org.itheima.struts.action.DateConversion

UnknowHandler未知處理器

解決的問題

UnknowHandler未知處理器是用來解決,用請求未知Action,或指定action裏的未知方法,或者action處理結束以後返回一個未知result時,沒有結果等狀況的

UnknownHandler接口

接口提供了三個方法要求子類實現。

  • handleUnknownAction:當用戶請求了未知的action時的回調。
  • handleUnknownActionMethod: 當用戶請求了Action中未知方法的回調。目前被廢棄了
  • handleUnKnownResult: 當action處理結束後返回未知result的回調。

使用步驟

  1. 新建一個類實現UnknowHandler接口
  2. 根據需求實現接口中的方法
    • handleUnknownAction內部實現

      String newNamespace = "/unknow";
      String newActionName = "test";
      ConfigurationManager cfgManager = Dispatcher.getInstance().getConfigurationManager();
      RuntimeConfiguration runtimeCfg = cfgManager.getConfiguration().getRuntimeConfiguration();
      ActionConfig actionConfig = runtimeCfg.getActionConfig(newNamespace, newActionName);
      return actionConfig;

      若是沒有找到請求的action,經過此方法轉到配置的新的action中。

      所以,須要在配置中配置一個新的action。

    • handleUnKnownResult內部實現

      String location = "/unknowresult.jsp";
      return new ServletDispatcherResult(location);

      若是action處理了,結果爲爲未知類型。
      出問題的基本都是開發人員在開發過程當中的編碼不仔細的問題。
      此類問題開發階段就要被扼殺。

  3. struts.xml中用bean標籤配置加載此實現的對象

    <bean name="handler" type="com.opensymphony.xwork2.UnknownHandler"
    	class="org.itheima.struts.handler.MyunkownHandler"></bean>
  4. 新建unkown-hanlder-ref標籤註冊此bean
    <unknown-handler-stack>
    	<unknown-handler-ref name="handler" />
    </unknown-handler-stack>

Exception捕獲

解決的問題

當action代碼執行中出現異常時,錯誤信息會反饋到客戶頁面,用戶體驗很差

局部異常捕獲

  • action標籤中配置exception-mapping標籤
    1
    2
    3<result name="xxx" type="redirect">/xxx.jsp</result>
    <exception-mapping result="xxx"
    exception="java.lang.Throwable" />
  • exception-mapping標籤中的result屬性指向捕獲異常後出錯的頁面結果。
  • exception-mapping標籤中的exception屬性指的是要捕獲那種異常。

全局異常捕獲

  • package標籤中配置global-exception-mapping標籤
    <global-results>
    	<result name="xxx">xxx.jsp</result>
    </global-results>
    <global-exception-mappings>
    	<exception-mapping result="xxx"
    			exception="java.lang.Throwable">
    	</exception-mapping>
    </global-exception-mappings>
  • global-exception-mapping標籤中的result屬性指向捕獲異常後出錯的頁面結果。
  • global-exception-mapping標籤中的exception屬性指的是要捕獲那種異常。

異常顯示

異常捕獲的做用是爲了提示用戶界面的顯示結果,但若是出錯了,開發人員是要知道錯誤日誌的。

若是要開啓錯誤日誌,在action標籤中配置以下:

<interceptor-ref name="defaultStack">
	<param name="exception.logEnabled">true</param>
	<param name="exception.logLevel">error</param>
</interceptor-ref>
相關文章
相關標籤/搜索