服务器端是tomcat服务器+Mysql数据库,安卓客户端使用POST方法连接servlet,实现简单的登录、注册程序。该servlet在Java web开发中已经实现好了,现在拿到安卓中用。
MVC结构是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。
public class AndroidLogin extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
//设置客户端的解码方式为utf-8
response.setContentType("text/html;charset=utf-8");
//
response.setCharacterEncoding("UTF-8");
boolean b=false;
userlogin MyPOJO=new userlogin();//新建MyPOJO类的对象myPOJO
//根据标示名获取JSP文件中表单所包含的参数
String id=request.getParameter("id");
String password=request.getParameter("password");
String result = "";
b=MyPOJO.isuserlogin(id,password);//使用模型对账号和密码进行验证,返回一个boolean类型的对象
PrintWriter out = response.getWriter();//回应请求
if(b){ //如果验证结果为真,跳转至登录成功页面
result = "success";
}
else { //如果验证结果为假,跳转至登录失败页面
result = "fail";
}
out.write(result);
out.flush();
out.close();
System.out.println(result);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
数据库模型层函数,存在返回true,不存在返回false:
import java.sql.*;
public class userlogin {
String drv = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/login";
String usr = "root";
String pwd = "***";
public boolean isuserlogin(String id,String password){
boolean isValid = false;
String sql="select * from ulogin where uname='"+id+"' and password='"+password+"'";
try{
Class.forName(drv).newInstance();
Connection conn = DriverManager.getConnection(url,usr,pwd);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(sql);
if(rs.next()){
isValid = true;
}
rs.close();
stm.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
if(isValid){//判断用户名以及密码是否与设定相符
return true;
}
else return false;
}
}
注册,返回servlet:
public class androidregister extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
//设置客户端的解码方式为utf-8
response.setContentType("text/html;charset=utf-8");
//
response.setCharacterEncoding("UTF-8");
boolean b = false;
register myPOJO=new register();
String id=request.getParameter("id");
String password=request.getParameter("password");
String email = request.getParameter("email");
String result = "";
b=myPOJO.userregister(id,password,email);//连接数据库,插入该用户信息
PrintWriter out = response.getWriter();//回应请求
if(b){
result = "success";
}
else{
result = "fail";
}
out.write(result);
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
数据库模型层,插入数据
public class register {
String drv = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/login";
String usr = "root";
String pwd = "***";
public boolean userregister(String id,String password,String email){
boolean b = false;
String sql = "select * from ulogin where uname='"+id+"'";
try{
Class.forName(drv).newInstance();
Connection conn = DriverManager.getConnection(url,usr,pwd);
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(sql);
if(!rs.next()){
sql = "insert into ulogin(uname,password,email) values('"+id+"','"+password+"','"+email+"')";
stm.execute(sql);
b = true;
}
rs.close();
stm.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
if(b)
{
return true;
}
else return false;
}
}
web.xml配置
AndroidLogin
service.AndroidLogin
AndroidLogin
/androidlogin.do
AndroidRegister
service.androidregister
AndroidRegister
/androidregister.do
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener{
private Button login,register;
private EditText id,password;
private final static int LOGIN_JUDGE = 1;
private int RequestCode = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
register = (Button) findViewById(R.id.register);
register.setOnClickListener(this);
id = (EditText) findViewById(R.id.id);
password = (EditText) findViewById(R.id.password);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1&&resultCode==2){
id.setText(data.getStringExtra("id"));
password.setText(data.getStringExtra("password"));
}
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
switch (msg.what){
case LOGIN_JUDGE:{
Bundle bundle = new Bundle();
bundle = msg.getData();
String result = bundle.getString("result");
//Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
try {
if (result.equals("success")) {
Toast.makeText(MainActivity.this,"登录成功!",Toast.LENGTH_SHORT).show();
}
}catch (NullPointerException e){
e.printStackTrace();
}
}
break;
}
}
};
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.login:{
new Thread(new Runnable() {
@Override
public void run() {
//使用下面类里的函数,连接servlet,返回一个result,使用handler处理这个result
String result = HttpLogin.LoginByPost(id.getText().toString(),password.getText().toString());
Bundle bundle = new Bundle();
bundle.putString("result",result);
Message message = new Message();
message.setData(bundle);
message.what = LOGIN_JUDGE;
handler.sendMessage(message);
}
}).start();
}
break;
case R.id.register:{
Intent intent = new Intent(this,RegisterActivity.class);
startActivityForResult(intent,RequestCode);
}
break;
}
}
}
注册实现,如果注册成功,则返回用户名和密码给上一个活动
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private int ResultCode = 2;
private final static int REGISTER_JUDGE = 2;
private Button register,back;
private EditText id,psw_1,psw_2,email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
register = (Button) findViewById(R.id.register_do);
register.setOnClickListener(this);
id = (EditText) findViewById(R.id.id_edit);
psw_1 = (EditText) findViewById(R.id.password_edit);
psw_2 = (EditText) findViewById(R.id.password_edit_1);
email = (EditText) findViewById(R.id.email_edit);
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
switch (msg.what){
case REGISTER_JUDGE:{
Bundle bundle = new Bundle();
bundle = msg.getData();
String result = bundle.getString("result");
//Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
try {
if (result.equals("success")) {
Intent intent = new Intent();
intent.putExtra("id",id.getText().toString());
intent.putExtra("password",psw_1.getText().toString());
setResult(ResultCode,intent);//向上一级发送数据
finish();
}
}catch (NullPointerException e){
e.printStackTrace();
}
}
break;
}
}
};
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.register_do:{
if( ! psw_1.getText().toString().equals(psw_2.getText().toString())){
Toast.makeText(RegisterActivity.this,"两次密码不一致!",Toast.LENGTH_LONG).show();
}else {
new Thread(new Runnable() {
@Override
public void run() {
String result = HttpLogin.RegisterByPost(id.getText().toString(),
psw_1.getText().toString(),email.getText().toString());
Bundle bundle = new Bundle();
bundle.putString("result",result);
Message msg = new Message();
msg.what = REGISTER_JUDGE;
msg.setData(bundle);
handler.sendMessage(msg);
}
}).start();
}
}
break;
}
}
}
布局:
HttpLogin类,连接servlet,获取返回值
public class HttpLogin {
public static String LoginByPost(String id,String password){
String address = "http://www.khqust.top/MyWebsite/androidlogin.do";
String result = "";
try{
URL url = new URL(address);//初始化URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");//请求方式
//超时信息
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//post方式不能设置缓存,需手动设置为false
conn.setUseCaches(false);
//我们请求的数据
String data = "id="+ URLEncoder.encode(id,"UTF-8")+
"&password="+ URLEncoder.encode(password,"UTF-8");
//获取输出流
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
conn.connect();
if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
result = new String(message.toByteArray());
//return result;
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return result;
}
public static String RegisterByPost(String id,String password,String email){
String address = "http://www.khqust.top/MyWebsite/androidregister.do";
String result = "";
try{
URL url = new URL(address);//初始化URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");//请求方式
//超时信息
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//post方式不能设置缓存,需手动设置为false
conn.setUseCaches(false);
//我们请求的数据
String data = "id="+ URLEncoder.encode(id,"UTF-8")+
"&password="+ URLEncoder.encode(password,"UTF-8")+
"&email="+ URLEncoder.encode(email,"UTF-8");
//获取输出流
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
conn.connect();
if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
result = new String(message.toByteArray());
//return result;
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return result;
}
}