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中可以看到来自客户端的请求

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值