Struts2的型別轉換

2021-09-30 16:06:56 字數 2389 閱讀 8029

一,區域性型別轉換(對某個action中的字段進行型別轉換):

1,寫乙個針對該action的要轉換的字段的轉換器,繼承defaulttypeconverter,重寫convertvalue方法

2,在該action同乙個目錄下(同一包下)    新建乙個***-conversion.properties檔案。***是該action的類名

規則:需要欄位名=該字段的轉換器

如:  point=com.mengya.converter.pointconverter

...(若還有其它的字段需要轉化則繼續寫)

3,這樣寫只能針對該action裡的字段進行轉換,其它的action不行,當然也可以配置其它的action的轉換器

4,對於字串,數字,日期struts2內建的型別轉換。

二,全域性型別轉換

1,在src(即class下面)下面新建乙個xwork-conversion.properties檔案。

規則:需要轉換的類=該類的轉換器

如:com.mengya.util.point=com.mengya.converter.pointconverter

三,轉換器:

1,繼承defaulttypeconverter

如:@override

public object convertvalue(map context, object value, class totype) else if (totype == string.class) {

point point = (point) value;

return "x=" + point.getx() + " y=" + point.gety();

return null;

2,繼承strutstypeconverter

如:// 從string轉換成乙個物件

@override

public object convertfromstring(map context, string value, class totype) {

string paramvalue = value[0];// 取第乙個元數,因為頁面沒有相同的欄位名

string params = paramvalue.split(",");// 將","把使用者所輸入的字串分隔開,即取得x與y的值

int x=integer.parseint(params[0]);

int y=integer.parseint(params[1]);

point p=new point();

p.setx(x);

p.sety(y);

return p;

// 從乙個物件轉換成乙個字串

@override

public string converttostring(map context, object value) {

point p=(point) value;

return "[x="+p.getx()+",y="+p.gety()+"]";

四,集合型別屬性轉換器,如action中有乙個集合型別的屬性也可以進行轉換

public class pointlistconverter extends strutstypeconverter {

// 從string轉換成list

@override

public object convertfromstring(map context, string value, class totype) {

listpointlist = new arraylist();

for (string str : value) {

point p = new point();

string s = str.split(",");

p.setx(integer.parseint(s[0]));

p.sety(integer.parseint(s[1]));

pointlist.add(p);

return pointlist;

// 從list集合轉換成stirng

@override

public string converttostring(map context, object totype) {

listpointlist = (list) totype;

string value = "";

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

value = value + "[x=" + pointlist.get(i).getx() + ",y=" + pointlist.get(i).gety() + "]";

return value;

五,說明:若action有乙個point屬性在jsp頁面可以這樣自己賦值:

Struts2 的型別轉換

1 總體概述 將 string 型別轉化為自定義型別,是瀏覽器傳遞的引數轉換成相應的物件型別,從伺服器跳轉到瀏覽器頁面是自定義型別 物件型別 到 string 型別的轉換。2 流程 當瀏覽器提交到乙個 action 時候,會找到相應的 action 類,當呼叫 action 類裡面set 方法的時候...

struts2的型別轉換

由於使用者在客戶端輸入的資料都為字串型別,當將其儲存到伺服器端時無疑要進行型別轉換,這樣型別轉換自然應運而生了 與型別轉換相關聯的還有輸入校驗,只是輸入校驗習慣性建立在型別轉換基礎之上,輸入校驗將在後面介紹 可以說型別轉換和輸入校驗主要是對使用者輸入的資料進行基本的處理和驗證,以增強系統的安全和穩定...

關於struts2的型別轉換

struts2會不會把form表單自動轉換成pojo的int,date型別呢?我在jsp這樣寫 user最開始我寫了乙個setage int age 的方法,action中的提供乙個private user user new user 執行程式時候一直報找不到方法setage,引數型別是字串陣列!我...