android登录tomcat服务器并查找数据库的内容
16lz
2021-01-24
目前的项目需要涉及到与服务器的交互,就把大概的代码贴出来交流一下。
大概的内容就是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<NameValuePair> params = new ArrayList<NameValuePair>();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 blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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;//匹配用户名及其密码 用了hibernateList 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 blocke.printStackTrace();}}
由于本人也只是很肤浅的学习了一下,有不足的地方希望大家提出来。
更多相关文章
- 【全球首个】Android声纹识别程序 SuperLock 2.3 Beta 抢先发送
- proguard-project.txt和project.properties混淆代码
- Android(安卓)- 分享内容 - 添加一个简单的分享操作
- Android(安卓)消息通知栏用法详解(一)
- Android之解决多语言适配部分TextView内容左对齐和内容一行不排
- Android中的文件存储数据方式 .
- Google 2018 更新内容
- android之ContentObserver内容观察者的使用
- Android(安卓)studio 生成的fragment_main.xml和activity_main.x