Amazon Ads

顯示具有 Struts2 標籤的文章。 顯示所有文章
顯示具有 Struts2 標籤的文章。 顯示所有文章

2014年3月28日 星期五

【J筆記】使用Struts2回傳JSON字串

在很多時候,動態網頁需要回應JSON字串給客戶端程式如JavaScript來做後續的處理的。我這裡做一個以Struts2回應的範例,以供日後回顧參考。

這裡的範例是以「2.3.16.1」為主。

需要的jar檔如下:


先簡單看一下web.xml的配置:

 mystruts

 
  struts2
  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
 

 
  struts2
  /*
 

主要意思是,將所有的回應,轉給Struts來做處理。

再來看struts.xml的配置:
 

 
    
 
    
     
      
     
   
            /index.jsp
        
 
   
    /pages/HelloWorld.jsp
   
   
    
     jsonString
    
   
    
 

需要注意的是第9至11行這邊,需要替我要回傳的JSON格式定義一個result-type,在這裡就是json。

這裡使用Struts2定義的org.apache.struts2.json.JSONResult類別。

再來我只要再定義一個Action,它在execute方法處理好要轉成JSON字串的物件,並返回json_ok的結果就好,如上的第16至20行。

JsonAction.java的程式如下:
package org.apache.struts.helloworld.action;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts.helloworld.model.JsonString;

import com.opensymphony.xwork2.ActionSupport;

public class JsonAction extends ActionSupport
{
 /**
  * 
  */
 private static final long serialVersionUID = 1645961153075600530L;

 private JsonString jsonString;
 
    public String execute() throws Exception {
         
        Map map = new HashMap();
        map.put("abc", "123");
        map.put("def", "456");
       
        this.getJsonString().setRes(map);
        return "json_ok";
    }

 public JsonString getJsonString()
 {
  if(jsonString == null)
  {
   this.jsonString = new JsonString();
  }
  return jsonString;
 }

 public void setJsonString(JsonString jsonString)
 {
  this.jsonString = jsonString;
 }
}

啟動伺服器後,送出要求後,就會得到下列的結果:


上列程式碼,可至這裡下載。

2013年12月12日 星期四

【分享】Spring與Struts2的Web應用程式

拜歐日前在複習Spring加上Struts2的Web應用程式時,有鑑於每次都要拉一堆jar檔,然後再一個個試,才讓程式可以執行過的過程非常繁雜,於是整理了一包可以跑的Web應用程式,可以在這裡下載。

下載完成後,只要解壓縮,再用Eclipse匯入後,就可以執行。

要匯入的jar檔如下,當初是先放一些基本的jar檔,然後啟動,若有報錯,再依報錯的訊息去找出缺的jar檔。


從上圖可以看出,使用的Spring版本為3.0.5,而Struts2版本為2.3.4.1,因為Struts2前陣子陸續有些安全性議題產生,建議自行再拉最新的jar回來替換。

2012年3月20日 星期二

Struts2的s:if tag

import com.opensymphony.xwork2.ActionSupport;

public class DemoAction extends ActionSupport {

    /**
     *
     */
    private static final long serialVersionUID = 3847991430058456326L;

    private String demoString;

    ...
   
    public String getDemoString() {
       return demoString;
    }

    public void setDemoString(String demoString) {
       this.demoString = demoString;
    }
}
若要在JSP中使用來判斷demoString的值是否為「0」的話,則是利用Struts2的tag,用法如下:&s:if <s:if test="%{demoString eq 0}">
…
</s:if>
<s:elseif test="%{demoString eq 2}">
    <%-- other condition --%>
</s:elseif>
<s:else>
<%-- else --%>
</s:else>


注意:上列中test=""中是%{...}