Struts2總結

一、         構建struts2框架的基本配置

1、  創建項目

2、  導入struts2的五個基本jar包: commons-logging-1.0.4.jar:日誌包、freemarker-2.3.13.jarognl-2.6.11.jarstruts2-core-2.1.6.jar:核心包、xwork-2.1.2.jarwebWork的核心包,struts2也依賴於它、commons-fileupload-1.2.1.jar

3、  配置項目下的web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <filter>

       <filter-name>struts2</filter-name>

       <filter-class>

           org.apache.struts2.dispatcher.FilterDispatcher

       </filter-class>

    </filter>

    <filter-mapping>

       <filter-name>struts2</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

</web-app>

4、  src目錄下創建struts2的配置文件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>

<package name="struts2" extends="struts-default">
    <action name="login" class="com.test.action.LoginAction">
        <result name="success">/result.jsp</result>
    </action>
</package>

</struts>

package裏的extends與類的繼承相似,struts-defaultstruts2裏已經存在的包 action裏的name與頁面裏表單裏的action的值

5、  com.test.action包下建相應的Action

public class LoginAction extends ActionSupport {

    private String username;

    private String password;

    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;

    }

    @SuppressWarnings("unchecked")

    public String execute() throws Exception {

       if ("hello".equals(this.getUsername().trim())

              && "world".equals(this.getPassword().trim())) {

                     @SuppressWarnings("unused")

           Map map=ActionContext.getContext().getSession();

           map.put("user","valid");

           return "success";

       }

       else{

           this.addFieldError("username","username or password error");

           return "failer";

       }

    }

    public void validate() {

       if (null == this.getUsername() || "".equals(this.getUsername().trim())) {

           this.addFieldError("username""username required");

       }

    if (null == this.getPassword() || "".equals(this.getPassword())) {

           this.addFieldError("password""password required");

       }

    }

}

:繼承ActionSupport類,實現Action

二、         struts2類型轉換

序:類型轉換就是客戶端用戶輸入的參數轉化爲服務器端java的對象,不管用戶輸入什麼樣的內容,到客戶端都是以字符串的形式存在。

1、  某個Action類或類對象的屬性需要類型轉換,則要寫一個.properties的屬性文件,使其能找到完成類型轉換的類,有兩種方式:

第一種是局部屬性文件,即在action包下創建,命名規則爲action類名-conversion.properties,在屬性文件裏是以keyvalue對形式存在,keystruts2要轉換的屬性名,value是轉換這個屬性的類。當用戶要轉換多個屬性裏可以換行加多個

第二種是全局屬性文件,即在src根目錄下創建一個名爲xwork-conversion.properties的屬性文件(名字不可以更改),在裏面寫配置信息。形式是:要轉換類的路徑=作爲轉換器的類路徑

2、  創建類型轉換的類

轉換類繼承StrutsTypeConverter類,分別實現它裏是面的convertToString(Map context, Object o)convertFromString(Map context, String[] values, Class toClass)兩個抽象方法,代碼如下:

public class PointConverter2 extends StrutsTypeConverter {

    public Object convertFromString(Map context, String[] values, Class toClass) {

       Point point = new Point();

       String[] paramValues = values[0].split(",");

       int x = Integer.parseInt(paramValues[0]);

       int y = Integer.parseInt(paramValues[1]);

       point.setX(x);

       point.setY(y);

       return point;

    }

    public String convertToString(Map context, Object o) {

       Point point = (Point) o;

       int x = point.getX();

       int y = point.getY();

       String result = " [ x=  " + x + ",  y=" + y + "]";

       return result;

    }

}

三、         struts2校驗

序:輸入校驗是驗證用戶輸入的信息是否合法是否有效。輸入校驗是建立在類型轉換的基礎之上的。若驗證有錯則顯示提示信息。輸入校驗的流程是:首先,類型轉換,然後校驗,若都沒錯則執行execute()方法,,若出錯,則跳轉到input指向的頁面。假若類型轉換不成功也要進行校驗。

1類型轉換,如果類型轉換失敗系統有默認的錯誤提示信息,改變這種系統的錯誤提示信息有兩種,就是有創建全局或局部的屬性文件,首先全局的是在classes目錄下寫屬性文件message.properties,內容是xwork.default.invalid.fieldvalue={0} error的鍵值對,在struts.xml中的配置是<constantname="struts.custom.i18n.resources" value="message"></constant>,其次局部的是在action包下創建“Action類名.properties”屬性文件,內容格式:invalid.fieldvalue.屬性名=要現實的信息。

2、校驗,struts2提供的多種校驗方式:

是在action中重寫validate()方法,在其內對各個參數進行校驗,校驗代碼如下:

public void validate() {

       if (null == username || username.length() < 6 || username.length() > 10) {

           this.addActionError("username invalid");

       }

       if (null == password || password.length() < 6 || password.length() > 10) {

           this.addActionError("password invalid");

       else if (null == repassword || repassword.length() < 6

              || repassword.length() > 10) {

           this.addActionError("repassword invalid");

       else if (!password.equals(repassword)) {

           this.addActionError("two password not the same");

       }

       if (age < 1 || age > 130) {

           this

                 .addActionError("\u8f93\u5165\u5e74\u9f84\u5e94\u8be5\u57280\u5c81\u5230120\u5c81\u4e4b\u95f4");

       }

        if(null==birthday){

        this.addActionError("birthday invalid");

        }

        if(null==graduation){

        this.addActionError("graduation invalid");

        }

       if (null != birthday && null != graduation) {

           Calendar c1 = Calendar.getInstance();

           c1.setTime(birthday);

           Calendar c2 = Calendar.getInstance();

           c2.setTime(graduation);

           if (!c1.before(c2)) {

              this.addActionError("birthday should before graduation");

           }

    }

:錯誤提示信息由action級別的,也有field級別的,field級別的,應在

<s:fielderror cssStyle="color:red" />標籤內顯示,action只需改fieldaction即可。可以用多種方式添加錯誤提示信息,可以在validate()方法中加入this.addActionError("password invalid");this.addFieldError("password""password invalid");以增加錯誤提示信息。

是最常用的xml校驗方式,即在action包下創建名稱爲“Action類名-validation.xml”文件,系統運行是會自動尋找該文件進行校驗,其格式參照第三章。這是對整個類的全局校驗方式,如果action類中有多個校驗方法,則用文件名爲”Action類名-方法名-validation.xml”的校驗文件對action類的某個方法進行校驗。Xml內容格式與全局是一樣的。

還以用js在客戶端進行驗證,使用方法是在struts2標籤form中加入onsubmit=”return validate();”,待驗證的每個struts標籤中都加入一個唯一標誌id,通過id獲得提交的屬性值。具體使用方法參照第三章。

四、         struts2校驗框架

對上述校驗的細化,可相對第四章。

五、         攔截器

1、創建攔截器類(這是一個驗證用戶是否登錄的實例):

public class AuthInterceptor extends AbstractInterceptor {

    public String intercept(ActionInvocation invocation) throws Exception {

       Map map = invocation.getInvocationContext().getSession();//得到execute()中保存在session中的值

       if (map.get("user") == null) {

           return Action.LOGIN;//若爲空則返回登錄頁面,需在struts.xml中配置

       else {

           return invocation.invoke();//若成功則到達指定頁面

       }

    }

}

sessionaction類(execute方法)中已經寫入,即

           @SuppressWarnings("unused")

           Map map=ActionContext.getContext().getSession();

           map.put("user","valid");

2、  配置struts.xml

Struts.xml中配置攔截器:

<interceptor name="auth" class="com.test.interceptor.AuthInterceptor">

</interceptor>

    //應用攔截器:

<interceptor-ref name="auth"></interceptor-ref>

<interceptor-ref name="defaultStack"></interceptor-ref>

若驗證用戶沒登錄則跳轉到登錄頁面,在struts.xml中配置全局action

<global-results>

    <result name="login" type="redirect">/login2.jsp</result>

</global-results>

注:注意一定要加入<interceptor-ref name="defaultStack"></interceptor-ref>默認攔截器棧,否則出錯。

六、         文件上傳下載

上傳

1、 導入兩個jar包:commons-io-1.3.2.jarcommons-fileupload-1.2.1.jar

2、 文件上傳jsp頁面:

表單代碼:

<s:form action="upload" theme="simple" enctype="multipart/form-data"

           method="post">

           <table align="center" border="1" width="50%">

              <tr>

                  <td>

                     file

                  </td>

                  <td id="more">

                     <s:file name="file"></s:file>

                     <input type="button" value="Add More.." onclick="addMore()">

                  </td>

              </tr>

              <tr>

                  <td>

                     <s:submit value="submit"></s:submit>

                  </td>

                  <td>

                     <s:reset value="reset"></s:reset>

                  </td>

              </tr>

           </table>

    </s:form>

js代碼:

       <script type="text/javascript">

    function addMore(){

       var td=document.getElementById("more");

       var br=document.createElement("br");

       var input=document.createElement("input");

       var button=document.createElement("input");

       input.type="file";

       input.name="file";

       button.type="button";

       button.value="Remove";

       button.onclick =function(){

           td.removeChild(br);

           td.removeChild(input);

           td.removeChild(button);

       }

       td.appendChild(br);

       td.appendChild(input);

       td.appendChild(button);

    }

</script>

3、  上傳文件的Action類核心代碼:

public class UploadAction extends ActionSupport {

    private List<File> file;//上傳多個文件用集合泛型

    private List<String> fileFileName;//文件名

    private List<String> fileContentType;//文件類型

    public List<File> getFile() {

       return file;

    }

    public void setFile(List<File> file) {

       this.file = file;

    }

    public List<String> getFileFileName() {

       return fileFileName;

    }

    public void setFileFileName(List<String> fileFileName) {

       this.fileFileName = fileFileName;

    }

    public List<String> getFileContentType() {

       return fileContentType;

    }

    public void setFileContentType(List<String> fileContentType) {

       this.fileContentType = fileContentType;

    }

    @Override

    public String execute() throws Exception {

       for (int i = 0; i < file.size(); i++) {

           InputStream is = new FileInputStream(file.get(i));

//         String root = ServletActionContext.getRequest().getRealPath(

//                "/upload");

//         String path="D://";

            String

            path=this.getClass().getResource("/").getPath();//得到d:/tomcat/webapps/工程名WEB-INF/classes/路徑

            path=path.substring(1,

            path.indexOf("WEB-INF/classes"));//從路徑字符串中取出工程路勁

            path=path+"/upload";

           File destFile = new File(path, this.getFileFileName().get(i));//在目的路徑下醫院文件名創建文件

           OutputStream os = new FileOutputStream(destFile);

           byte[] buffer = new byte[400];

           int length = 0;

           while ((length = is.read(buffer)) > 0) {

              os.write(buffer, 0, length);//寫入硬盤

           }

           is.close();

           os.close();

       }

       return SUCCESS;

    }

}

4、  struts.xml文件上傳配置

<action name="upload" class="com.test.action.UploadAction">

           <result name="success">/uploadResult.jsp</result>

           <result name="input">/upload.jsp</result>

           <interceptor-ref name="fileUpload">

              <param name="maximumSize">4096000</param>

              <param name="allowedTypes">application/vnd.ms-powerpoint</param>

           </interceptor-ref>

           <interceptor-ref name="defaultStack"></interceptor-ref>

    </action>

5、 上傳結果顯示頁面

username:<s:property value="username"/><br>

password:<s:property value="password"/><br>

file:<s:property value="fileFileName"/>

下載

1、超鏈接jsp下載頁面

    <s:a href="download.action">download</s:a>

2、下載核心代碼action

public class DownloadAction extends ActionSupport {

    public InputStream getDownloadFile(){ 

       return ServletActionContext.getServletContext().getResourceAsStream("/upload/struts.ppt");

    }

    @Override

    public String execute() throws Exception {      

       return SUCCESS;

    }

}

3、 struts.xml配置

<action name="download" class="com.test.action.DownloadAction">

           <result name="success" type="stream">

              <param name="contentType">application/vnd.ms-powerpoint</param>

              <param name="contentDisposition">filename="struts.ppt"</param>

              <param name="inputName">downloadFile</param>

           </result>

    </action>

七、         struts2國際化

詳細請參照第七章

發佈了22 篇原創文章 · 獲贊 21 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章