到青軟實習之後,我清楚意識到自己的不足——只會做 Android 是遠遠不夠的。前陣子公司也開始要求我處理伺服器端的工作,於是我重新拾起 Java EE,往後打算走 Java EE + Android 的雙軌路線。
參考黎老師的 WebService 課程後,我覺得那是相當典型的應用(黎老師的教學真的很棒,讓我受益良多),只是他原本用的是 Struts,於是今天中午我把它移植到 Struts2,一方面練手,一方面也順便複習。以下進入正題。
做 Struts2 的第一步是配置專案,這部分比 Android 麻煩不少。首先是 web.xml,基本上就是註冊 Struts2 的核心 Filter:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="https://java.sun.com/xml/ns/javaee"
- xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
- https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
-
- <filter>
- <!-- 定義核心Filter的名稱 -->
- <filter-name>struts2</filter-name>
- <!--定義核心Filter的實現類 -->
- <filter-class>
- org.apache.struts2.dispatcher.FilterDispatcher
- </filter-class>
- </filter>
-
- <filter-mapping>
- <!--核心Filter的名稱 -->
- <filter-name>struts2</filter-name>
- <!--使用該核心Filter來接受所有的Web請求 -->
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
而 struts.xml 的角色就有點像 Android 裡的 AndroidManifest.xml。這裡只設定一個 Action,卻能回傳兩種結果——json 與 xml,畢竟目前 Android 端搭配 JSON 的 WebService 相當流行:
- <?xml version="1.0" encoding="UTF-8" ?>
-
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "https://struts.apache.org/dtds/struts-2.0.dtd">
-
- <struts>
- <package name="struts2" extends="struts-default">
- <action name="List" class="com.su.action.VideoListAction">
- <result name="xml">/videos.jsp</result>
- <result name="json">/jsonvideos.jsp</result>
- </action>
- </package>
- </struts>
接著是回傳結果的頁面。先看 XML 版本,也就是 videos.jsp,這裡用到 Struts 的迭代器,可以把取得的 videos 逐筆處理後輸出:
- <%@ 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"?>
- <videos>
- <s:iterator value="#request.videos" id="video">
- <video id="<s:property value="#video.id"/>">
- <title><s:property value="#video.title"/></title>
- <timelength><s:property value="#video.time"/></timelength>
- </video>
- </s:iterator>
- </videos>
如果要回傳的是 JSON,則改用 jsonvideos.jsp:
- <%@ 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:
- package com.su.action;
-
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.util.List;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.apache.struts2.ServletActionContext;
-
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- import com.su.domain.Video;
- import com.su.service.VideoService;
- import com.su.service.impl.VideoServiceBean;
-
- public class VideoListAction extends ActionSupport {
- private VideoService service = new VideoServiceBean();
- private String format;
- public String getFormat() {
- return format;
- }
- public void setFormat(String format) {
- this.format = format;
- }
-
- @Override
- public String execute() throws Exception {
- List<Video> videos = service.getLastVideos();
- if (format.equals("json")) {
- StringBuilder json = new StringBuilder();
- json.append('[');
- for(Video video : videos){ // {id:76,title:"xxxx",timelength:80}
- json.append('{');
- json.append("id:").append(video.getId()).append(',');
- json.append("title:\"").append(video.getTitle()).append("\",");
- json.append("timelength:").append(video.getTime());
- json.append('}').append(',');
- }
- json.deleteCharAt(json.length()-1);
- json.append(']');
- ServletActionContext.getRequest().setAttribute("videos", json);
- System.out.println("1111111111111111111111111111");
- return "json";
- }
- else {
- ServletActionContext.getRequest().setAttribute("videos", videos);
- return "xml";
- }
-
- }
- }
邏輯其實很單純:JSON 就是把 videos 裡的資料拼接成字串後放進 ServletActionContext;XML 則更省事,直接把 List 丟回去即可。