詳解在Java的Struts2框架中設置裝備擺設Action的辦法。本站提示廣大學習愛好者:(詳解在Java的Struts2框架中設置裝備擺設Action的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解在Java的Struts2框架中設置裝備擺設Action的辦法正文
在Struts2中Action部門,也就是Controller層采取了低侵入的方法。為何這麼說?這是由於在Struts2中action類其實不須要繼續任何的基類,或完成任何的接口,更沒有與Servlet的API直接耦合。它平日更像一個通俗的POJO(平日應當包括一個無參數的execute辦法),並且可以在內容界說一系列的辦法(無參辦法),並可以經由過程設置裝備擺設的方法,把每個辦法都看成一個自力的action來應用,從而完成代碼復用。
例如:
package example;
public class UserAction {
private String username;
private String password;
public String execute() throws Exception {
//…………..
return “success”;
}
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;
}
}
action拜訪servlet
在這個Action類裡的屬性,既可以封裝參數,又可以封裝處置成果。體系其實不會嚴厲辨別它們。
然則為了應用戶開辟的Action類更標准,Struts2為我們供給了一個接口Action,該類界說以下:
publicinterface Action {
publicstaticfinal String ERROR="error";
publicstaticfinal String INPUT="input";
publicstaticfinal String NONE="none";
publicstaticfinal String LOGIN="login";
publicstaticfinal String SUCCESS="success";
public String execute()throws Exception;
}
然則我們寫Action平日不會完成該接口,而是繼續該接口的完成類ActionSupport.
該類代碼以下:
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {
................
public void setActionErrors(Collection errorMessages) {
validationAware.setActionErrors(errorMessages);
}
public Collection getActionErrors() {
return validationAware.getActionErrors();
}
public void setActionMessages(Collection messages) {
validationAware.setActionMessages(messages);
}
public Collection getActionMessages() {
return validationAware.getActionMessages();
}
public Collection getErrorMessages() {
return getActionErrors();
}
public Map getErrors() {
return getFieldErrors();
}
//設置表單域校驗毛病
public void setFieldErrors(Map errorMap) {
validationAware.setFieldErrors(errorMap);
}
public Map getFieldErrors() {
return validationAware.getFieldErrors();
}
public Locale getLocale() {
ActionContext ctx = ActionContext.getContext();
if (ctx != null) {
return ctx.getLocale();
} else {
LOG.debug("Action context not initialized");
return null;
}
}
//獲得國際化信息的辦法
public String getText(String aTextName) {
return textProvider.getText(aTextName);
}
public String getText(String aTextName, String defaultValue) {
return textProvider.getText(aTextName, defaultValue);
}
public String getText(String aTextName, String defaultValue, String obj) {
return textProvider.getText(aTextName, defaultValue, obj);
}
.........
//用於拜訪國際化資本包的辦法
public ResourceBundle getTexts() {
return textProvider.getTexts();
}
public ResourceBundle getTexts(String aBundleName) {
return textProvider.getTexts(aBundleName);
}
//添加action的毛病信息
public void addActionError(String anErrorMessage) {
validationAware.addActionError(anErrorMessage);
}
//添加action的通俗信息
public void addActionMessage(String aMessage) {
validationAware.addActionMessage(aMessage);
}
public void addFieldError(String fieldName, String errorMessage) {
validationAware.addFieldError(fieldName, errorMessage);
}
public void validate() {
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
..........
}
後面說到struts2並沒有直接與Servlet的API耦合,那末它是怎樣拜訪Servlet的API的呢?
本來struts2中供給了一個ActionContext類,該類模仿了Servlet的API。其重要辦法以下:
1)Object get (Object key):該辦法模仿了HttpServletRequest.getAttribute(String name)辦法。
2)Map getApplication()前往一個Map對象,該對象模仿了ServletContext實例.
3)static ActionContext getContext():獲得體系的ActionContext實例。
4)Map getSession():前往一個Map對象,該對象模仿了HttpSession實例.
5)Map getParameters():獲得一切的要求參數,模仿了HttpServletRequest.getParameterMap()
你或許會奇異為何這些辦法總是前往一個Map?這重要是為了便於測試。至於它是怎樣把Map對象與現實的Servlet API的實例停止轉換的,這個我們基本就不要擔憂,由於struts2曾經內置了一些攔阻器來幫我們完成這一轉換。
為了直接應用Servlet的API,Struts2為我們供給了以下幾個接口。
1)ServletContextAware:完成該接口的Action可以直接拜訪ServletContext實例。
2)ServletRequestAware:完成該接口的Action可以直接拜訪HttpServletRequest實例。
3)ServletResponseAware:完成該接口的Action可以直接拜訪HttpServletResponse實例。
以上重要講了action拜訪servlet,上面讓我們來看一下Struts2的Action是若何完成代碼復用的。就拿UserAction來講,我假如讓這個action既處置用戶注冊(regist)又處置登錄(longin)該若何改寫這個action呢?改寫後的UserAction以下:
package example;
public class UserAction extends ActionSupport {
private String username;
private String password;
public String regist() throws Exception {
//…………..
return SUCCESS;
}
public String login() throws Exception {
//…………..
return SUCCESS;
}
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;
}
}
struts.xml中的action設置裝備擺設
是否是這麼寫就ok了,固然不可我們還必需在struts.xml文件中設置裝備擺設一下。設置裝備擺設辦法有兩種:
1) 應用通俗的方法為Action元素指定method屬性.
<action name=”loginAction” class=”example.UserAction” method=”login”>
<result name=”success”>/success.jsp</result>
</action>
<action name=”registAction” class=”example.UserAction” method=”regist”>
<result name=”success”>/success.jsp</result>
</action>
2) 采取通配符的方法為Action元素指定method屬性。
<action name=”*Action” class=”example.UserAction” method=”{1}”>
<result name=”success”>/success.jsp</result>
</action>
應用通配符的方法過於靈巧,上面是一個較龐雜的設置裝備擺設情形。
<action name=”*_*” class=”example.{1}Action” method=”{2}”>
……….
</action>
個中占位符{1}與_的前一個*婚配,{2}與後一個*婚配。
基於注解方法Action設置裝備擺設:
上面要說的Action的設置裝備擺設不是在src/struts.xml中,而是用注解方法來停止設置裝備擺設的
條件是除根本的那六個jar包以外,還須要一個struts-2.1.8.1\lib\struts2-convention-plugin-2.1.8.1.jar
不外struts.xml照樣要有的
詳細示例
Login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Struts2登錄驗證</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h3>Struts2登錄</h3><hr/>
<form action="${pageContext.request.contextPath}/user/login.qqi" method="post">
<table border="1" width="500px">
<tr>
<td>用戶名</td>
<td><input type="text" name="loginname"/></td>
</tr>
<tr>
<td>暗碼</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登錄"/></td>
</tr>
</table>
</form>
</body>
</html>
src/struts.xml
<span ><?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <!-- 要求參數的編碼方法 --> <constant name="struts.i18n.encoding" value="UTF-8"/> <!-- 指定被struts2處置的要求後綴類型。多個用逗號離隔 --> <constant name="struts.action.extension" value="action,do,go,qqi"/> <!-- 當struts.xml修改後,能否從新加載。默許值為false(臨盆情況下應用),開辟階段最好翻開 --> <constant name="struts.configuration.xml.reload" value="true"/> <!-- 能否應用struts的開辟形式。開辟形式會有更多的調試信息。默許值為false(臨盆情況下應用),開辟階段最好翻開 --> <constant name="struts.devMode" value="false"/> <!-- 設置閱讀器能否緩存靜態內容。默許值為true(臨盆情況下應用),開辟階段最好封閉 --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 指定由spring擔任action對象的創立 <constant name="struts.objectFactory" value="spring" /> --> <!-- 能否開啟靜態辦法挪用 --> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> </struts></span>
LoginAction.java
package com.javacrazyer.web.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;
/**
* 應用注解來設置裝備擺設Action
*
*/
@ParentPackage("struts-default")
// 父包
@Namespace("/user")
@Results( { @Result(name = "success", location = "/msg.jsp"),
@Result(name = "error", location = "/error.jsp") })
@ExceptionMappings( { @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") })
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = -2554018432709689579L;
private String loginname;
private String pwd;
@Action(value = "login")
public String login() throws Exception {
if ("qq".equals(loginname) && "123".equals(pwd)) {
return SUCCESS;
} else {
return ERROR;
}
}
@Action(value = "add", results = { @Result(name = "success", location = "/index.jsp") })
public String add() throws Exception {
return SUCCESS;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
success.jsp和error.jsp我就不貼出來了
注解設置裝備擺設的說明
1) @ParentPackage 指定父包
2) @Namespace 指天命名空間
3) @Results 一組成果的數組
4) @Result(name="success",location="/msg.jsp") 一個成果的映照
5) @Action(value="login") 指定某個要求處置辦法的要求URL。留意,它不克不及添加在Action類上,要添加到辦法上。
6) @ExceptionMappings 一級聲明異常的數組
7) @ExceptionMapping 映照一個聲明異常
因為這類方法不是很經常使用,所以年夜家只做懂得便可