首先,服务器端已经存在一个项目,该项目基于SSH,已经部署在tomcat上并且正在运行了.我在这个项目的action层新建了一个包,该包主要是Struts2的一些action,只是这些action不是返回某些view,而是返回json,定义这些action的XML配置如下:
<package name="mobie" namespace="/mobie" extends="json-default">
<action name="login" class="loginAction" method="login">
<!-- 设置返回类型为json -->
<result name="success" type="json">
<!-- 将对象放进一个map里面,这个map作为该action的一个field,必须具有setter个getter方法
这样就可以向客户端返回整个实体的json对象,这个在需要返回复杂的组和对象是比较实用 -->
<param name="root">dataMap</param>
</result>
</action>
</package>
action类:
import java.util.HashMap;
import java.util.Map;
import com.jeanselam.intf.UserService;
import com.jeanselam.pojo.User;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String email;
private String password;
private User user;
private Map<String, Object> dataMap = new HashMap<String, Object>();
private UserService userService;//业务接口,不写出来,省略
public Map<String, Object> getDataMap() {
return dataMap;
}
public void setDataMap(Map<String, Object> dataMap) {
this.dataMap = dataMap;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String login() throws Exception
{
//System.out.println("---------------------------移动端登陆");
System.out.println("---------------------------移动端登陆"+email+"\t"+password);
user = userService.login(email, password);
dataMap.put("user", user);
if(user != null)
{
return SUCCESS;
}
return ERROR;
}
}
然后,在服务器端和android端都应该有相同的一个实体类,并且解析的json的字段名必须和该类的field名一致:
import java.util.Set;
/**
* Created by lin on 15-11-8.
*
*/
public class User{
private Integer id;
private String email;
private String password;
private Integer gender;
private String tel;
private String nickname;
private Integer isActive;//是否处于激活状态:1 是 0 否
private Address address;
private Set<Order> orders;//一对多
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Integer getIsActive() {
return isActive;
}
public void setIsActive(Integer isActive) {
this.isActive = isActive;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email + '\'' +
", password='" + password + '\'' +
", gender=" + gender +
", tel='" + tel + '\'' +
", nickname='" + nickname + '\'' +
", isActive=" + isActive +
", address=" + address +
", orders=" + orders +
'}';
}
}
然后主要开发android端,在android端我的思路大概是这样的:通过http协议访问服务器端的action,服务器返回json,然后android接受json后,通过解析json构造出实例,然后显示在activity上反馈给用户.于是,在android端的主要工作就是解析json和显示数据的问题了,而解析json的工作可以通过某些包来做比较方便.
新建android项目:导入一下jar包:
界面文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.ddd3.ddd3.MainActivity"
android:orientation="vertical"
android:background="@color/colorBackground">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="JeanseLam™"
android:textSize="35dp"
android:textColor="@color/colorText"/>
<View
android:layout_width="match_parent"
android:layout_height="1dip"
android:background="#696969"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/mainUrl"
android:textSize="20dp"
android:textColor="@color/colorText"/>
<View
android:layout_width="fill_parent"
android:layout_height="40dp"></View>
<TextView
android:id="@+id/loginInfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textColor="@color/colorError"/>
<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:hint="Type your Email"/>
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:password="true"
android:hint="Enter password"/>
<Button
android:id="@+id/btn_login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/button_selector"
android:text="登录"
android:textColor="@color/colorBtnText"
android:layout_marginBottom="10dp"/>
<Button
android:id="@+id/btn_exit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="退出"
android:background="@drawable/button_selector"
android:textColor="@color/colorBtnText"
android:layout_marginBottom="10dp"/>
<TextView
android:id="@+id/btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新用户?"
android:textColor="@color/colorText"
android:autoLink="all"/>
</LinearLayout>
activity:
package com.ddd3.ddd3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.ddd3.entity.User;
import com.ddd3.service.JSONService;
public class MainActivity extends AppCompatActivity {
private EditText emailText;
private EditText passwordText;
private Button btn_login;
private Button btn_exit;
private TextView info;
private RequestQueue requestQueue;//用于网络网络请求,每一个activity只需要一个requestQueue
//private UserService userService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
emailText = (EditText)findViewById(R.id.email);
passwordText = (EditText)findViewById(R.id.password);
btn_login = (Button)findViewById(R.id.btn_login);
btn_exit = (Button)findViewById(R.id.btn_exit);
info = (TextView)findViewById(R.id.loginInfo);
btn_login.setOnClickListener(new ButtonListener());
btn_exit.setOnClickListener(new ButtonListener());
requestQueue = Volley.newRequestQueue(this);//实例化请求队列
}
class ButtonListener implements View.OnClickListener{
@Override
public void onClick(View v) {
if(v.getId() == btn_login.getId()){
String email = emailText.getText().toString();
String password = passwordText.getText().toString();
if(email.equals("") || password.equals("")){
info.setText("请输入您的Email和密码");
}
else{
//服务端url
String url = "http://192.168.56.1:8080/JeanseLam/mobie/login?email="+email+"&password="+password;
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<org.json.JSONObject>() {
@Override
public void onResponse(org.json.JSONObject jsonObject) {
//System.out.println("----------------"+jsonObject.toString());
String jsonStr = jsonObject.toString();
//由于服务器端传过来的date格式gson默认是无法解析的,所以在创建gson的时候就要对date的格式进行设置
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
//在服务器端传过来的json是包含类名的,应该做些字符串的处理,把类名去掉才可解析成实体类,否则解析的类的所有属性值均为null,我实验过了
User user = gson.fromJson(jsonStr.substring(jsonStr.indexOf(":")+1,jsonStr.length()-1), new TypeToken<User>() {
}.getType());//构造实例
//System.out.println("-------------------"+user.toString());
application.getSession().put("user", user);//用户登陆信息作为全局变量
Intent intent = new Intent(MainActivity.this,IndexActivity.class);//转到主页
startActivity(intent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("-------------------"+error.getMessage());
}
});
jr.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
requestQueue.add(jr);
}
}
else if(v.getId() == btn_exit.getId()){
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
}
需要注意的是:由于访问本地项目,url的地址为:192.168.56.1:8080而不是localhost或其他