目前的项目需要涉及到与服务器的交互,就把大概的代码贴出来交流一下。
大概的内容就是android端用post方法与服务器连接,然后在服务器端用servlet去根据用户名去查找数据库,如果用户名存在那么登录成功并查找存取的数据。
android端的内容:
final String uriConnection = "http://192.168.0.102:8080/IMLOP/servlet/MyServlet.servlet";
//用户名及其密码
String username;
String password;
//获取用户名及其密码
ed_username = (EditText) findViewById(R.id.username);
ed_password = (EditText) findViewById(R.id.password);
username = ed_username.getText().toString();
password = ed_password.getText().toString();
HttpResponse httpResponse = null;
List params = new ArrayList();
if (!username.equals("") && !password.equals("")) {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
}
try {
httpRequest.setEntity(new UrlEncodedFormEntity(params,
HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(httpRequest);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (httpResponse.getStatusLine().getStatusCode() == 200) {
Toast.makeText(getApplicationContext(), "登录成功",
Toast.LENGTH_SHORT).show();
}
然后是服务器上的servlet:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username= request.getParameter("username");
String password= request.getParameter("password");
response.getOutputStream().print(">>>>>>");
System.out.println("username:" + username);
System.out.println("password:" + password);
// 下面这的字符串是用于去数据库查找是否有匹配的用户
String parameters = username+ "," + password;
//匹配用户名及其密码 用了hibernate
List user = HibernateService.execProcedure("p_userBylogininfo_chk",
parameters);
//查询数据库的内容,VehicleDao类就是存放的一些数据的处理方法,使用其中的queryHQL方法查找
VehicleDao search_dao = new VehicleDao();
String search_information;
search_information = "select cs.publishTime,cs.arriveAt "
+ "from UserserviceCargosource cs ";
ArrayList> list;
try {
list = search_dao.queryHQL(search_information);
//打印查找到的内容
if (list != null && list.size() > 0) {
for (Object ob : list) {
Object[] id=(Object[])ob;
System.out.println(id[0]+" "+id[1]);
}
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
由于本人也只是很肤浅的学习了一下,有不足的地方希望大家提出来。