转载:http://blog.csdn.net/zlfxy/article/details/8508176
该程序通过提交数据给服务器,服务器通过servlet验证后,返回信息给客户端。
先上效果图吧:此登录的客户端Demo是通过下载的源码,服务器端我自己写的。
登录成功后效果:
1、Android客户端的代码为:
- package com.loulijun.logindemo;
- import java.security.MessageDigest;
- import java.util.ArrayList;
- import java.util.List;
- 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.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.params.BasicHttpParams;
- import org.apache.http.params.HttpConnectionParams;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.app.ProgressDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.content.SharedPreferences.Editor;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo.State;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.provider.Settings;
- import android.view.View;
- import android.widget.Button;
- import android.widget.CheckBox;
- import android.widget.CompoundButton;
- import android.widget.EditText;
- import android.widget.Toast;
- public class LoginDemoActivity extends Activity {
- /** Called when the activity is first created. */
- private Button loginBtn;
- private Button registerBtn;
- private EditText inputUsername;
- private EditText inputPassword;
- private ProgressDialog mDialog;
- private String responseMsg = "";
- private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟
- private static final int SO_TIMEOUT = 10*1000; //设置等待数据超时时间10秒钟
- private static final int LOGIN_OK = 1;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.login);
- loginBtn = (Button)findViewById(R.id.login_btn_login);
- registerBtn = (Button)findViewById(R.id.login_btn_zhuce);
- inputUsername = (EditText)findViewById(R.id.login_edit_account);
- inputPassword = (EditText)findViewById(R.id.login_edit_pwd);
- //登录
- loginBtn.setOnClickListener(new Button.OnClickListener()
- {
- @Override
- public void onClick(View arg0) {
- mDialog = new ProgressDialog(LoginDemoActivity.this);
- mDialog.setTitle("登陆");
- mDialog.setMessage("正在登陆服务器,请稍后...");
- mDialog.show();
- Thread loginThread = new Thread(new LoginThread());
- loginThread.start();
- }
- });
- registerBtn.setOnClickListener(new Button.OnClickListener()
- {
- @Override
- public void onClick(View arg0) {
- Intent intent = new Intent();
- intent.setClass(LoginDemoActivity.this, RegisterActivity.class);
- startActivity(intent);
- }
- });
- }
- private boolean loginServer(String username, String password)
- {
- boolean loginValidate = false;
- //使用apache HTTP客户端实现
- String urlStr = "http://10.0.2.2:8080/Login/Login";
- HttpPost request = new HttpPost(urlStr);
- //如果传递参数多的话,可以对传递的参数进行封装
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- //添加用户名和密码
- params.add(new BasicNameValuePair("username",username));
- params.add(new BasicNameValuePair("password",password));
- try
- {
- //设置请求参数项
- request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- HttpClient client = getHttpClient();
- //执行请求返回相应
- HttpResponse response = client.execute(request);
- //判断是否请求成功
- if(response.getStatusLine().getStatusCode()==200)
- {
- loginValidate = true;
- //获得响应信息
- responseMsg = EntityUtils.toString(response.getEntity());
- }
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- return loginValidate;
- }
- //初始化HttpClient,并设置超时
- public HttpClient getHttpClient()
- {
- BasicHttpParams httpParams = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
- HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
- HttpClient client = new DefaultHttpClient(httpParams);
- return client;
- }
- //Handler
- Handler handler = new Handler()
- {
- public void handleMessage(Message msg)
- {
- switch(msg.what)
- {
- case 0:
- mDialog.cancel();
- Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
- Intent intent = new Intent();
- intent.setClass(LoginDemoActivity.this, MainActivity.class);
- startActivity(intent);
- finish();
- break;
- case 1:
- mDialog.cancel();
- Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();
- break;
- case 2:
- mDialog.cancel();
- Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();
- break;
- }
- }
- };
- //LoginThread线程类
- class LoginThread implements Runnable
- {
- @Override
- public void run() {
- String username = inputUsername.getText().toString();
- String password = inputPassword.getText().toString();
- System.out.println("username="+username+":password="+password);
- //URL合法,但是这一步并不验证密码是否正确
- boolean loginValidate = loginServer(username, password);
- System.out.println("----------------------------bool is :"+loginValidate+"----------response:"+responseMsg);
- Message msg = handler.obtainMessage();
- if(loginValidate)
- {
- if(responseMsg.equals("success"))
- {
- msg.what = 0;
- handler.sendMessage(msg);
- }else
- {
- msg.what = 1;
- handler.sendMessage(msg);
- }
- }else
- {
- msg.what = 2;
- handler.sendMessage(msg);
- }
- }
- }
- }
2、服务器端的主要代码为:
由于只是一个测试Demo,所以该测试并没有通过数据库的查询,而是直接在程序中写上固定的用户名和密码进行匹配。
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException
- {
- //response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- request.setCharacterEncoding("utf-8");
- String name = request.getParameter("username");
- //out.print(name);
- String pass = request.getParameter("password");
- //out.print(pass);
- if(("zlf").equals(name)&&"123456".equals(pass))
- {
- out.print("success");
- }
- else
- {
- out.print("failed");
- }
- }
- /**
- * The doPost method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to post.
- *
- * @param request the request send by the client to the server
- * @param response the response send by the server to the client
- * @throws ServletException if an error occurred
- * @throws IOException if an error occurred
- */
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException
- {
- doGet(request, response);
- }
如有需要,下载源码为:
改源码有下载的别人的源码,然后我自己没进行数据库连接,因此我改写了一下。在源码中,有一个android客户端文件夹,一个Login文件夹,一个LoginServlet文件夹。Login文件夹是我自己改写的servlet,测试可以正常运行。