Struts2(接受表單參數)請求數據自動封裝和數據類型轉換


Struts2請求數據自動封裝:

  (1)實現原理:參數攔截器

  (2)方式1:jsp表單數據填充到action中的屬性;

         普通的成員變量,必須給set,get可以不給的。

       注意點,Action中定義成員變量,成員變量的setXxx方法名中的Xxx和表單中name屬性提交的參數對應起來的;

  (3)方式2:領域模型接受表單的參數(常用),jsp表單數據填充到action的對象的屬性;

         對象類型,一定給get方法。

       注意點:Action中定義封裝的實體類對象如private User user,並給set,get方法,在jsp頁面需要注意是user.id;

  (4)方式3:模型驅動接受表單的參數,了解即可,這里省略;


1:方式1:

第一步:引包,省去

第二步:配置struts2的過濾器

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 3   <display-name>struts2_20170221</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   
13   <!-- struts2過濾器 -->
14   <filter>
15       <!-- 過濾器名稱 -->
16       <filter-name>struts2</filter-name>
17       <!-- 過濾器類 -->
18       <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
19   </filter>
20   <!-- struts2過濾器映射 -->
21   <filter-mapping>
22       <!-- 過濾器名稱 -->
23       <filter-name>struts2</filter-name>
24       <!-- 過濾器映射 -->
25       <url-pattern>/*</url-pattern>
26   </filter-mapping>
27   
28 </web-app>

第三步:開發Action

 1 package com.bie.type;
 2 
 3 import java.util.Date;
 4 
 5 import com.opensymphony.xwork2.ActionSupport;
 6 
 7 /** 
 8 * @author BieHongLi 
 9 * @version 創建時間:2017年2月21日 下午8:39:13 
10 * Struts2的核心業務,請求數據自動封裝和類型轉換
11 * 這個繼承不繼承即可extends ActionSupport,習慣繼承了
12 */
13 public class TypeAction extends ActionSupport{
14 
15 
16     private static final long serialVersionUID = 1L;
17     private String name;
18     private String password;
19     private int age;
20     private Date birthday;//Date日期類型,導入的utilsl類型的
21     
22     //普通的成員變量,必須給set,get可以不給的。
23     public String getName() {
24         return name;
25     }
26     public String getPassword() {
27         return password;
28     }
29     public int getAge() {
30         return age;
31     }
32     public Date getBirthday() {
33         return birthday;
34     }
35 
36 
37     //處理注冊請求,String類型的,不能帶參數的
38     public String register() {
39         System.out.println(name+" "+password+" "+age+" "+birthday);
40         return SUCCESS;
41     }
42 }

第四步:配置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="finalPackage" extends="struts-default">
        <action name="requestAction" class="com.bie.finalImpl.FinalAction">
            <result name="success">success.jsp</result>
        </action>
        
        <action name="ImplAction" class="com.bie.finalImpl.ImplAction">
            <result name="success">success.jsp</result>
        </action>
        
        <action name="type_*" class="com.bie.type.TypeAction" method="{1}">
            <result name="success">show.jsp</result>
        </action>
    </package>
    
</struts>

第五步:注冊頁面index.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>表單提交的頁面</title>
 8 </head>
 9 <body>
10 <form action="${pageContext.request.contextPath}/type_register.action" method="post">
11     賬號:<input type="text" name="name"/>
12     密碼:<input type="password" name="password"/>
13     年齡:<input type="text" name="age"/>
14     出生:<input type="text" name="birthday"/>
15     <input type="submit" value="注冊"/>
16 </form>
17 </body>
18 </html>

第六步:顯示頁面show.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>顯示的頁面</title>
 8 </head>
 9 <body>
10 <h1>Struts2的進行數據封裝和類型轉換的使用</h1>
11 </body>
12 </html>

 方式2:

第一步:引包,省去

第二步:配置struts2的過濾器,和上面的一樣

第三步:開發Action

 1 package com.bie.type;
 2 
 3 import java.util.Date;
 4 
 5 import com.opensymphony.xwork2.ActionSupport;
 6 
 7 /** 
 8 * @author BieHongLi 
 9 * @version 創建時間:2017年2月21日 下午8:39:13 
10 * Struts2的核心業務,請求數據自動封裝和類型轉換
11 * 這個繼承不繼承即可extends ActionSupport,習慣繼承了
12 */
13 public class TypeAction extends ActionSupport{
14 
15 
16     private static final long serialVersionUID = 1L;
17     private User user;//對象類型,一定給get方法
18     public User getUser() {
19         return user;
20     }
21     public void setUser(User user) {
22         this.user = user;
23     }
24     
25     //處理注冊請求,String類型的,不能帶參數的
26     public String register() {
27         System.out.println(user.getName());
28         System.out.println(user.getPassword());
29         System.out.println(user.getAge());
30         System.out.println(user.getBirthday());
31         return SUCCESS;
32     }
33     
34 }

第四步:在開發action之前需要先創建一個實體類User.java

 1 package com.bie.type;
 2 
 3 import java.util.Date;
 4 
 5 /** 
 6 * @author BieHongLi 
 7 * @version 創建時間:2017年2月22日 下午4:17:02 
 8 * 
 9 */
10 public class User {
11 
12     private String name;
13     private String password;
14     private int age;
15     private Date birthday;//Date日期類型,導入的utilsl類型的
16     
17     //普通的成員變量,必須給set,get可以不給的。
18     public void setName(String name) {
19         this.name = name;
20     }
21     public void setPassword(String password) {
22         this.password = password;
23     }
24     public void setAge(int age) {
25         this.age = age;
26     }
27     public void setBirthday(Date birthday) {
28         this.birthday = birthday;
29     }
30     public String getName() {
31         return name;
32     }
33     public String getPassword() {
34         return password;
35     }
36     public int getAge() {
37         return age;
38     }
39     public Date getBirthday() {
40         return birthday;
41     }
42     
43 }

第五步:配置struts.xml,和上面的一樣,省去

第六步:注冊頁面index.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>表單提交的頁面</title>
 8 </head>
 9 <body>
10 <form action="${pageContext.request.contextPath}/type_register.action" method="post">
11     賬號:<input type="text" name="user.name"/><br/>
12     密碼:<input type="password" name="user.password"/><br/>
13     年齡:<input type="text" name="user.age"/><br/>
14     出生:<input type="text" name="user.birthday"/><br/>
15     <input type="submit" value="注冊"/>
16 </form>
17 </body>
18 </html>

 第七步:顯示頁面show.jsp,和上面的一樣,省去


 2Struts的數據類型轉換:

  (1):Struts中jsp提交的數據,struts會自動轉換為action中屬性的類型。對於基本數據類型以及日期類型會自動轉換;日期類型只支持yyyy-MM-dd格式,如何是其他格式,需要自定義類型轉換器。

  (2):自定義類型轉換器:

    a:局部類型轉換器;

    b:全局類型轉換器;

  (3):Struts2轉換器API:

    |--TypeConverter                             轉換器接口

      |--DefaultTypeConverter             默認類型轉換器類

        |--StrutsTypeConverter         用戶編寫的轉換器類,繼承此類即可

  (4):局部類型轉換器,轉換器開發步驟:

    《需要注意的是TypeAction和TypeAction-conversion.properties必須在同一目錄下,轉換器類一般在utils包下

    a:寫轉換器類,自定義轉換器繼承StrutsTypeConverter類,重寫convertFromString和converToString方法;

    b:注冊轉換器,配置轉換器類(告訴struts應用自己的轉換器類)

        --》在同包的action目錄下(在action所在包中建立),新建一個properties文件

        --》命名規則:ActionClassName-conversion.properties

           命名舉例:TypeAction-conversion.properties

              《需要注意的是TypeAction必須放在相應的目錄下面。》    

    c:內容,在所建立的ActionClassName-conversion.properties書寫如下內容;

        user.birthday=轉換器全路徑(com.bie.type.MyConverter)

    d:總結:

        轉換器,不能給其他Action使用。以上的轉換器注冊時候是與Action的名字相耦合的,因此只能在自己的Action中內部使用,稱之為局部類型轉換注冊方式;


3:局部類型轉換器,轉換器開發步驟

  (1):寫轉換器類(依舊是上面的開發案例和內容,只是增加了轉換器,數據類型轉換的使用)

package com.bie.type;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

/**
* @author BieHongLi
* @version 創建時間:2017年2月22日 下午5:10:49
* 自定義類型轉換器
*/
public class MyConverter extends StrutsTypeConverter{

    /***
     * 把String轉換為指定的類型【String to Date】
     * @param context 當前上下文環境
     * @param values  jsp表單提交的字符串的值
     * @param toClass 要轉換為目標類型
     */
    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        //判斷 內容不能為空
        if(values==null || values.length==0){
            return null;
        }
        //判斷類型必須為Date
        if(Date.class!=toClass){
            return null;
        }
        try {
            //轉換
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            return sdf.parse(values[0]);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String convertToString(Map arg0, Object arg1) {
        return null;
    }

}

  (2):配置轉換器類(告訴struts應用自己的轉換器類)

  (3):內容文件命名為:TypeAction-conversion.properties

1 user.birthday=com.bie.type.MyConverter

 4:全局類型轉換器,轉換器開發步驟:《需要寫一個轉換器,給所有的action用》

  (1):寫轉換器類  

  (2):配置全局轉換器類(告訴struts應用自己的轉換器類)

     --》在項目src目錄下建立以下固定文件:xwork-conversion.properties  

  (3):內容

     Java.util.Date=轉換器類(com.bie.type.MyConverter)

  (4)全局類型轉換器,轉換器開發步驟

    局部類型轉換器和全局類型轉換器的主要區別就是配置的不一樣;

    文件命名為:xwork-conversion.properties

      要轉換稱的某種類型的全路徑 = 自定義類型轉換器的全路徑;

1 java.util.Date=com.bie.type.MyConverter

     注意:可以使用多種日期格式的進行轉換,主要改變的是類轉換器,這樣yyyy-MM-dd/yyyyMMdd/yyyy年MM月dd日,這三種格式都可以進行輸入了。

 1 package com.bie.type;
 2 
 3 import java.text.DateFormat;
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 import java.util.Map;
 8 
 9 import org.apache.struts2.util.StrutsTypeConverter;
10 
11 /** 
12 * @author BieHongLi 
13 * @version 創建時間:2017年2月22日 下午5:10:49 
14 * 自定義類型轉換器
15 */
16 public class MyConverter extends StrutsTypeConverter{
17 
18     //新需求:要求項目中要支持的格式,如:yyyy-MM-dd/yyyyMMdd/yyyy年MM月dd日
19     //先定義項目中支持的轉換的格式
20     DateFormat[] df={
21         new SimpleDateFormat("yyyy-MM-dd"),
22         new SimpleDateFormat("yyyyMMdd"),
23         new SimpleDateFormat("yyyy年MM月dd日")
24     };
25     
26     /***
27      * 把String轉換為指定的類型【String to Date】
28      * @param context 當前上下文環境
29      * @param values  jsp表單提交的字符串的值
30      * @param toClass 要轉換為目標類型
31      */
32     /*@Override
33     public Object convertFromString(Map context, String[] values, Class toClass) {
34         //判斷 內容不能為空
35         if(values==null || values.length==0){
36             return null;
37         }
38         //判斷類型必須為Date
39         if(Date.class!=toClass){
40             return null;
41         }
42         try {
43             //轉換
44             SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
45             return sdf.parse(values[0]);
46         } catch (ParseException e) {
47             throw new RuntimeException(e);
48         }
49     }*/
50 
51     
52     @Override
53     public Object convertFromString(Map context, String[] values, Class toClass) {
54         //判斷 內容不能為空
55         if(values==null || values.length==0){
56             return null;
57         }
58         //判斷類型必須為Date,注意Date是 java.util.Date;
59         if(Date.class!=toClass){
60             return null;
61         }
62         //迭代,轉換失敗向下一個格式轉換,轉換成功直接返回
63         for(int i=0;i<df.length;i++){
64             try {
65                 //轉換
66                 return df[i].parse(values[0]);
67             } catch (ParseException e) {
68                 continue;
69             }
70         }
71         return null;
72     }
73     @Override
74     public String convertToString(Map arg0, Object arg1) {
75         return null;
76     }
77 
78 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM