用手机访问web应用的demo,整体思路是:
1、通过手机访问web应用,并向服务器发送信息。
2、服务器接收客户端信息。
3、服务器处理数据(解析xml文件)。
4、重组信息,返回给客户端。
一、服务器代码
首先,建立一个web工程:Test1
然后新建一个servlet,用于手机客户端调用。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ServletDemo extends HttpServlet { /** * Constructor of the object. */ public ServletDemo() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //获得客户端发送的数据 ServletInputStream is = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String requestString = reader.readLine(); //向客户端返回数据 String responseString = processStringRequest(requestString,request); ServletOutputStream os = response.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write(responseString); //关闭资源 writer.flush(); writer.close(); reader.close(); os.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occure */ public void init() throws ServletException { } private String processStringRequest(String requestString,HttpServletRequest request){ List list = this.toRead(request.getRealPath("/")+"user.xml"); String response = ""; if(null != list && list.size() > 0){ for(int i = 0 ; i < list.size(); i++){ JavaBean a = (JavaBean)list.get(i); response += "client say:"+requestString+"server say: this is your info:"+a.getName()+"@"+a.getSex()+"@"+a.getAge(); System.out.println(a.getName()); } }else{ response = "is wrong!"; } return response; } public List toRead(String filename) { List alist = new ArrayList(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(filename); NodeList employees = document.getChildNodes(); for (int i = 0; i < employees.getLength(); i++) { Node employee = employees.item(i); NodeList employeeInfo = employee.getChildNodes(); for (int j = 0; j < employeeInfo.getLength(); j++) { Node node = employeeInfo.item(j); NodeList employeeMeta = node.getChildNodes(); JavaBean bean = new JavaBean(); boolean status = false; for (int k = 0; k < employeeMeta.getLength(); k++) { if(employeeMeta.item(k).getNodeName().equals("name")){ bean.setName(employeeMeta.item(k).getTextContent()); } if(employeeMeta.item(k).getNodeName().equals("age")){ bean.setAge(employeeMeta.item(k).getTextContent()); } if(employeeMeta.item(k).getNodeName().equals("sex")){ bean.setSex(employeeMeta.item(k).getTextContent()); } status = true; } if(status){ alist.add(bean); } } } } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } return alist; } }
web工程的web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>ServletDemo</servlet-name> <servlet-class>ServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletDemo</servlet-name> <url-pattern>/servlet/ServletDemo</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
xml文件格式
<?xml version="1.0" encoding="GB2312" standalone="no"?> <employees> <employee> <name>user0</name> <sex>m</sex> <age>30</age> </employee> </employees>
解析xml文件用到的javabean:
public class JavaBean { private String name; private String sex; private String age; public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
二,客户端代码
1、新建Android工程
2、修改main。xml文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:layout_height="wrap_content" android:id="@+id/address" android:layout_width="fill_parent" android:text="http://192.168.1.111:8089/Test1/servlet/ServletDemo" > </EditText> <Button android:id="@+id/ButtonGo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="go!" > </Button> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:textColor="#000000" android:id="@+id/pagetext" /> </LinearLayout>
3、添加关键代码
import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.TextView; import android.util.Log; import android.view.View; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; public class ClientDemo extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView tView = (TextView) findViewById(R.id.pagetext); final Button button = (Button) findViewById(R.id.ButtonGo); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { String response_string = ""; boolean out = true; boolean in = true; try { System.out.println("ty"+tView.getText().toString()); URL url = new URL("http://192.168.1.111:8089/Test1/servlet/ServletDemo"); URLConnection connection = url.openConnection(); connection.setDoInput(in); connection.setDoOutput(out); BufferedWriter writer = null; //向服务器发送数据 if(out){ writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); writer.write("I am clent request!!"); writer.flush(); } //接受服务器返回的数据 BufferedReader reader = null; if(in){ reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response_string = reader.readLine(); System.out.println("response: "+response_string); Log.v("test", response_string); tView.setText(response_string); } if(writer != null){ writer.close(); } if(reader != null){ reader.close(); } } catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); } } }); } }
1、程序启动2、发送请求后
小结。
1、整个demo比较简单,但我们又接触到了新知识,这里面需要注意的是,服务器的ip地址要用实际地址 上篇已经说明了原因。
2、整个步骤比较简单,首先客户端创建连接,然后发送消息,最后接收消息,服务器同理。