当前位置:文档之家› Tomcat 上如何部署Servlet及Android中如何与服务器通信

Tomcat 上如何部署Servlet及Android中如何与服务器通信

Tomcat 上如何部署Servlet及Android中如何与服务器通信

下载Tomcat并安装

Apache Tomcat powers numerous large-scale, mission-critical web applications across a diverse range of industries and organizations. Some of these users and their stories are listed on the PoweredBy wiki page. Apache Tomcat, Tomcat, Apache, the Apache feather, and the Apache Tomcat project logo are trademarks of the Apache Software Foundation.

I add this English description due to junk baidu wenku`s rules

Eclipse中编写Servlet代码:创建java工程

package com.webservice.test;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

public class WebserviceTest extends HttpServlet {

private static final long serialVersionUID = 512;

private List list;

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

doGet(req, response);

}

protected void doGet(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{

response.setContentType("test/plain");

response.setCharacterEncoding("UTF-8");

PrintWriter outPrintWriter = response.getWriter();

JSONArray jsonArray = new JSONArray();

list = initData();

for(Student bean:list) {

JSONObject jsonObject = new JSONObject();

try{

jsonObject.put("stunum", bean.getStunum());

jsonObject.put("name",bean.getName());

jsonObject.put("chinese", bean.getChinese());

jsonObject.put("math", bean.getMath());

jsonObject.put("english", bean.getEnglish());

}catch (Exception e) {

e.printStackTrace();

}

jsonArray.put(jsonObject);

}

outPrintWriter.write(jsonArray.toString());

outPrintWriter.flush();

outPrintWriter.close();

}

private List initData(){

List studentlist= new ArrayList();

Student stuOne = new Student();

stuOne.setStunum(10001);

stuOne.setName("sloden");

stuOne.setChinese(82);

stuOne.setMath(88);

stuOne.setEnglish(80);

studentlist.add(stuOne);

Student stuTwo = new Student();

stuTwo.setStunum(10002);

stuTwo.setName("candy");

stuTwo.setChinese(81);

stuTwo.setMath(87);

stuTwo.setEnglish(80);

studentlist.add(stuTwo);

Student stuThree = new Student();

stuThree.setStunum(10003);

stuThree.setName("tenny");

stuThree.setChinese(89);

stuThree.setMath(85);

stuThree.setEnglish(89);

studentlist.add(stuThree);

return studentlist;

}

/*public static void main(String[] args){

}*/

}

class Student{

private int stunum;

private String name;

private int chinese;

private int math;

private int english;

public int getStunum() {

return stunum;

}

public void setStunum(int stunum) {

this.stunum = stunum;

}

public String getName() {

return name;

}

public void setName(String name) {

https://www.doczj.com/doc/ab6300847.html, = name;

}

public int getChinese() {

return chinese;

}

public void setChinese(int chinese) {

this.chinese = chinese;

}

public int getMath() {

return math;

}

public void setMath(int math) {

this.math = math;

}

public int getEnglish() {

return english;

}

public void setEnglish(int english) {

this.english = english;

}

}

代码中用到了HttpServlet ,JSONArray ,JSONObject 类,需要导入jar包,HttpServlet可以从TomCat\lib\servlet-api.jar,JSONArray ,JSONObject 需要导入

json-lib-1.1-jdk13.jar包,eclipse中可以在项目名称上右键选择properties,现在java build path ,然后选择Libraries,点击Add External JARs,选择jar包

代码编写好后,在项目下面bin中会生成对应的class文件:

这些class文件最后都是要部署到Tomcat中去的,包括包名文件夹,比如:com/webservice/test 这些目录都是要拷贝进去的。

Tomcat中配置:

在Tomcat的webapp中新建工程文件夹,命名为“server-test”,然后在server-test中新建文件夹“WEB-INF”,在“WEB-INF”文件夹中新建文件夹“classes”,用于存放工程的class 文件。在在“WEB-INF”文件夹中新建文件web.xml,内容如下:

xmlns:xsi="https://www.doczj.com/doc/ab6300847.html,/2001/XMLSchema-instance"

xsi:schemaLocation="https://www.doczj.com/doc/ab6300847.html,/xml/ns/javaee

https://www.doczj.com/doc/ab6300847.html,/xml/ns/javaee/web-app_3_0.xsd"

version="3.0"

metadata-complete="true">

Tomcat Manager Application

A scriptable management web application for the Tomcat Web Server;

Manager lets you view, load/unload/etc particular web applications.

test

com.webservice.test.WebserviceTest

test

/test

将编译生成的class 文件放到项目中的WEB-INF目录中的classes目录下,启动Tomcat:

然后在浏览器中输入:http://localhost:8080/server-test/test

如果出现如下问题:

出现这样的问题,需要再环境变量中导入jar包,在我做实验的过程中导入了如下几个包:commons-beanutils.jar、commons-logging.jar、ezmorph-1.0.2.jar、commons-lang-2.1.jar、

json-lib-1.1-jdk13.jar、servlet-api.jar,其中除了servlet-api.jar包外,其他jar包可以从网上下载,servlet-api.jar可以从Tomcat中lib文件夹中得到:

配置好后再浏览器中输入:http://localhost:8080/server-test/test,就好出现如下界面:

下载文件,用UltraEdit 打开,可以看到如下内容:

[{"math":88,"stunum":10001,"name":"sloden","english":80,"chinese":82},{"math":87,"stunum":1

0002,"name":"candy","english":80,"chinese":81},{"math":85,"stunum":10003,"name":"tenny","en

glish":89,"chinese":89}]

这个时候Tomcat中的项目就部署好了!

Android中客户端与服务端通信

Android代码如下:

package jiao.jiao;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import https://www.doczj.com/doc/ab6300847.html,ValuePair;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.json.JSONArray;

import org.json.JSONObject;

import android.app.Activity;

import https://www.doczj.com/doc/ab6300847.html,.ConnectivityManager;

import https://www.doczj.com/doc/ab6300847.html,workInfo;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

public class WebClientForAndroidActivity extends Activity { /** Called when the activity is first created. */

public EditText showEditText,queryEditText;

public Button getButton;

public static final String TAG = "client";

public static final int CONNECTMESSAGE_SUCCESS = 10051;

public static final int CONNECTMESSAGE_ERROR = 10052;

public static final int CONNECTMESSAGE_TIMEOUT = 10053;

public StringBuilder stringBuilder;

public Handler handler;

public static final String httpUrl= "http://10.18.49.71:8080/server-test/test";

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(https://www.doczj.com/doc/ab6300847.html,yout.main);

handler = new Handler(){

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

//super.handleMessage(msg);

if (msg.arg1 == CONNECTMESSAGE_SUCCESS) {

if (stringBuilder!=null) {

try {

String jsonString = stringBuilder.toString();

StringBuffer stringBuffer = new StringBuffer();

//JSONArray jsonArray = new JSONArray(jsonString);

JSONArray jsonArray = new JSONArray(jsonString);

//jsonArray.put(jsonString.toString());

//jsonArray.put(jsonString);

for (int i = 0; i < jsonArray.length(); i++) {

JSONObject jsonObject = jsonArray.getJSONObject(i);

stringBuffer.append("---------the "+i+" student info-------");

stringBuffer.append("stunum:").append(jsonObject.getInt("stunum")).a ppend("\n");

stringBuffer.append("name:").append(jsonObject.getString("name")).ap pend("\n");

stringBuffer.append("math:").append(jsonObject.getInt("math")).appen d("\n");

stringBuffer.append("english:").append(jsonObject.getInt("english")) .append("\n");

stringBuffer.append("chinese:").append(jsonObject.getInt("chinese")) .append("\n");

}

showEditText.setText(stringBuffer.toString());

} catch (Exception e) {

e.printStackTrace();

}

}

}

if (msg.arg1 == CONNECTMESSAGE_ERROR) {

showEditText.setText("can not get info for service");

}

}

};

queryEditText = (EditText) this.findViewById(R.id.stunum);

showEditText = (EditText) this.findViewById(https://www.doczj.com/doc/ab6300847.html,);

getButton = (Button) this.findViewById(R.id.getinfo);

getButton.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

new Thread(){

@Override

public void run() {

// TODO Auto-generated method stub

connectService();

}

}.start();

}

});

if (checkNetWork()) {

Log.d(TAG, "---------------------network is ok");

}else {

getButton.setEnabled(false);

}

}

public boolean checkNetWork(){

ConnectivityManager cm = (ConnectivityManager) this

.getSystemService(this.CONNECTIVITY_SERVICE);

NetworkInfo info = cm.getActiveNetworkInfo();

if (info != null && info.isConnected()) {

return true;

} else {

Log.d(TAG, "It's can't connect the Internet!");

return false;

}

}

public void connectService(){

HttpPost request = new HttpPost(httpUrl);

HttpClient httpClient = new DefaultHttpClient();

List params = new ArrayList();

params.add(new

BasicNameValuePair("stunum",queryEditText.getText().toString()));

HttpResponse response;

try {

HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");

request.setEntity(entity);

response = httpClient.execute(request);

int status = response.getStatusLine().getStatusCode();

Log.d(TAG, "---------------status:"+status);

if(status==HttpStatus.SC_OK){

Log.d(TAG, "---------------connected success!!!");

entity = response.getEntity();

if(entity!=null){

BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));

stringBuilder = new StringBuilder();

String infoString =null;

while ((infoString=reader.readLine())!=null) {

stringBuilder= stringBuilder.append(infoString+"\n");

}

reader.close();

Message msgMessage = new Message();

msgMessage.arg1 = CONNECTMESSAGE_SUCCESS;

handler.sendMessage(msgMessage);

}

}else {

Message msgMessage = new Message();

showEditText.setText("connect error!!!");

msgMessage.arg1 = CONNECTMESSAGE_ERROR;

handler.sendMessage(msgMessage);

}

} catch (Exception e) {

e.printStackTrace();

Message msgMessage = new Message();

msgMessage.arg1 = CONNECTMESSAGE_ERROR;

handler.sendMessage(msgMessage);

}

}

}

AndroidManifest.xml文件如下:

package="jiao.jiao"

android:versionCode="1"

android:versionName="1.0">

android:name="android.permission.ACCESS_NETWORK_STATE"/>

android:icon="@drawable/ic_launcher"

android:label="@string/app_name">

android:name=".WebClientForAndroidActivity"

android:label="@string/app_name">

效果如下:

如有问题可以加QQ five-one-five-eight-one-two-eight-one-one

相关主题
文本预览
相关文档 最新文档