一、Eclipse创建Dynamic Web Project工程
1、File——new File——写入工程名——Target runtime下面选折Apache tomcat v8.0 并点选右边New Runtime...按钮将你解压tomcat导入,tomcat下有需要用到的第三方工具包servlet
2、点击next——并在Content directory下面的单选框打勾,是为了Web-INF下创建web.xml 用于注册映射相关的Java服务类
3、在WEB-INF下面创建个classes文件夹,单击项目名我这里是LoginTest下拉菜单中点选Properties,在弹出的对话框左边点选Java Build Path 在对话框右边第一栏Source最下面的Default output folder 下的输入框将你创建WEB-INF/classes的path路径写入输入框后,(WEB-INF/classes的路径怎么获取了,点击classes右键下拉菜单Properties弹出对话框将path路径复制,第一个“/”需去掉),中点击finish
这样一个Web项目框架就建好了
当然你也可以手动创建Web工程框架,WEB-INF以及其下web.xml文件这个必须有,同时要引入一个servlet-api.jar第三方包,找不到可以到tomcat的lib目录下去找
二、接下来写服务器端Servlet小应用服务类
1、src下建个包并新建一个类继承于HttpServlet
写出你需要请求响应方法"doGet()"或者"doPost()"的方法,写出相应的逻辑代码:具体代码如下
<span style="font-size:14px;">import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/**指明发送给接收者的实体正文的媒体类型和编码方式*/
resp.setContentType("text/html;charset=utf-8"); // 解决响应请求中文乱码
String userName = req.getParameter("user");
String passWord = req.getParameter("psw");
System.out.println("doGet userName :"+userName+ " passWord :"+passWord);
/**乱码解决方法一*/
// String user_Name = new String(userName.getBytes("ISO-8859-1"),"UTF-8");
// System.out.println("doGet user_Name :"+user_Name+ " passWord :"+passWord);
PrintWriter writer = resp.getWriter();
if(userName.equals("admin")){
writer.print("<html><body><h1>"+userName+"登录成功 </h1></body></html>");
}else{
writer.print("<html><body><h1>"+userName+"登录失败 </h1></body></html>");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doPost >>>>>");
doGet(req, resp);
}
}</span>
<span style="font-size:14px;">import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PrintServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("请求成功!");
}
}</span>
2、并在web.xml文件中写出映射查找关系,具体代码如下
<span style="font-size:14px;"><?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.scxh.java1503.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>PrintServlet</servlet-name>
<servlet-class>com.scxh.java1503.PrintServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>PrintServlet</servlet-name>
<url-pattern>/print</url-pattern>
</servlet-mapping>
</web-app></span>
3、在tomcat解压包中找到conf文件夹找到server.xml文件打开,在<Host></Host>之间假如这段代码
<Context path="/app" docBase="F:\WORK\Developer\WORKSPACE\androidExercise\LoginTest\Login"/>
path自定义取名,docBase是指WEB-INF的上级目录绝对路径,这样映射到webapps/Root/目录下了,而不需要没修改就得复制粘贴到该目下,当然最终修改完成还是需要复制粘贴到该目下,这样做只是为了调试方便。
这样服务端的所有准备工作映射关系就准备完毕
三、Android客户端请求服务端程序代码
1、建xml布局
2、activty类实现点击事件注意监听注册,网络连接,当然需要注意网络耗时操作要在子线程中或异步任务AsyncTask中去完成,请求的URL地址不能写错否则报错
具体代码如下
分别实现请求链接
GET请求方法
Post请求方法
<span style="font-size:14px;">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.scxh.android1503.R;
import com.scxh.android1503.util.Logs;
public class HttpConnectActivity extends Activity implements OnClickListener{
private Button mConnectBtn,mGetConnetBtn,mPostConnetBtn;
private TextView mShowMessageTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http_connect_layout);
mConnectBtn = (Button) findViewById(R.id.http_connect_btn);
mShowMessageTxt = (TextView) findViewById(R.id.http_show_message_txt);
mGetConnetBtn = (Button) findViewById(R.id.http_connect_get_btn);
mPostConnetBtn = (Button) findViewById(R.id.http_connect_post_btn);
mConnectBtn.setOnClickListener(this);
mGetConnetBtn.setOnClickListener(this);
mPostConnetBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
/**建立网络连接*/
case R.id.http_connect_btn:
String httpUrl = "http://192.168.1.156/app/print";
/**异步类解决网络操作不能在主线程*/
new AsyncTask<String, Void, String>(){
@Override
protected String doInBackground(String... params) {
String httpUrl = params[0];
try {
URL url = new URL(httpUrl);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("GET");
connect.connect();
String str = "";
int statusCode = connect.getResponseCode();
Logs.v("statusCode :"+statusCode);
if(statusCode == 200){
str = readStr(connect.getInputStream());
}
return str;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}
}.execute(httpUrl);
break;
case R.id.http_connect_get_btn:
/**GET请求方法*/
httpUrl = "http://192.168.1.156/app/login"; http://192.168.1.156/app/login?user=xiaoming&psw=abcd"
String userName = "张三";
try {
userName = URLEncoder.encode(userName, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpUrl = httpUrl + "?user="+userName+"&psw=abcd&sex=男";
Logs.v("httpUrl :"+httpUrl);
/**异步类解决网络操作不能在主线程*/
new AsyncTask<String, Void, String>(){
@Override
protected String doInBackground(String... params) {
String httpUrl = params[0];
try {
URL url = new URL(httpUrl);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("GET");
connect.connect();
String str = readStr(connect.getInputStream());
return str;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}
}.execute(httpUrl);
break;
case R.id.http_connect_post_btn:
/**POST请求方法*/
httpUrl = "http://192.168.1.156/app/login";
/**异步类解决网络操作不能在主线程*/
new AsyncTask<String, Void, String>(){
@Override
protected String doInBackground(String... params) {
Logs.v("doInBackground >>>>>");
String httpUrl = params[0];
try {
URL url = new URL(httpUrl);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.connect();
OutputStream os = connect.getOutputStream();
PrintWriter writer = new PrintWriter(os);
writer.print("user=张三&psw=123456");
writer.flush();
String str = readStr(connect.getInputStream());
connect.disconnect();
return str;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}
}.execute(httpUrl);
break;
}
}
/**
* 从输入流读数据
* @param is
* @return
* @throws IOException
*/
public String readStr(InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line=reader.readLine()) != null){
sb.append(line);
}
reader.close();
is.close();
return sb.toString();
}
public String getHttpConnect(String httpUrl){
try {
/**Get请求传参方式*/
httpUrl = httpUrl +"?user=admin&psw=abcd"; //http://192.168.1.156/app/login?user=xiaoming&psw=abcd"
URL url = new URL(httpUrl); //统一资源定位符
HttpURLConnection connet = (HttpURLConnection) url.openConnection(); //打开Http连接
connet.setRequestMethod("GET"); //设置 http请求方式
connet.setConnectTimeout(15000); //设置http连接超时时间
connet.setReadTimeout(10000); //设置读数据超时时间
connet.connect(); //建立连接
/**post传参实现方式 :
* 向字节输出流中写数据 */
/*OutputStream os = connet.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.print("user=xiaoming&psw=abcd");
pw.flush();*/
InputStream is = connet.getInputStream(); //得到字节输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); //得到字符输入缓冲流
/**从字符输入缓冲流中一行一行读取数据
* 添加到StringBuilder */
String line;
StringBuilder sb = new StringBuilder();
while((line = reader.readLine())!=null){
sb.append(line);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**Apache建立连接的方法*/
public void httpClientConnet(){
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://192.168.1.156/app/login?user=xiaoming&psw=abcd");
try {
HttpResponse response = client.execute(request);
InputStream is = response.getEntity().getContent();
//String str = readStr(is);
String str = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}</span>