您的位置:首页 > 编程语言 > Java开发

android与服务器之间数据通信(struts2+JSON+android)

2015-08-22 22:27 609 查看
本文主要解决android与服务器之间的数据传递问题

服务器端使用hibernate+struts2架构进行开发

以用户登陆为例:

1.服务器端的配置:

在服务器端部分,主要与android客户端交互的部分就是struts2的action,该action继承ActionSupport类,实现ServletRequestAware,和ServletResponseAware接口。

/**
* LoginAction.java [V 1.0.0]
*classes:org.action.LoginAction
*Create at: 2015年8月19日下午6:45:38
*/
package org.action.reglog;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.model.Users;
import org.service.imp.LogRegService;

import com.opensymphony.xwork2.ActionSupport;

/**
* org.action.LoginAction
*
* @author xiangdong she Create at:2015年8月19日.下午6:45:38
*/
public class LoginAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
private final Logger log = Logger.getLogger(LoginAction.class);
/**
*
*/
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;

/*
* (non-Javadoc)
*
* @see
* org.apache.struts2.interceptor.ServletResponseAware#setServletResponse
* (javax.servlet.http.HttpServletResponse)
*/
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}

/*
* (non-Javadoc)
*
* @see
* org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(
* javax.servlet.http.HttpServletRequest)
*/
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}

public void login() throws IOException {
this.response.setContentType("text/html;charset=utf-8");
// 解决post乱码
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
log.error("encoding error!!!");
e1.printStackTrace();
}
String username=request.getParameter("username");
String password=request.getParameter("password");
// 解决get乱码

//		String username = new String(request.getParameter("username").getBytes(
//				"ISO-8859-1"), "UTF-8");
//		String password = new String(request.getParameter("password").getBytes(
//				"ISO-8859-1"), "UTF-8");

JSONObject jsonObject = new JSONObject();
Users user=null;
LogRegService lgService = new LogRegService();
try {
user=lgService.getUser(username);
if (lgService.login(username, password)) {
if (lgService.isActivated(username)) {
if (lgService.isBind(username)) {

request.getSession().setAttribute("username", username);
user.setLoginNum(user.getLoginNum()+1);
lgService.updateUser(user);
jsonObject.put("logmess", "success");
<span style="white-space:pre">						</span>//利用JSONobject类进行封装数据,并且传递数据(可以封装类,可以将该action在浏览器中实现,自己查看json//分装类和单独数据的格式)
//例如:<span style="font-family: 'Times New Roman';font-size:14px;">{"username":"username","logmess":"success","user":{"passwd":"passwd","username":"username","loginNum":15,"validateCode":"activated","email":"administorEmail@qq.com","userId":7,"tel":"11110000","answer":"answer","gender":true,"realName":"realname</span>
//其中:user就是一个类,而username和logmess是单数的数据
jsonObject.put("username", username);
jsonObject.put("user", user);//此处需要注意,自己可以实现定义一个用户类

} else {
jsonObject.put("logmess", "not bind");
}
} else {
jsonObject.put("logmess", "Inactive");
}
} else {
if (lgService.checkUid(username)) {
jsonObject.put("logmess", "password error");
} else {
jsonObject.put("logmess", "user not existed");
}
}
response.getWriter().write(jsonObject.toString());
log.info("execute success");
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("inner error!");
e.printStackTrace();
}
}
}
以上部分就是登录的action类,由于项目业务的需要,所以会做很多逻辑判断,如果自己测试,则可以精简,吧一些if{}else{}语句去掉,写好该类之后,需要在struts.xml文件中说明:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "struts-2.1.dtd" >
<struts>
<!-- setting encoding,DynamicMethod,language <constant name="struts.custom.i18n.resources"
value="messageResource"></constant> -->
<!-- <constant name="struts.i18n.encoding" value="UTF-8"></constant> -->
<!-- <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant> -->
<package name="RegLog" <span style="background-color: rgb(255, 0, 0);">extends="json-default"</span> <span style="background-color: rgb(0, 0, 153);">namespace="/reglog"</span>>
<action name="loginx" class="org.action.reglog.LoginAction"
method="login">
<span style="color:#ff0000;background-color: rgb(255, 255, 0);"><result type="json" /></span>
</action>
<!--<action name="register" class="org.action.reglog.RegistAction"
method="register">
<result type="json" />
</action>-->
</package>
</struts>
注:请注意标红的地方,这是使用json封装数据所必要的。也请注意标蓝的地方,包的命名空间在struts2.n之后也是必要的(我忘了是2.几了...).还有标黄的地方,这是返回类型,必须的要。

2.android客户端的配置

private String loginPro() {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
JSONObject jsonObject;
String result = "failed";
Users user=new Users();
JSONObject js;
try {
jsonObject = query(username, password);
result = jsonObject.getString("logmess");
<span style="background-color: rgb(51, 255, 51);">js=jsonObject.getJSONObject("user");</span>
user.setUsername(js.getString("username"));
user.setPasswd(js.getString("passwd"));
user.setLoginNum(js.getInt("loginNum"));
user.setValidateCode(js.getString("validateCode"));
user.setEmail(js.getString("email"));
user.setUserId(js.getInt("userId"));
user.setTel(js.getString("tel"));
<span style="background-color: rgb(51, 51, 255);">System.out.println(user.getEmail());
</span><span style="background-color: rgb(255, 255, 204);">			</span><span style="background-color: rgb(51, 51, 255);">System.out.println(user.getUsername());
</span><span style="background-color: rgb(255, 255, 255);">			</span><span style="background-color: rgb(51, 51, 255);">System.out.println(user.getLoginNum());
</span><span style="background-color: rgb(255, 255, 255);">			</span><span style="background-color: rgb(51, 51, 255);">System.out.println(user.getTel());
</span><span style="background-color: rgb(255, 255, 255);">			</span><span style="background-color: rgb(51, 51, 255);">System.out.println(result);
</span><span style="background-color: rgb(255, 255, 255);">			</span><span style="background-color: rgb(51, 51, 255);">System.out.println(jsonObject);</span>
} catch (Exception e) {
DialogUtil.showDialog(Login.this, "服务器响应错误,稍后再试。。", false);
}
return result;
}

private JSONObject query(String username, String password) throws Exception {
<span style="color:#ff0000;">Map<String, String> map = new HashMap<String, String>();
map.put("username", username);
map.put("password", password);</span>
String url = HttpUtil.BASE_URL + "reglog/loginx.action";
String result = HttpUtil.postRequest(url, map);

JSONObject jsonObject = new JSONObject(result);
Log.d("json中的值", jsonObject.toString());
return jsonObject;
}

private boolean validate() {
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (username.equals("")) {
DialogUtil.showDialog(this, "用户名是必填项", false);
return false;
}
if (password.equals("")) {
DialogUtil.showDialog(this, "密码必填", false);
}
return true;
}

}


注:绿色部分是使用JSONobject类接受user类,之后对user的属性进行注入。蓝色部分是对接受到的数据的输出检验。红色部分就是在传输之前,将数据以map的方式进行封装,以便于调用以下类的post方法,进行诗句发送。

要用到的数据发送的基本方法:分别使用get和post方法发送数据
package com.client.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpUtil {
public static HttpClient httpClient = new DefaultHttpClient();
public static final String BASE_URL = "http://113.251.216.196:8080/JavaWebStruct/";

public static String getRequest(final String url) throws Exception {
Log.d("执行getRequest方法", "开始执行");
FutureTask<String> task = new FutureTask<String>(new Callable<String>() {

@Override
public String call() throws Exception {
HttpGet get = new HttpGet(url);
HttpResponse response = httpClient.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
return null;
}
});
new Thread(task).start();
return task.get();
}

public static String postRequest(final String url,final Map<String, String> rawParams) throws Exception{
Log.d("执行postRequest方法", "开始执行");

FutureTask<String> task=new FutureTask<String>(new Callable<String>() {

@Override
public String call() throws Exception {
HttpPost post=new HttpPost(url);
List<NameValuePair> params=new ArrayList<NameValuePair>();
for (String key : rawParams.keySet()) {
params.add(new BasicNameValuePair(key, rawParams.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
Log.d("执行postRequest方法", "执行到中间");
HttpResponse response=httpClient.execute(post);

if (response.getStatusLine().getStatusCode()==200) {
String result=EntityUtils.toString(response.getEntity());
Log.d("entityUtils返回值", result);
return result;
}
return null;
}
});
new Thread(task).start();
Log.d("执行postRequest方法", "执行结束");
return task.get();

}

}


其中用到的一个显示控件的通用方法:

package com.client.util;

import com.example.androidtest.Success;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.content.DialogInterface.OnClickListener;

public class DialogUtil {
public static void showDialog(final Context ctx, String msg, boolean goHome) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx).setMessage(msg).setCancelable(false);
if (goHome) {
builder.setPositiveButton("确定", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ctx, Success.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
});
} else {
builder.setPositiveButton("确定", null);
}
builder.create().show();
}

public static void showDialog(Context ctx, View view) {
new AlertDialog.Builder(ctx).setView(view).setCancelable(false).setPositiveButton("确定", null).create().show();
}
}
编码不是问题,问题也不是问题,主要问题是思路要清晰。。。。。。

若本文中出现某些问题或其他问题,请私聊



或留言
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: