struts2的類型轉換執行個體

來源:互聯網
上載者:User

首先jsp頁面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'input.jsp' starting page</title>

  </head>
  
  <body>
   
   <h3><font color="red">使用逗號將點的兩個座標分割開</font></h3>
   
   <s:form action="pointConverter">
   
   <s:textfield name="point" label="point"></s:textfield>
   <s:textfield name="age" label="age"></s:textfield>
   <s:textfield name="username" label="username"></s:textfield>
   <s:textfield name="date" label="birthday"></s:textfield>
   
   <s:submit label="submit"></s:submit>
   
   </s:form>
   
  </body>

</html>

然後是bean層

然後**Action,且對應Action目錄下有屬性檔案告訴Action裡的屬性值需要用自己寫的哪個類型轉換檔轉換

package com.test.converter;

import java.util.Map;

import ognl.DefaultTypeConverter;

import com.test.bean.Point;

public class PointConverter extends DefaultTypeConverter
{

@Override
public Object convertValue(Map context, Object value, Class toType)
{
if(Point.class == toType)                                             //先是由PointAction-conversion.properties設定檔

{
Point point = new Point();

String[] str = (String[])value;

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

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

point.setX(x);
point.setY(y);

return point;
}
if(String.class == toType)                                           //在頁面上需要顯示時候才調用,然後再返回string類型
{
Point point = (Point)value;

int x = point.getX();
int y = point.getY();

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

return result;
}

return null;
}

}

還有全域類型轉換設定檔xwork-conversion.properties

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.