Android登录注册功能实现:Json+Servlet+sqlserver

服务端

(一)DBManager 数据库管理

负责连接数据库和封装三个方法,1、获取数据库信息 2、根据sql语句查询 3、根据sql语句更新

public class DBManager {

    public final static String TABLE_NAME="android_user";

    public final static String USERNAME="username";
    public final static String PASSWORD="password";
    public Statement getStatement() {
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.microsoft.sqlserver.jdbc");
            connection = (Connection) DriverManager.getConnection("jdbc:sqlserver://localhost:1433;useUnicode=true;databaseName=mybatis", "sa", "12345678");
            statement = connection.createStatement();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return statement;
    }
    public ArrayList<HashMap<String,Object>> getDatabaseInfo()
    {
        ArrayList<HashMap<String,Object>> lists=new ArrayList<>();
        HashMap<String,Object> map=null;
        String sql = " select * from  " + TABLE_NAME;
        Statement statement = getStatement();
        ResultSet resultSet=null;
        try {
            resultSet=statement.executeQuery(sql);
            if(resultSet.next())
            {
                map=new HashMap<>();
                map.put(USERNAME,resultSet.getString(DBManager.USERNAME));
                map.put(PASSWORD,resultSet.getString(DBManager.PASSWORD));
                lists.add(map);
            }
        }catch (SQLException e)
        {
            e.printStackTrace();
        }
        return lists;
    }
    //查询返回结果集
    public ResultSet query(String sql) {
        ResultSet resultSet = null;
        Statement statement = getStatement();
        System.out.println("stmt = " + statement);
        try {
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resultSet;
    }
    //更新返回更新条数
    public int update(String sql) {
        Statement statement = getStatement();
        int result = 0;
        try {
            result = statement.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}

(二)LoginHandler登录处理

继承HttpServlet,根据客户端传来的username,password判断,然后把四种情况的result(Json格式)通过output.writeUTF(result);返回给客户端

public class LoginHandler extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
        resp.setContentType("text/html; charset=UTF-8");

        DataOutputStream output=new DataOutputStream(resp.getOutputStream());

        String userName=req.getParameter("username");
        String password=req.getParameter("password");

        String result=doLogin(userName,password);
        System.out.println("result = " + result);
        output.writeUTF(result);

    }

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    private String doLogin(String userName, String password) {
        /*
         * login_result:
         * -1:登陆失败,未知错误!
         * 0: 登陆成功!
         * 1:登陆失败,用户名或密码错误!
         * 2:登陆失败,用户名不存在!
         * */
        HashMap<String,Object> map=new HashMap<>();
        String sql="select * from"+ DBManager.TABLE_NAME+" where "+DBManager.USERNAME+" = "+"'"+userName+"'";
        DBManager dbManager=new DBManager();
        ResultSet result=dbManager.query(sql);
        try{
            result.next();
            String pwd=result.getString(DBManager.PASSWORD);
            if (!password.equals(pwd))
            {
                map.put("login_result",-1);
            }else
            {
                map.put("login_result",0);
                map.put(DBManager.USERNAME,result.getString(DBManager.USERNAME));
                map.put(DBManager.PASSWORD,result.getString(DBManager.PASSWORD));
            }

        }catch (SQLException e)
        {
            e.printStackTrace();
            map.put("login_result",2);
        }
        return (new Gson()).toJson(map);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

(三)NewUser 注册

public class NewUser extends HttpServlet{


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        Content-Type
         用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件
         CharacterEncoding
         作用是设置对客户端请求进行重新编码的编码

         也就是说一个是设置读,一个是设置取
         */
        resp.setContentType("text/html;charset=UTF-8");
        //DataOutputStream将负责建立到中间人的连接 ,获取响应输出流对象,然后在里面写东西
        DataOutputStream output=new DataOutputStream(resp.getOutputStream());
       //根据请求获取单个用户信息
        HashMap<String,Object> map=getParamsFromRequest(req);
        //判断是否存在该用户
        String result=HandleNewUser(map);
        output.writeUTF(result);
    }

    private String HandleNewUser(HashMap<String, Object> map) {
        /*
         *   result_code:
         * 0 用户名不存在,可以正常注册
         * 1  用户名已存在
         * 2 数据库操作异常
         * */
        //result存放三种情况的标记
        HashMap<String,Object> result=new HashMap<>();
        String userName= (String) map.get(DBManager.USERNAME);
        if(isUsernameExisted(userName))
        {
            result.put("result_code", 1);
        }else {
            DBManager dbManager=new DBManager();
            String password= (String) map.get(DBManager.PASSWORD);
            String sql = "Insert into " + DBManager.TABLE_NAME + " values ("
                    + "'" + userName + "',"
                    + "'" + password +  "')";

            System.out.println("sql = " + sql);
            int executeResult = dbManager.update(sql);
            if(executeResult == 0) {
                result.put("result_code", 2);
            } else {
                result.put("result_code", 0);
            }
        }
        //Gson将java对象转换为JSON
        return (new Gson()).toJson(result);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }


   //根据请求获取单个用户信息
    HashMap<String,Object> getParamsFromRequest(HttpServletRequest request)
    {
        HashMap<String,Object> map=new HashMap<>();
        map.put(DBManager.USERNAME,request.getParameter(DBManager.USERNAME));
        map.put(DBManager.PASSWORD,request.getParameter(DBManager.PASSWORD));
        return map;
    }
    boolean isUsernameExisted(String username)
    {
        Boolean isExisted=true;
        DBManager dbManager=new DBManager();
        String sql="select * from "+DBManager.TABLE_NAME+" where "
                +DBManager.USERNAME+" = "+"'"+username+"'";
        ResultSet resultSet= dbManager.query(sql);
        try {
            resultSet.next();
            String user=resultSet.getString("1");
            isExisted=true;

        }catch (SQLException e)
        {
            isExisted=false;
            e.printStackTrace();

        }
        return isExisted;
    }
}

android客户端

(一)LoginActivity

public class LoginActivity extends Activity implements OnClickListener {
    private EditText loginUsername;
    private EditText loginPassword;
    private Button loginButton;
    private Button createButton;

    private ProgressDialog loginProgress;

    public static final int MSG_LOGIN_RESULT = 0;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch(msg.what) {
            case MSG_LOGIN_RESULT:
                loginProgress.dismiss();
                JSONObject json = (JSONObject) msg.obj;
                handleLoginResult(json);
                break;
            }
        };
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        initViews();
    }
    private void initViews() {
        loginUsername = (EditText)findViewById(R.id.login_username);
        loginPassword = (EditText)findViewById(R.id.login_password);
        loginButton   = (Button)findViewById(R.id.login);
        createButton  = (Button)findViewById(R.id.create_count);

        loginButton.setOnClickListener(this);
        createButton.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.login:
            handleLogin();
            break;
        case R.id.create_count:
            handleCreateCount();
            break;
        default:
            break;  
        }

    }
    private void handleLogin() {
        String username = loginUsername.getText().toString();
        String password = loginPassword.getText().toString();
        login(username, password);
    }
    private void login(final String username, final String password) {
        loginProgress = new ProgressDialog(this);
        loginProgress.setCancelable(false);
        loginProgress.setCanceledOnTouchOutside(false);
        loginProgress.show(this, null, "登录中...");

        //创建子线程用于网络连接
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("First app", "start network!");
                HttpClient client = new DefaultHttpClient();
                 创建一个HttpPost对象,传入目标的网络地址
                HttpPost httpPost = new HttpPost("http://192.168.1.116:8080/AndroidWeb/servlet/LoginHandler");
                /*
                 * 通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中
                 */
                List<NameValuePair> params = new ArrayList<NameValuePair>(); 
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                HttpResponse httpResponse = null;
                try {
                    //调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入
                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    //调用HttpClient的execute()方法,并将HttpPost对象传入
                    //执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所有信息就保护在HttpResponse里面
                    httpResponse = client.execute(httpPost);
                    //先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了
                    if(httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.d("First app", "network OK!");
                        HttpEntity entity = httpResponse.getEntity();
                        把实体内容转成字符串
                        String entityString = EntityUtils.toString(entity);
                        String jsonString = entityString.substring(entityString.indexOf("{"));
                        Log.d("First app", "entity = " + jsonString);
                        // 转成json
                        JSONObject json = new JSONObject(jsonString);
                        sendMessage(MSG_LOGIN_RESULT, json);
                        Log.d("First app", "json = " + json);
                    }
                } catch (UnsupportedEncodingException e) {
                    Log.d("yanghongbing", "UnsupportedEncodingException");
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    Log.d("yanghongbing", "ClientProtocolException");
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.d("yanghongbing", "IOException");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    Log.d("yanghongbing", "IOException");
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void handleCreateCount() {
        Intent intent = new Intent(this, CreateUserActivity.class);
        startActivity(intent);
        finish();
    }

    private void handleLoginResult(JSONObject json){
        /*
         * 
         * */
        int resultCode = -1;
        try {
            resultCode = json.getInt("result_code");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        switch(resultCode) {
        case 0:
            onLoginSuccess(json);
            break;
        case 1:
            Toast.makeText(this, "登陆失败,用户名或密码错误!", Toast.LENGTH_SHORT).show();
            break;
        case 2:
            Toast.makeText(this, "用户名不存在", Toast.LENGTH_SHORT).show();
            break;
        case -1:
        default:
            Toast.makeText(this, "登陆失败!未知错误", Toast.LENGTH_SHORT).show();
            break;
        }
    }

    private void onLoginSuccess(JSONObject json) {
        Intent intent = new Intent(this, UserInfoActivity.class);

        try {
            intent.putExtra("username", json.getString("username"));
            intent.putExtra("gender", json.getString("gender"));
            intent.putExtra("age", json.getInt("age"));
            intent.putExtra("phone", json.getString("phone"));
            intent.putExtra("email", json.getString("email"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        startActivity(intent);
        finish();
    }
    private void sendMessage(int what, Object obj) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}

(二)CreateUserActivity

public class  extends Activity implements OnClickListener {

    public static final String CREATE_ACCOUNT_URL = "http://192.168.1.116:8080/AndroidWeb/servlet/NewUser";
    public static final int MSG_CREATE_RESULT = 1;

    private EditText eUsername;
    private EditText ePwd1;
    private EditText ePwd2;


    private Button btnSubmit;
    private Button btnReset;

    ProgressDialog progress;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch(msg.what) {
            case MSG_CREATE_RESULT:
                progress.dismiss();
                JSONObject json = (JSONObject) msg.obj;
                hanleCreateAccountResult(json);
                break;
            }
        }   
    };

    private void hanleCreateAccountResult(JSONObject json) {
        /*
         *   *   result_code: 
         * 0  注册成功
         * 1  用户名已存在
         * 2 数据库操作异常
         * */
        int result;
        try {
            result = json.getInt("result_code");
        } catch (JSONException e) {
            Toast.makeText(this, "没有获取到网络的响应!", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            return;
        }

        if(result == 1) {
            Toast.makeText(this, "用户名已存在", Toast.LENGTH_LONG).show();
            return;
        }

        if(result == 2) {
            Toast.makeText(this, " 数据库操作异常", Toast.LENGTH_LONG).show();
            return;
        }

        if(result == 0) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_user_activity);

        initViews();
    }

    private void initViews() {
        eUsername = (EditText)findViewById(R.id.new_username);
        ePwd1 = (EditText)findViewById(R.id.new_password_1);
        ePwd2 = (EditText)findViewById(R.id.new_password_2);

        btnSubmit = (Button)findViewById(R.id.new_btn_submit);
        btnReset = (Button)findViewById(R.id.new_btn_reset);
        btnSubmit.setOnClickListener(this);
        btnReset.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.new_btn_submit:
            handleCreateAccount();
            break;
        case R.id.new_btn_reset:
            handleReset();
            break;
        }

    }

    private void handleCreateAccount() {
        boolean isUsernameValid = checkUsername();
        if(!isUsernameValid) {
            Toast.makeText(this, "用户名不正确,请重新输入", Toast.LENGTH_LONG).show();
            return;
        }

        int pwdResult = checkPassword();
        if(pwdResult == 1) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_LONG).show();
            return;
        } 
        if (pwdResult == 2) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }


        createAccount();
    }

    private void createAccount() {
        progress = new ProgressDialog(this);
        progress.setCancelable(false);
        progress.setCanceledOnTouchOutside(false);
//      progress.show(this, null, "注册中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("First app", "Start Network!");
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(CREATE_ACCOUNT_URL);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", eUsername.getText().toString()));
                params.add(new BasicNameValuePair("password", ePwd1.getText().toString()));

                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if(httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.d("First app", "Network OK!");
                        HttpEntity entity = httpResponse.getEntity();
                        String entityStr = EntityUtils.toString(entity);
                        String jsonStr = entityStr.substring(entityStr.indexOf("{"));
                        JSONObject json = new JSONObject(jsonStr);
                        sendMessage(MSG_CREATE_RESULT, json);

                    }
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private boolean checkUsername() {
        String username = eUsername.getText().toString();
        if(TextUtils.isEmpty(username)) {
            return false;
        }
        return true;
    }

    private int checkPassword() {
        /*
         * return value:
         * 0 password valid
         * 1 password not equal 2 inputs
         * 2 password empty
         * */
        String pwd1 = ePwd1.getText().toString();
        String pwd2 = ePwd2.getText().toString();
        if(!pwd1.equals(pwd2)) {
            return 1;
        } else if(TextUtils.isEmpty(pwd1)) {
            return 2;
        } else {
            return 0;
        }
    }

    private void handleReset() {
        eUsername.setText("");
        ePwd1.setText("");
        ePwd2.setText("");

    }

    private void sendMessage(int what, Object obj) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

}

(三)UserInfoActivity

显示用户信息,登录成功加入的界面

public class UserInfoActivity extends Activity {
    private TextView tvUsername;
    private TextView tvPassword;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_info_activity);
        initViews();
        Intent intent = getIntent();
        displayUserInfo(intent);
    }

    private void initViews() {
        tvUsername = (TextView) findViewById(R.id.usr_info_username);
        tvPassword   = (TextView) findViewById(R.id.usr_info_password);

    }

    private void displayUserInfo(Intent intent) {
        String username = intent.getStringExtra("username");
        String password   = intent.getStringExtra("password");


        tvUsername.setText(username);
        tvPassword.setText(password);

    }

}
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值