1. 程式人生 > >android + tomcat + eclipse實現登入

android + tomcat + eclipse實現登入

客戶端開發平臺:Android studio( sdk版本26 ,模擬器 Android7.0
伺服器開發平臺:eclipse+tomcat
*

服務端

1.新建名為login_server的動態web專案(注意勾選自動新增web.xml配置檔案)
2.在專案Java目錄中新建包:main
3.在包main下新建名為Login的servlet
4.然後寫新增程式碼:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;

public Login() {
        }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	    response.setContentType("text/html");
	    response.setCharacterEncoding("utf-8");
	    PrintWriter out = response.getWriter();
	    String loginName = request.getParameter("name");
	    String loginPwd = request.getParameter("pwd");
	    if(loginName.equals("1")&&loginPwd.equals("1")) {
	    	System.out.println("success in Server ");
	    	out.print(true);
           // request.getRequestDispatcher("success.html").forward(request, response);
	    }else {
	    	out.print(false);
	    }
	}
}

在web.xml配置檔案中寫上如下程式碼:

<?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  
  <display-name>fleaMarket</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>main.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
</web-app>

5.再webContent目錄下新增名為index的html檔案,新增如下程式碼

 <body>
<form action="Login" method="post">
   	<table align="center">
		<tr>
			<td>user:</td>
			<td><input type="text" name="name"></td>
		</tr>
		<tr>
			<td>password:</td>
			<td><input type="text" name="pwd"></td>
		</tr>
		<tr>
		<tr>
			<td>submit</td>
			<td><input type="submit"></td>
		</tr>
	</table>
客戶端程式碼:

1.在android studio上新建一個名為fleaMarket專案
2.新建Java類LoginServer,程式碼如下:

public class LoginToServer {
private String result;
private Boolean isConnect = false;
private String url = "http://192.168.43.3:8080/fleaMarket/Login";//連線伺服器的地址,千萬別弄錯了
private OkHttpClient okHttpClient = new OkHttpClient();
public String doPost(String name,String pwd) throws IOException{
    RequestBody formBody = new FormBody.Builder()
            .add("name",name)
            .add("pwd",pwd)
            .build();
    final Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();
    Response response;
    try{
        response = okHttpClient.newCall(request).execute();
        Log.d("loginToServer",String.valueOf(response.isSuccessful()));
        if (response.isSuccessful()){
           isConnect = true;
        }
        if(isConnect){
            result = response.body().string();
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    return result;
}

}
3.在主活動MainActivity的程式碼如下:
public class MainActivity extends AppCompatActivity {

private EditText name;
private EditText pwd;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initail();
    button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            final Handler myHandler = new Handler(){
                public void handleMessage(Message msg){
                    String responseResult = (String)msg.obj;
                    if(responseResult.equals("true")){
                        Toast.makeText(MainActivity.this,"登入成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(MainActivity.this,"登入失敗",Toast.LENGTH_SHORT).show();
                    }
                }
            };
            new Thread(new Runnable() {
                @Override
                public void run() {
                    LoginToServer loginToServer = new LoginToServer();
                    try{
                        String result = loginToServer.doPost(name.getText().toString().trim(),pwd.getText().toString().trim());
                        Message message = new Message();
                        message.obj = result;
                        Log.d("Main result",result);
                        myHandler.sendMessage(message);
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    });
}
public void initail(){
    name = (EditText)findViewById(R.id.name);
    pwd = (EditText)findViewById(R.id.password);
    button = (Button)findViewById(R.id.login);
}

}
5.主活動的佈局檔案程式碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" 
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:hint="姓名"/>
<EditText
    android:id="@+id/password"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:hint="密碼"
    android:inputType="textPassword"/>
<Button
    android:id="@+id/login"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="登入"
    android:textSize="26sp"
    android:textColor="#000"/>
6.在AndroidManifest .xml中新增許可權:
<uses-permission android:name="android.permission.INTERNET"/>

補充:
1.先在tomcat上啟動index.html
2.然後在客戶端啟動Android專案後就可以連線伺服器了!
3.在eclipse下的console中可以看到來自客戶端的請求