android 与struts2的通信并返回json式

一 、服务器端
1所需要用到的jar包,

其中注意,要用xwork-2.1.2.jar我尝试了高版本的总是出错,纠结了蛮久的

android 与struts2的通信并返回json式_第1张图片


2.struts.xml








   

   responseJson









其中这里注意要extends="json-default",这样才能够返回json式而不是界面。


3.Login.action

package org.lei.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lei.model.User;
import org.lei.srvice.UserManager;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;


import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.bcel.internal.generic.NEW;

@Component("loginAction")
@Scope("prototype")
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport{
	private String userName;
	private String userPassword;
	private MapresponseJson;

	public String getUserName() {
		return userName;
	}
	public Map getResponseJson() {
		return responseJson;
	}
	public void setResponseJson(Map responseJson) {
		this.responseJson = responseJson;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	private UserManager userManager;
	public UserManager getUserManager() {
		return userManager;
	}
	/*将userManager进行注入,这里是由Struts-Spring-plugin的插件注入的,不加@resource也可以
	 * 加了貌似没有起作用,默认去找一个userManager
	 * */
	@Resource
	public void setUserManage(UserManager userManager) {
		this.userManager = userManager;
	}
	@Override
	public String execute() throws Exception {
		System.out.println("执行execute***************");
		User user  = new User(1,"renlei","123456");
		responseJson = new HashMap();
		if(userName.equals("renlei")&&userPassword.equals("123456")){
			/*Map map = new HashMap<>();
			map.put("userName", user.getUserName());
			this.setResponseJson(map);*/
			responseJson.put("User", new Gson().toJson(user, User.class));
		}
		System.out.println(responseJson.toString());
		return SUCCESS;
	}
	
}
这里我使用的是ssh的框架,所以大家只用看execute函数里面的东西即可以,其他一些都是基本的Struts2的配置,例如web.xml等,这里就不详细给出。

二 客户端

package org.lei.activity;


import java.util.ArrayList;
import java.util.List;


import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.lei.model.User;
import org.lei.net.Connect;


import com.google.gson.Gson;
import com.lei.chatroomhttp.R;
import com.lei.chatroomhttp.R.layout;
import com.lei.chatroomhttp.R.menu;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface.OnCancelListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;




public class LoginActivity extends Activity implements OnClickListener{
private EditText userNameEditText;
private EditText userPasswordEditText;
private ImageButton loginImageButton;
private ImageButton registerImageButton;
private CheckBox rem_userNameCheckBox;
private CheckBox rem_userPasswrodCheckBox;
private Handler mHandler;
private Handler childHandler;
//private ProgressDialog dialog = new ProgressDialog(this);
LoginThread loginThread = new LoginThread();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
mHandler = new Handler(){

public void handleMessage(Message msg){
String result = (String) msg.obj;
System.out.println("mhandler"+result+"******");
if(result.equals("fail")){

Toast toast = Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG);
toast.show();
}
else{
try {
JSONObject jsonObject = new JSONObject(result);
Gson gson  = new Gson();
User user = gson.fromJson(jsonObject.getString("User"), User.class);
Toast toast = Toast.makeText(getApplicationContext(),user.getUserName()+user.getUserPassword() , Toast.LENGTH_LONG);
toast.show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
//dialog.dismiss();
}
};
loginThread.setDaemon(true);
loginThread.start();


}

private void init (){
userNameEditText = (EditText)findViewById(R.id.username);
userPasswordEditText =(EditText)findViewById(R.id.userpassword);
loginImageButton = (ImageButton)findViewById(R.id.loginimgbtn);
registerImageButton = (ImageButton)findViewById(R.id.login_ibtn_Register);
rem_userNameCheckBox=(CheckBox)findViewById(R.id.chk_rem_username);
rem_userPasswrodCheckBox=(CheckBox)findViewById(R.id.chk_rem_userpassword);
loginImageButton.setImageResource(R.drawable.loginbtn);
loginImageButton.setOnClickListener(this);
}


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击登录1");
switch (v.getId()) {
case R.id.loginimgbtn:
System.out.println("点击登录");
Message msg = childHandler.obtainMessage();
msg.sendToTarget();
//dialog = ProgressDialog.show(this,  "","与服务器通信中,请稍后……");
//dialog.setCancelable(true);

break;


default:
break;
}
}
class LoginThread extends Thread{

public void run(){
setName("childThread");
Looper.prepare();
childHandler  = new Handler(){
public void handleMessage(Message msg){
Listparams = new ArrayList();
params.add(new BasicNameValuePair("userName",userNameEditText.getText().toString()));
params.add(new BasicNameValuePair("userPassword",userPasswordEditText.getText().toString()));
Object result = null;
try {
result = Connect.getInstance().getResult("login", params);
if(result!=null){
sendMsg(result.toString());

}
else{
sendMsg("fail");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

};
Looper.loop();
}
/*
* 根据返回值给mainHandle发送不同消息
*/
private void sendMsg(String info ){
Message msg  =  mHandler.obtainMessage();
msg.obj = info;
mHandler.sendMessage(msg);
}
}

}



2我将通信的部分自己封装成了一个类,方便调用

package org.lei.net;


import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


/**
 * @author renlei
 *
 */
public class Connect {
//public  static Connect httpConnect = new Connect();

private static Connect httpConnect;
private Connect(){}
public static Connect getInstance(){
if(httpConnect == null){
synchronized (Connect.class) {
if(httpConnect == null){
httpConnect = new Connect();
}
}
}
return httpConnect;
}
public Object getResult(String actionName,Listparams)throws Exception{
//创建客户端连接对象
HttpClient httpClient = new DefaultHttpClient();

HttpPost request = new HttpPost("http://192.168.2.144:8080/MySSH/"+actionName+".action");
//设置上传的数据,上传的数据封装到list集合中,并转换为UTF-8字符集
System.out.println(request.toString());
System.out.println(actionName+params.toString());
request.addHeader("Accept","text/json");
request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//执行请求,并返回响应对象
System.out.println("发送请求1");
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (Exception e) {
System.out.println(e.getMessage()+"yichang********");
e.printStackTrace();
// TODO: handle exception
}
//判断服务器响应状态
System.out.println("发送请求2");
System.out.println(response.getStatusLine().getStatusCode() );
if(response.getStatusLine().getStatusCode() == 200){
//获取服务器返回信息
System.out.println("**************result");
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity,"UTF-8");
return json;
}
return null;

}
}



原工程下载地址

http://download.csdn.net/detail/renlei0109/7129495

你可能感兴趣的:(服务器客户端通信)