一.移動客服端實現對PC端數據的操作 在PC端模擬一個資料庫,實現用戶的增刪改查,然後在移動客服端實現對PC端資料庫的操作 在PC端建立三個表 用戶表(Users),員工表(Emp), 部門表(Dept), User表對應欄位,並設置對應的set/get方法,這裡不一一寫出 Emp表對應欄位 Dep ...
一.移動客服端實現對PC端數據的操作
在PC端模擬一個資料庫,實現用戶的增刪改查,然後在移動客服端實現對PC端資料庫的操作
在PC端建立三個表
用戶表(Users),員工表(Emp), 部門表(Dept),
User表對應欄位,並設置對應的set/get方法,這裡不一一寫出
private int uno; private String uname; private String upwd;
Emp表對應欄位
private int eno; private String ename; private int eage; private String esex; private Date eintime;
Dept表對應欄位
private int dno; private String dname;
對資料庫的模擬操作:
pc端代碼:
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; 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 com.entity.Users; import com.google.gson.Gson; /** * 處理Users相關請求的控制類 */ @WebServlet("/UserServlet") public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; //定義一個集合,初始化一些用戶 private List<Users> userList; public UserServlet() { super(); userList=new ArrayList<Users>(); userList.add(new Users(1, "admins", "admins")); userList.add(new Users(2, "jack", "000000")); userList.add(new Users(3, "lucy", "000000")); userList.add(new Users(4, "toms", "000000")); userList.add(new Users(5, "join", "000000")); } //所有來到UserServlet的請求都將進入service中進行分發 @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); //獲取用戶要請求的方法 String method=request.getParameter("method"); switch(method){ case "login": doLogin(request, response); break; case "register": doRegister(request, response); break; case "userList": doFindUserList(request, response); break; case "userById": doFindUserById(request, response); break; case "updateUser": doUpdateUser(request, response); break; case "deleteUser": doDeleteUser(request, response); break; } } //用戶登錄 protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收用戶傳遞的參數 String name=request.getParameter("uname"); String pwd=request.getParameter("upwd"); PrintWriter out=response.getWriter(); for (Users users : userList) { if(users.getUname().equals(name)&&users.getUpwd().equals(pwd)){ out.println("用戶登錄成功"); return; } } out.print("用戶名和密碼錯誤"); out.close(); } //添加用戶 protected void doRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("----------進入添加用戶操作----------"); //接收用戶傳遞的參數 String name=request.getParameter("uname"); String pwd=request.getParameter("upwd"); //將信息封裝成一個Users對象 userList.add(new Users(userList.size()+1, name, pwd)); PrintWriter out=response.getWriter(); out.println("用戶"+name+"添加成功"); out.close(); } //查詢所有用戶 protected void doFindUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); //將所有用戶以JSON格式響應到客戶端 out.println(new Gson().toJson(userList)); out.close(); } //根據Id查詢單個用戶 protected void doFindUserById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); //取出ID int id=Integer.parseInt(request.getParameter("uno")); for (Users users : userList) { if(users.getUno()==id){ out.println(new Gson().toJson(users)); return; } } out.close(); } //修改用戶 protected void doUpdateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id=Integer.parseInt(request.getParameter("uno")); String name=request.getParameter("uname"); String pwd=request.getParameter("upwd"); PrintWriter out=response.getWriter(); for (Users users : userList) { if(users.getUno()==id){ users.setUname(name); users.setUpwd(pwd); out.println(new Gson().toJson("修改用戶成功")); return; } } out.println(new Gson().toJson("修改用戶失敗")); out.close(); } //刪除用戶 protected void doDeleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id=Integer.parseInt(request.getParameter("uno")); PrintWriter out=response.getWriter(); for (Users users : userList) { if(users.getUno()==id){ userList.remove(users); out.println(new Gson().toJson("刪除用戶成功")); return; } } out.println(new Gson().toJson("刪除用戶失敗")); out.close(); } }
HTML頁面 :
用戶登錄代碼:<a href="http://localhost:8080/Web_Project/UserServlet?method=login&uname=xiaolin&upwd=000000">用戶登錄</a><br/><br/>,傳參其他的相同
PC端對數據的操作完成。
手機客服端代碼:
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.example.utils.CallBack; import com.example.utils.FileUtils; import com.example.utils.HttpUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //用戶登錄(自帶模擬器:10.0.2.2,Genymotion:本地IP) public void doLogin(View view){ new Thread(new Runnable() { @Override public void run() { try {
//192.168.3.183需要改成你的本地IP地址,下麵的都需要改成你本地的IP地址 URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet?method=login&uname=xiaolin&upwd=000000"); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.connect(); //獲取結果 InputStream input=conn.getInputStream(); final String result= FileUtils.formatStreamToString(input); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //添加用戶 public void doRegister(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet"); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//以POST方式傳值 conn.setDoOutput(true);//允許向伺服器傳遞參數,預設false conn.connect(); //向伺服器傳遞數據java.net.URLEncoder.encode("","utf-8"); String data="method=register&uname=xiaolin&upwd=123456"; OutputStream out=conn.getOutputStream(); out.write(data.getBytes()); out.close(); //獲取結果 InputStream input=conn.getInputStream(); final String result= FileUtils.formatStreamToString(input); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //查詢所有用戶 public void doFindUserList(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet?method=userList"); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.connect(); //直接將返回的流轉換為一個字元串 String result=FileUtils.formatStreamToString(conn.getInputStream()); //如何解析一個JSON字元串 final JSONArray array=new JSONArray(result); runOnUiThread(new Runnable() { @Override public void run() { for(int i=0;i<array.length();i++){ try { JSONObject obj=array.getJSONObject(i); String msg="用戶名:"+obj.getString("uname")+",密碼:"+obj.getString("upwd"); Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //查詢單個用戶 public void doFindUserById(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet?method=userById&uno=1"); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.connect(); //直接將返回的流轉換為一個字元串 String result=FileUtils.formatStreamToString(conn.getInputStream()); //如何解析一個JSON字元串 final JSONObject obj=new JSONObject(result); runOnUiThread(new Runnable() { @Override public void run() { String msg= null; try { msg = "用戶名:"+obj.getString("uname")+",密碼:"+obj.getString("upwd"); Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //更新用戶 public void doUpdateUser(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet"); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//以POST方式傳值 conn.setDoOutput(true);//允許向伺服器傳遞參數,預設false conn.connect(); //向伺服器傳遞數據java.net.URLEncoder.encode("","utf-8"); String data="method=updateUser&uno=6&uname=xiaolin&upwd=111111"; OutputStream out=conn.getOutputStream(); out.write(data.getBytes()); out.close(); //獲取結果 InputStream input=conn.getInputStream(); final String result= FileUtils.formatStreamToString(input); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(),result.toString(), Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //刪除用戶 public void doDeleteUser(View view){ try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet"); String data="method=deleteUser&uno=6"; HttpUtils.doPost(url, data, new CallBack() { @Override public void success(final String str) { runOnUI(str); } @Override public void failed(final String str) { runOnUI(str); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } public void addEmp(View view){ try { URL url=new URL("http://192.168.3.183:8080/Web_Project/EmpServlet"); String data="method=addEmp&ename=小明&eage=21&esex=男&eintime=2017-7-8&dno=1"; HttpUtils.doPost(url, data, new CallBack() { @Override public void success(final String str) { runOnUI(str); } @Override public void failed(final String str) { runOnUI(str); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } public void findEmpList(View view){ try { URL url=new URL("http://192.168.3.183:8080/Web_Project/EmpServlet?method=empList"); HttpUtils.doGet(url,null, new CallBack() { @Override public void success(final String str) { try { final JSONArray array=new JSONArray(str); for(int i=0;i<array.length();i++){ JSONObject obj=array.getJSONObject(i); JSONObject dept=obj.getJSONObject("dept"); String empInfo="員工姓名"+obj.getString("ename")+",部門:"+dept.getString("dname"); runOnUI(empInfo); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void failed(final String str) { runOnUI("查詢失敗"); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } private void runOnUI(final String str){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(),str, Toast.LENGTH_SHORT).show(); } }); } }
工具類:
FileUtils
public class FileUtils { //將一個輸入流轉換為一個字元串 public static String formatStreamToString(InputStream stream){ if(stream!=null){ ByteArrayOutputStream out=new ByteArrayOutputStream(); byte[] bytes=new byte[1024]; int len=0; try { while((len=stream.read(bytes))!=-1){ out.write(bytes,0,len); } String str=out.toString(); out.flush(); out.close(); stream.close(); return str; } catch (IOException e) { e.printStackTrace(); } } return null; } //執行下載文件到指定位置 public static void downLoadFile(final String fromPath, final String savePath, final CallBack callBack){ if(fromPath!=null&&savePath!=null){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL(fromPath); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20*1000); conn.connect(); InputStream input=conn.getInputStream(); File file=new File(savePath); if(!file.getParentFile().exists()) file.getParentFile().mkdirs(); OutputStream out=new FileOutputStream(file); byte[] bytes=new byte[1024]; for(int len=0;(len=input.read(bytes))!=-1;){ out.write(bytes,0,len); } out.flush(); out.close(); input.close(); callBack.success(null);//下載成功 } catch (Exception e) { e.printStackTrace(); callBack.failed(null);//下載失敗 } } }).start(); } } public static boolean existsFile(String path){ if(path!=null&&path.length()>0) { File file = new File(path); if(file.exists()) return true; } return false; } }
HttpUtils
public class HttpUtils { public static void doPost(final URL url, final String data, final CallBack callBack){ new Thread(new Runnable() { @Override public void run() { try { HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(10*1000); conn.setDoOutput(true); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.connect(); if(data!=null&&data.length()>0){ OutputStream out=conn.getOutputStream(); out.write(data.getBytes()); out.close(); } callBack.success(FileUtils.formatStreamToString(conn.getInputStream())); } catch (IOException e) { e.printStackTrace(); callBack.failed("操作出錯"); } } }).start(); } public static void doGet(final URL url,final String data,final CallBack callBack){ new Thread(new Runnable() { @Override public void run() { try { HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10*1000); conn.setDoOutput(true); conn.setInstanceFollowRedirects(true); conn.connect(); if(data!=null&&data.length()>0){ OutputStream out=conn.getOutputStream(); out.write(data.getBytes()); out.close(); } callBack.success(FileUtils.formatStreamToString(conn.getInputStream())); } catch (IOException e) { e.printStackTrace(); callBack.failed("操作出錯"); } } }).start(); } }
CallBack
public interface CallBack { public void success(String str); public void failed(String str); }
界面:
手機客服端代碼完成。