[置顶] Android+struts2+json方式模拟手机登录功能

涉及到的知识点: 

1.Struts2框架的搭建(包括Struts2的jSON插件)

  2.Android前台访问Web采用HttpClient方式。

  3.Android采用JSON的解析。

服务端主要包含一个Action,通过struts的web配置配置struts.xml驱动业务逻辑的执行,然后对于符合条件的登录,返回给客户端通过jsonobject包装的数据。

服务端代码:

  1. package com.easyway.json.android;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import org.apache.struts2.interceptor.ServletRequestAware;  
  10. import org.apache.struts2.interceptor.ServletResponseAware;  
  11.   
  12. import com.opensymphony.xwork2.ActionSupport;  
  13.   
  14. /**   * 模拟登录,并返回json数据 @author xiangzhihong
  15.  */  
  16. public class LoginAction extends ActionSupport implements ServletRequestAware,  
  17.         ServletResponseAware {  
  18.     /** * */  
  19.     private static final long serialVersionUID = 1L;  
  20.   
  21.     HttpServletRequest request;  
  22.   
  23.     HttpServletResponse response;  
  24.       
  25.     private String userName;  
  26.     private String password;  
  27.       
  28.   
  29.     public String getPassword() {  
  30.         return password;  
  31.     }  
  32.   
  33.     public void setPassword(String password) {  
  34.         this.password = password;  
  35.     }  
  36.   
  37.     public String getUserName() {  
  38.         return userName;  
  39.     }  
  40.   
  41.     public void setUserName(String userName) {  
  42.         this.userName = userName;  
  43.     }  
  44.   
  45.     public void setServletRequest(HttpServletRequest request) {  
  46.         this.request = request;  
  47.     }  
  48.   
  49.     public void setServletResponse(HttpServletResponse response) {  
  50.         this.response = response;  
  51.     }  
  52.       
  53.     /** 
  54.      * 模拟用户登录的业务 
  55.      */  
  56.     public void login() {  
  57.         try {         

  1.                this.response.setContentType("text/json;charset=utf-8");  
  2.                this.response.setCharacterEncoding("UTF-8");  
  3.                //JSONObject json=new JSONObject();   
  4.                 Map<String,String> <span style="color: #ff0000;">json</span>=new HashMap<String,String>();  
  5.                 if ("admin".equals(userName)&&"123456".equals(password)) {  
  6.                      json.put("message""欢迎管理员登陆");  
  7.                 } else if ((!"admin".equals(userName))&&"123456".equals(password)) {  
  8.                     json.put("message""欢迎"+userName+"登陆!");  
  9.                 } else {  
  10.                     json.put("message""非法登陆信息!");  
  11.                 }  
  12.               byte[] jsonBytes = json.toString().getBytes("utf-8");  
  13.               response.setContentLength(jsonBytes.length);  
  14.               response.getOutputStream().write(jsonBytes);  
  15.               response.getOutputStream().flush();  
  16.               response.getOutputStream().close();  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21. }  

   接下来是客户端代码,用AsyncHttpClient进行网络的请求,如果包含我返回的json字符串的标志,我认为访问成功
 客户端代码:
package xzh.com.listviewhover.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import xzh.com.listviewhover.R;
import xzh.com.listviewhover.base.Constants;

/**  * Created by xiangzhihong on 2016/3/14 on 12:07.  * 测试服务端的登录json  */ public class LoginActivity extends AppCompatActivity {
    @InjectView(R.id.account)
    EditText account;
    @InjectView(R.id.pwd)
    EditText pwd;
    @InjectView(R.id.login)
    Button login;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
       initProxy();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        initView();
    }

    private void initProxy() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .build());
        //设置虚拟机的策略  StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());
    }

    private void initView() {
    }

    @OnClick(R.id.login)
    void loginClick(View v){
        String userName=account.getText().toString();
        String password=pwd.getText().toString();
        doLogin(userName,password);
    }

    private void doLogin(String userName, String password) {
        final String[] result = {null};
        String reqUrl=null;
        reqUrl= Constants.LOGIN_URL+"userName="+userName+"&password="+password;
        try {
            doHttp(result, reqUrl);
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setTitle("提示")
                    .setMessage(result[0])
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(LoginActivity.this,MainActivity.class));
                        }
                    }).setNegativeButton("取消",new DialogInterface.OnClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create().show();

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

    private void doHttp(final String[] result, String reqUrl) {

        // HttpClient httpclient = new DefaultHttpClient(); // HttpGet request=new HttpGet(reqUrl); // request.addHeader("Accept","text/json"); // HttpResponse response =httpclient.execute(request); // HttpEntity entity=response.getEntity(); // String json = EntityUtils.toString(entity,"UTF-8"); // if(json!=null&&json.contains("message")){ //// JSONObject jsonObject=new JSONObject(json); //// result=jsonObject.get("message").toString(); // result="登录成功"; // }else { // result="登录失败请重新登录"; // }   AsyncHttpClient client = new AsyncHttpClient();
        client.get(this,reqUrl,new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content!=null&&content.contains("message")){
                    result[0] ="登录成功";
                }else {
                    result[0] ="登录失败";
                }
            }
        });
    }
}
好了,就到这,有需要的需要体验的请到我的git账号下载测试程序。

服务端代码:https://github.com/xiangzhihong/login

客户端代码:https://github.com/xiangzhihong/loginAndroid



你可能感兴趣的:([置顶] Android+struts2+json方式模拟手机登录功能)