1. 程式人生 > >SSH傳送JSON資料到Android端 簡單途徑

SSH傳送JSON資料到Android端 簡單途徑

僅適合小專案,簡單的同時帶來了好多弊端。

loginAction.java 的部分程式碼:

	public String login(){
		StringBuffer sb = null;
		if(userService.isExitUser(username, password)){
			//ActionContext.getContext().getSession().put("user", user);
			//return "success";
			User user = userService.getUser(username, password);
			sb = new StringBuffer();
			sb.append("{\"user\":[");

			sb.append('{')
					.append("\"id\":\"" + user.getId() + "\"")
					.append(",")
					.append("\"userName\":\"" + user.getUserName() + "\"")
					.append(",")
					.append("\"password\":\"" + user.getPassword() + "\"")
					.append(",")
					.append("\"realName\":\"" + user.getRealName() + "\"")
					.append(",")
					.append("\"score\":\"" + user.getScore() + "\"")
					.append(",")
					.append("\"First\":\"" + user.getFirst() + "\"")
					.append(",")
					.append("\"Second\":\"" + user.getSecond() + "\"")
					.append(",")
					.append("\"Third\":\"" + user.getThird() + "\"")
					.append('}');
			sb.append("]}");
		}
		String str = new String(sb);
		ActionContext.getContext().getSession().put("user",str);
		System.out.println("登入");
		return "success";
	}

.xml 的部分程式碼:

		<!--登入-->
		<action name="loginAction" class="loginAction" method="login">
			<result name="success">/resultJSONLogin.jsp</result>
			<!--
			<result name="error">/error.jsp</result>
			<result name="failure">/</result>
			-->
		</action>

resultJSONLogin.jsp 的程式碼:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><%=pageContext.getSession().getAttribute("user")%>

客戶端收到的就是resultJSONLogin.jsp顯示出來的資訊,即JSON