手機端要和使用中的 Web 服務對話,最省事的方式就是 JSON。本文示範在 SSH 框架下先只掛上 Struts2,把登入表單的資料接收、封裝成 JSON 再吐回前端,作為後續串接 Android 的基礎。
<?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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
這裡的 package 繼承 json-default,才能使用 json 型別的 result:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"https://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="as" extends="json-default">
<action name="login" class="as.action.LoginAction" method="login">
<result type="json"></result>
</action>
</package>
</struts>
這個 Action 同時實作 ModelDriven<User> 做參數接收,以及 ServletRequestAware、ServletResponseAware 拿到容器物件,最後用 JSONObject 組出回應:
package as.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import net.sf.json.JSONObject;
import as.model.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class LoginAction extends ActionSupport
implements ServletResponseAware, ServletRequestAware, ModelDriven<User>{
private User user;
private HttpServletResponse response;
private HttpServletRequest request;
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public void setServletResponse(HttpServletResponse arg0) { this.response = arg0; }
public void setServletRequest(HttpServletRequest arg0) { this.request = arg0; }
public void login() {
try {
this.response.setContentType("text/html;charset=utf-8");
this.response.setCharacterEncoding("UTF-8");
JSONObject json = new JSONObject();
Map map = new HashMap<Object, String>();
map.put("name", user.getName());
map.put("pwd", user.getPwd());
json.put("LoginInfo", map);
response.getWriter().write(json.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public User getModel() {
if (user == null) {
return user = new User();
}
return user;
}
}
寫法上有一點可以更好:既然已經繼承 json-default,其實可以直接回傳物件讓框架序列化,不必自己動手寫 JSONObject。但手寫的好處是回應結構完全可控,跨端協作時反而更明確。另外 setCharacterEncoding("UTF-8") 這行別省,中文亂碼多半出在這裡。
package as.model;
public class User {
private String name;
private String pwd;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPwd() { return pwd; }
public void setPwd(String pwd) { this.pwd = pwd; }
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>登入測試頁</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<center>
<form action="login" method="post">
用戶名: <input type="text" name="name"><br>
密 碼: <input type="password" name="pwd"><br>
<input type="submit" value="登陸" name="submit">
<input type="reset" value="取消" name="reset">
</form>
</center>
</body>
</html>
測試帳號可用 2222 / 1111。表單提交後,頁面會收到一段形如 {"LoginInfo":{"name":"2222","pwd":"1111"}} 的 JSON。接下來在 Android 端建立專案,用 HttpClient 或 HttpURLConnection 打這個位址,解析 LoginInfo 節點即可完成登入驗證。