开发者社区> 问答> 正文

新建一个服务器,android客户端通过服务器和SQL Server 2005交互,:报错

package com.guo.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.guo.dao.UserDao;
import com.guo.entity.User;
import com.guo.util.DBUtil;

public class UserDaoImpl implements UserDao {
	public User login(String username,String password) {
		//SQL 查询语句
		String sql = "select id,username,password from UserTbl where username=? and password=?";
		String sql1 = "update UserTbl set id=2 where username=?";
		//实例化数据库工具类
		DBUtil util = new DBUtil();
		//获得数据库连接
		Connection conn = util.openConnection();
		try {
			//创建预定义语句
			PreparedStatement ps = conn.prepareStatement(sql);
			//设置查询参数
			ps.setString(1, username);
			ps.setString(2, password);
			//结果集
			ResultSet rs = ps.executeQuery();
			//判断该用户是否存在
			if(rs.next()) {
				//获得编号
				int id = rs.getInt(1);
				//实例化User
				User user = new User();
				//设置User属性
				user.setId(id);
				user.setPassword(password);
				user.setUsername(username);
				
				try {
				PreparedStatement ps1 = conn.prepareStatement(sql1);
				ps1.setString(1, username);
				} catch(SQLException e) {
					e.printStackTrace();
				}
				return user;
			}
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			util.closeConnection(conn);
		}
		return null;
	}
}

package com.guo.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guo.dao.UserDao;
import com.guo.dao.impl.UserDaoImpl;
import com.guo.entity.User;
 
public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		UserDao dao = new UserDaoImpl();
		//获得客户端请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		User user = dao.login(username,password);
		if(user!=null) {
			//响应客户端内容,登录成功
//			out.print(build(user));
			out.print("1");
		} else {
			//响应客户端内容,登录失败
			out.print("0");
		}
		out.flush();
		out.close();
	}

	//将用户对象转换为字符串返回给客户端
	private String build(User user) {
		String userMsg = "";
		userMsg += "id=" + user.getId();
		userMsg += ";";
		userMsg += "username=" + user.getUsername();
		return userMsg;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//调用doGet方法
		doGet(request, response);
	}
	//初始化方法
	public void init() throws ServletException {
		
	}
	//构造方法
	public LoginServlet() {
		super();
	}
	//销毁方法
	public void destroy() {
		super.destroy();
	}
}

package com.guo.wlo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.guo.util.HttpUtil;

public class LoginActivity extends Activity {
    /** Called when the activity is first created. */
	//声明登录、取消按钮
	private Button cancelBtn, loginBtn;
	//声明用户名密码输入框
	private EditText userEditText,pwdEditText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置标题
        setTitle("移动办公自动化系统");
        //设置当前Activity界面布局
        setContentView(R.layout.login_system);
        //通过findViewById方法实例化组件
        cancelBtn = (Button)findViewById(R.id.cancelButton);
        //通过findViewById方法实例化组件
        loginBtn = (Button)findViewById(R.id.loginButton);
        //通过findViewById方法实例化组件
        userEditText = (EditText)findViewById(R.id.userEditText);
        //通过findViewById方法实例化组件
        pwdEditText = (EditText)findViewById(R.id.pwdEditText);
        
        cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(validate()){
					if(login()){
						Intent intent = new Intent(LoginActivity.this,MainMenuActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
					}else{
						showDialog("用户名称或者密码错误,请重新输入!");
					}
				}
			}
		});
    }
    //登录方法
	private boolean login(){
    	//获得用户名称
		String username = userEditText.getText().toString();
		//获得密码
		String pwd = pwdEditText.getText().toString();
		//获得登录结果
		String result=query(username,pwd);
		/*
		if(result!=null&&result.equals("0")) {
			return false;
		} else if(result==null) {
			return false;
		} else {
			saveUserMsg(result);
			return true;
		}
		*/
		if(result!=null) {
			return true;
		} else {
			return false;
		}
	}
	//对用户名和密码非空进行验证
	private boolean validate(){
		String username = userEditText.getText().toString();
		if(username.equals("")){
			showDialog("用户名称是必填项!");
			return false;
		}
		String pwd = pwdEditText.getText().toString();
		if(pwd.equals("")){
			showDialog("用户密码是必填项!");
			return false;
		}
		return true;
	}
	//定义一个显示提示信息的对话框
	private void showDialog(String msg){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg)
		       .setCancelable(false)
		       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
	}
	//通过登录帐号和密码进行查询,发送Post请求,获得相应结果
	private String query(String username,String password){
		//查询字符串
		String queryString = "username="+username+"&password="+password;
		//查询URL
		String url = HttpUtil.BASE_URL+"servlet/LoginServlet?"+queryString;
		//查询并返回结果
		return HttpUtil.queryStringForPost(url);
    }

	//将用户信息保存到配置文件
	private void saveUserMsg(String msg) {
		//用户编号
		String id = "";
		//用户名称
		String username = "";
		try {
			//获得信息数组
			String[] msgs = msg.split(";");
			int idx = msgs[0].indexOf("=");
			id = msgs[0].substring(idx+1);
			idx = msgs[1].indexOf("=");
			username = msgs[1].substring(idx+1);
		} catch(ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();
		}
		//共享信息
		SharedPreferences pre = getSharedPreferences("user_msg", MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor editor = pre.edit();
		//保存用户Id
		editor.putString("id", id);
		//保存用户名称
		editor.putString("username", username);
		//提交
		editor.commit();
	}
}

package com.guo.util;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	//声明Base URL常量
	public static final String BASE_URL = "http://localhost:8080/mobile_OA_Server/";
	
	//通过url获得HttpGet对象
	public static HttpGet getHttpGet(String url) {
		//实例化HttpGet
		HttpGet request = new HttpGet(url);
		return request;
	}
	
	//通过url获得HttpPost对象
	public static HttpPost getHttpPost(String url) {
		//实例化HttpPost
		HttpPost request = new HttpPost(url);
		return request;
	}
	
	//通过HttpGet获得HttpResponse对象
	public static HttpResponse getHttpResponse(HttpGet request)
			throws ClientProtocolException,IOException {
		//实例化HttpResponse
		HttpResponse response = new DefaultHttpClient().execute(request);
		return response;
	}
	
	//通过HttpPost获得HttpResponse对象
	public static HttpResponse getHttpResponse(HttpPost request) 
			throws ClientProtocolException, IOException {
		//实例化HttpResponse
		HttpResponse response = new DefaultHttpClient().execute(request);
		return response;
	}
	
	//通过url发送post请求,返回请求结果
	public static String queryStringForPost(String url) {
		//获得HttpPost实例
		HttpPost request = HttpUtil.getHttpPost(url);
		String result = null;
		try {
			//获得HttpResponse实例
			HttpResponse response = HttpUtil.getHttpResponse(request);
			//判断是否请求成功
			if(response.getStatusLine().getStatusCode() == 200) {
				//获得返回结果
				result = EntityUtils.toString(response.getEntity());
				return result;
			}
		} catch(ClientProtocolException e) {
			e.printStackTrace();
			result = "网络异常!";
			return result;
		} catch(IOException e) {
			e.printStackTrace();
			result = "网络异常!";
			return result;
		}
		return null;
	}
	
	//通过url发送get请求,返回请求结果
	public static String queryStringForGet(String url) {
		//获得HttpGet实例
		HttpGet request = HttpUtil.getHttpGet(url);
		String result = null;
		try {
			//获得HttpResponse实例
			HttpResponse response = HttpUtil.getHttpResponse(request);
			//判断是否请求成功
			if(response.getStatusLine().getStatusCode() == 200) {
				//获得返回结果
				result = EntityUtils.toString(response.getEntity());
				return result;
			}
		} catch(ClientProtocolException e) {
			e.printStackTrace();
			result = "网络异常!";
			return result;
		} catch(IOException e) {
			e.printStackTrace();
			result = "网络异常!";
			return result;
		}
		return null;
	}
	
	//通过HttpPost发送post请求,返回请求结果
	public static String queryStringForPost(HttpPost request) {
		String result = null;
		try {
			//获得HttpResponse实例
			HttpResponse response = HttpUtil.getHttpResponse(request);
			//判断是否请求成功
			if(response.getStatusLine().getStatusCode() == 200) {
				//获得请求结果
				result = EntityUtils.toString(response.getEntity());
				return result;
			}
		} catch(ClientProtocolException e){
			e.printStackTrace();
			result = "网络异常!";
			return result;
		} catch(IOException e) {
			e.printStackTrace();
			result = "网络异常!";
			return result;
		}
		return null;
	}
}

登录方法中query方法不管用,只要输入任意用户名和密码都能进入客户端

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/login" >
    
	<TableLayout
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	    android:stretchColumns="1">
	    
	    <TableRow>
	        <TextView 
	            android:text="用户名称:"
	            android:id="@+id/TextView"
	            android:layout_width="wrap_content"
	            android:layout_height="wrap_content"
	            android:textColor="#0000ff"/>
	        
	        <EditText
	            android:text=""
	            android:id="@+id/userEditText"
	            android:layout_width="fill_parent"
	            android:layout_height="wrap_content"/>
	    </TableRow>
	    
	    <TableRow>
	        <TextView 
	            android:text="用户密码:"
	            android:id="@+id/TextView"
	            android:layout_width="wrap_content"
	            android:layout_height="wrap_content"
	            android:textColor="#0000ff"/>
	        
	        <EditText
	            android:text=""
	            android:id="@+id/pwdEditText"
	            android:layout_width="fill_parent"
	            android:layout_height="wrap_content"
	            android:password="true"/>
	    </TableRow>
	    
	    <TableRow
	        android:gravity="right">
	        
	        <Button
	            android:text="退出"
	            android:id="@+id/cancelButton"
	            android:layout_width="wrap_content"
	            android:layout_height="wrap_content"/>
	        
	        <Button
	            android:text="登录"
	            android:id="@+id/loginButton"
	            android:layout_width="wrap_content"
	            android:layout_height="wrap_content"/>
	    </TableRow>
	</TableLayout>
</LinearLayout>

展开
收起
kun坤 2020-06-06 00:39:50 926 0
1 条回答
写回答
取消 提交回答
  • 好像??错了就是错了,没错就是没错,还有好像的? :)

    ######

    客户端登录,输入任意用户名和密码都能进入客户端,我不知道哪里出了问题,纠结了好几天了,希望大家帮忙看看,String sql1 = "update UserTbl set id=2 where username=?";这条SQL语句是为了验证客户端是否和服务器连接上,结果数据库中的数据并没有改变,但是,我又没找到客户端和服务器之间的连接哪里出了问题,希望大家帮忙看看,指导我一下,谢谢!

    ######呵呵看我空间里的android客户端与服务器端登陆返回json数据例子######在你空间没找到啊
    2020-06-06 00:39:59
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何运维千台以上游戏云服务器 立即下载
网站/服务器取证 实践与挑战 立即下载
ECS块储存产品全面解析 立即下载