溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

發(fā)布時間:2020-12-08 16:43:03 來源:億速云 閱讀:221 作者:Leah 欄目:移動開發(fā)

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

環(huán)境部署

服務器:apache-tomcat-8.5.9

語言版本:Java 1.8.0_101

編譯環(huán)境:Eclipse

                  android Studio

調用jar包:httpclient-4.2.5,httpcore-4.2.4 //HttpClient父類

                   mysql-connector-java-5.1.40-bin //用于連接mysql數(shù)據庫

思路:涉及到服務器端mysql數(shù)據庫安裝、web應用部分開發(fā)和Android客戶端開發(fā)三個部分

步驟:

1、mysql數(shù)據庫安裝

a、先安裝mysql-installer-community-5.7.17.0,其中在Setup Type上選擇“Server only”,然后記住數(shù)據庫端口號和賬號(例如:root)密碼(例如:123456),如下圖:

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

b、安裝成功驗證。命令行窗口輸入密碼,然后輸入顯示所有數(shù)據庫命令:show databases; 一定要有分號,并按回車。

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

c、NavicatforMySQL下載及使用。注冊,然后連接數(shù)據庫,輸入密碼后,能夠看到已存在的數(shù)據庫,可以在其中進行相關數(shù)據庫和數(shù)據表的創(chuàng)建操作。

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

(具體以參考資料中的內容為主)

2、web應用部分開發(fā)

a、新建servlet,并且配置好web.xml中的相應信息(在WebContent下的WEB-INF文件夾下加入web.xml文件來連接servlet與jsp前端),此外還需在libs中添加mysql-connector-java-5.1.37-bin.jar文件,代碼如下:

package com.Servlet;
 
 import java.io.IOException;
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import java.io.PrintWriter;
 import java.sql.Connection;
 import java.sql.ResultSet;
 import java.sql.Statement;
 import com.DBTool.DBUtil;
 
 @WebServlet("/Servlet")
 public class Login extends HttpServlet {
   private static final long serialVersionUID = L;
    
   /**
   * @see HttpServlet#HttpServlet()
   */
   public Login() {
     super();
     // TODO Auto-generated constructor stub
   }
   /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     // TODO Auto-generated method stub
     response.getWriter().append("Served at: ").append(request.getContextPath());
   }
 
   /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String ID = request.getParameter("ID"); 
     String PW= request.getParameter("PW");
     boolean type=false;
     response.setContentType("text/html; charset=UTF-8");
     PrintWriter out = response.getWriter();
     try
     {
       Connection con=DBUtil.getConnection();
       Statement stmt=con.createStatement();
       //mysql數(shù)據庫中的數(shù)據表,表名叫:demotable ,需要自己預先在數(shù)據庫中進行創(chuàng)建,包含相應的字段和記錄。
       String sql="select * from mysql.demotable where uid="+ID+" and pwd="+PW;
       ResultSet rs=stmt.executeQuery(sql);
       while(rs.next())
       {
         type=true;
       }
     }
     catch(Exception ex)
     {
       ex.printStackTrace();
     }
     finally
     {
       DBUtil.Close();
       out.print(type);
       out.flush();
       out.close();
     }
   }
 
 }

web.xml內容如下:

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
   <display-name>web</display-name>
   <servlet>
     <display-name>Login</display-name>
     <servlet-name>Login</servlet-name>
     <servlet-class>com.Servlet.Login</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>Login</servlet-name>
     <url-pattern>/Login</url-pattern>
   </servlet-mapping>
   <welcome-file-list>
     <welcome-file>index.html</welcome-file>
     <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
 </web-app>

b、前端界面設計(TestPage.jsp)如下:

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Insert title here</title>
 </head>
 <body>
 <form id="from" action="Login" method="post">
 <table>
 <tr><td>用戶名</td><td><input type="text" name="ID"></td></tr>
 <tr><td>密碼</td><td><input type="password" name="PW"></td></tr>
 <tr><td colspan="2" align="center"><input type="submit" value="登陸"/></td></tr>
 </table>
 </form>
 </body>
 </html>

c、在java Resources下的src文件夾中新建com.DBTool包,用作數(shù)據池來連接數(shù)據庫,在包中建立DBUtil類實現(xiàn)功能,代碼如下:

package com.DBTool;
 
 
 import java.sql.*;
 
 public class DBUtil {
   //其中mysql是數(shù)據庫名稱,在mysql57版本的數(shù)據庫中已經預先新建完成;3306是mysql數(shù)據庫的端口號。
   private static String url="jdbc:mysql://localhost:3306/mysql";
   //com.mysql.jdbc.Driver是mysql-connector-java-5.1.40中的驅動包路徑
   private static String driverClass="com.mysql.jdbc.Driver";
   //mysql的賬號和密碼是在安裝mysql中進行設置的,這里拿來用即可。
   private static String username="root";
   private static String password="123456";
   private static Connection conn;
   //裝載驅動
   static{
     try{
       Class.forName(driverClass);
     }
     catch(ClassNotFoundException e){
       e.printStackTrace();
     }
   }
   //獲取數(shù)據庫連接
   public static Connection getConnection(){
     try{
       conn=DriverManager.getConnection(url,username,password);
     }
     catch(SQLException e){
       e.printStackTrace();
     }
     return conn;
   }
   //建立數(shù)據庫連接
   public static void main(String[] args){
     Connection conn=DBUtil.getConnection();
     if(conn!=null){
       System.out.println("數(shù)據庫連接成功");
     }
     else{
       System.out.println("數(shù)據庫連接失敗");
     }
   }
   //關閉數(shù)據庫連接
   public static void Close(){
     if(conn!=null){
       try{
         conn.close();
       }
       catch(SQLException e){
         e.printStackTrace();
       }
     }
   }
 }

d、運行服務器,測試是否成功搭建。

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互

3、Android部分開發(fā)

僅附上核心部分代碼,如下:

 public void SendByHttpClient(final String id, final String pw){ 
     new Thread(new Runnable() { 
       @Override 
       public void run() { 
         try { 
           HttpClient httpclient=new DefaultHttpClient(); 
           HttpPost httpPost=new HttpPost("http://web應用部署服務器上的IP地址:/HttpClientDemo/Login");//服務器地址,指向Servlet 
           List<NameValuePair> params=new ArrayList<NameValuePair>();//將id和pw裝入list 
           params.add(new BasicNameValuePair("ID",id)); 
           params.add(new BasicNameValuePair("PW",pw)); 
           final UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");//以UTF-8格式發(fā)送 
           httpPost.setEntity(entity); 
           HttpResponse httpResponse= httpclient.execute(httpPost); 
           if(httpResponse.getStatusLine().getStatusCode()==200)//在200毫秒之內接收到返回值 
           { 
             HttpEntity entity=httpResponse.getEntity(); 
             String response=EntityUtils.toString(entity1, "utf-8");//以UTF-8格式解析 
             Message message=new Message(); 
             message.what=USER_LOGIN; 
             message.obj=response; 
             handler.sendMessage(message);使用Message傳遞消息給線程 
           } 
         } 
         catch (Exception e) { 
           e.printStackTrace(); 
         } 
       } 
     }).start(); 
   } 

看完上述內容,你們掌握Android應用中怎么與Apache Tomcat服務器實現(xiàn)數(shù)據交互的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI