Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Struts2 打造 WebService:以 XML 與 JSON 回傳資料

到青軟實習之後,我清楚意識到自己的不足——只會做 Android 是遠遠不夠的。前陣子公司也開始要求我處理伺服器端的工作,於是我重新拾起 Java EE,往後打算走 Java EE + Android 的雙軌路線。

參考黎老師的 WebService 課程後,我覺得那是相當典型的應用(黎老師的教學真的很棒,讓我受益良多),只是他原本用的是 Struts,於是今天中午我把它移植到 Struts2,一方面練手,一方面也順便複習。以下進入正題。

做 Struts2 的第一步是配置專案,這部分比 Android 麻煩不少。首先是 web.xml,基本上就是註冊 Struts2 的核心 Filter:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="https://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="https://java.sun.com/xml/ns/javaee   
  6.     https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <display-name></display-name>   
  8.   <welcome-file-list>  
  9.     <welcome-file>index.jsp</welcome-file>  
  10.   </welcome-file-list>  
  11.     
  12.   <filter>  
  13.     <!-- 定義核心Filter的名稱 -->  
  14.     <filter-name>struts2</filter-name>  
  15.     <!--定義核心Filter的實現類 -->  
  16.     <filter-class>  
  17.         org.apache.struts2.dispatcher.FilterDispatcher  
  18.     </filter-class>  
  19. </filter>  
  20.   
  21. <filter-mapping>  
  22.     <!--核心Filter的名稱 -->  
  23.     <filter-name>struts2</filter-name>  
  24.     <!--使用該核心Filter來接受所有的Web請求 -->  
  25.     <url-pattern>/*</url-pattern>  
  26. </filter-mapping>  
  27. </web-app>  

而 struts.xml 的角色就有點像 Android 裡的 AndroidManifest.xml。這裡只設定一個 Action,卻能回傳兩種結果——json 與 xml,畢竟目前 Android 端搭配 JSON 的 WebService 相當流行:

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE struts PUBLIC  
  4.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  5.     "https://struts.apache.org/dtds/struts-2.0.dtd">  
  6.   
  7. <struts>  
  8.     <package name="struts2" extends="struts-default">  
  9.         <action name="List" class="com.su.action.VideoListAction">  
  10.             <result name="xml">/videos.jsp</result>  
  11.             <result name="json">/jsonvideos.jsp</result>  
  12.         </action>  
  13.     </package>  
  14. </struts>  

接著是回傳結果的頁面。先看 XML 版本,也就是 videos.jsp,這裡用到 Struts 的迭代器,可以把取得的 videos 逐筆處理後輸出:

  1. <%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><?xml version="1.0" encoding="UTF-8"?>  
  2. <videos>   
  3. <s:iterator value="#request.videos" id="video">  
  4.     <video id="<s:property value="#video.id"/>">  
  5.     <title><s:property value="#video.title"/></title>  
  6.     <timelength><s:property value="#video.time"/></timelength>  
  7.     </video>  
  8.     </s:iterator>   
  9. </videos>  

如果要回傳的是 JSON,則改用 jsonvideos.jsp:

  1. <%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${videos}  

這裡要特別注意!在 XML 檔案中:

<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><?xml version="1.0" encoding="UTF-8"?>

這些尖括號之間千萬不要留空格,否則在 Chrome 裡會無法被辨識為 XML 檔,解析時就會報錯(例如找不到文件頭之類的訊息)。

最後是 Java 程式碼部分。首先是 VideoListAction.java,也就是主要的 Action,功能上相當於 Android 的 Activity:

  1. package com.su.action;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.apache.struts2.ServletActionContext;  
  11.   
  12. import com.opensymphony.xwork2.ActionContext;  
  13. import com.opensymphony.xwork2.ActionSupport;  
  14. import com.su.domain.Video;  
  15. import com.su.service.VideoService;  
  16. import com.su.service.impl.VideoServiceBean;  
  17.   
  18. public class VideoListAction extends ActionSupport {  
  19.     private VideoService service = new VideoServiceBean();  
  20.     private String format;  
  21.     public String getFormat() {  
  22.         return format;  
  23.     }  
  24.     public void setFormat(String format) {  
  25.         this.format = format;  
  26.     }  
  27.       
  28.     @Override  
  29.     public String execute() throws Exception {  
  30.         List<Video> videos = service.getLastVideos();  
  31.         if (format.equals("json")) {  
  32.             StringBuilder json = new StringBuilder();  
  33.             json.append('[');  
  34.             for(Video video : videos){ // {id:76,title:"xxxx",timelength:80}   
  35.                 json.append('{');  
  36.                 json.append("id:").append(video.getId()).append(',');  
  37.                 json.append("title:\"").append(video.getTitle()).append("\",");  
  38.                 json.append("timelength:").append(video.getTime());  
  39.                 json.append('}').append(',');  
  40.             }  
  41.             json.deleteCharAt(json.length()-1);  
  42.             json.append(']');  
  43.             ServletActionContext.getRequest().setAttribute("videos", json);  
  44.             System.out.println("1111111111111111111111111111");  
  45.             return "json";  
  46.         }  
  47.        else {  
  48.         ServletActionContext.getRequest().setAttribute("videos", videos);  
  49.         return "xml";  
  50.        }  
  51.         
  52.     }  
  53. }  

邏輯其實很單純:JSON 就是把 videos 裡的資料拼接成字串後放進 ServletActionContext;XML 則更省事,直接把 List 丟回去即可。

Copyright © Linux教程網 All Rights Reserved