用博客记录点滴……

java 通过HttpURLConnection与servlet通信

研究了一天才搞清楚,其实挺简单的,在这里记录下,以便以后参考。

一、创建一个servlet项目

 

主要包括(WEB-INF)里面有classes文件夹、lib文件夹、web.xml文件。

将写好的servlet类编译成的.class放到项目中的classes文件夹下(我的是helloServlet.class)

1、在web.xml中配置

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5"> 
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>helloServlet</servlet-class><!-路径加名称,如果是在classes中的myclass中则用:myclass/helloServlet。如果是lib中的.jar包则用com.gis.arcgisengine.ServiceContext的形式->
    </servlet>     
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern><!-通过url访问的别名,实际上就是对helloServlet.class的访问,前面的/不能少->
    </servlet-mapping>
    
</web-app>

2、helloServlet文件(是servlet类)

 

import java.io.IOException;
import java.io.PrintWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class helloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L; 
    public helloServlet() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //overwrite        
        String[] myName = null;
        response.setContentType("application/octet-stream");
        try {
            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
            Object obj = ois.readObject();//读取输入对象(传过来的流对象)
            ois.close();
            myName = (String[])obj;
            for(int i=0;i<myName.length;i++){
                System.out.println(myName[i]);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        String name = request.getParameter("name");
        ServletOutputStream out = response.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(name);//写入输出对象(返回给调用函数)
        oos.close();
        out.close();
        
        /*String name = request.getParameter("name");
        if(name != null){
            name = new String(name.getBytes("ISO-8859-1"),"GB2312");
        }else{
            name = "默认值";
        }
        response.setContentType("text/html;charset=GB2312");
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("<h1>"+name+":你好</h1>");
        out.println("  </BODY>");
        out.println("</HTML>");
        System.out.println(name);
        out.flush();
        out.close();*/
    }

    public void init() throws ServletException {
        // Put your code here
    }

}

 

二、创建普通项目并调用servlet项目中的helloServlet.class中的方法

1、项目中创建普通类

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class webtest {
     public static void myFun(){
         try{
         String[] arr = {"aaa","bbb","ccc","ddd"};     
         String tempGisEngineUrl = "http://sun:8080/helloapp/hello?name=中国";//hello是在servlet项目中web.xml中配置的url访问别名。
         URL imsServerURL = new URL(tempGisEngineUrl);
         HttpURLConnection imsConnection = (HttpURLConnection) imsServerURL
                    .openConnection();
         imsConnection.setDoInput(true);
         imsConnection.setDoOutput(true);
         imsConnection.setUseCaches(false);
         imsConnection.setDefaultUseCaches(false);
         imsConnection.setRequestProperty("Content-Type",
                    "application/octet-stream");
         ObjectOutputStream oos = new ObjectOutputStream(imsConnection
                    .getOutputStream());
         oos.writeObject(arr);//写入输出对象
         oos.flush();
         oos.close();
         ObjectInputStream ois = new ObjectInputStream(imsConnection
                    .getInputStream());
         String oResult = (String)ois.readObject();//读取输入对象
         ois.close();
         imsConnection.disconnect();
         System.out.println("from servlet:"+oResult);//将读取到的输入对象进行转换后打印到后台
         }catch(Exception ex){
             System.out.println(ex.getMessage());
         }
     }
     
     public static void main(String[] args){
         myFun();
     }
}

 

三、运行结果:

1、在servlet端输出:

aaa  

bbb

ccc

ddd

2、在调用端输出:from servlet:中国

注意:

实现service方法。 

    Servlet的主要功能是接受从浏览器发送过来的HTTP请求(request),并返回HTTP响应(response)。这个工作是在service方法中完成的。service方法包括从request对象获得客户端数据和向response对象创建输出。 

    如果一个Servlet从javax.servlet.http.HttpServlet继承,实现了doPost或doGet方法,那么这个Servlet只能对POST或GET做出响应。如果开发人员想处理所有类型的请求(request),只要简单地实现service方法即可(但假如选择实现service方法,则不必实现doPost或doGet方法,除非在service方法的开始调用super.service())。

posted @ 2015-06-04 10:29  aegisada  阅读(1310)  评论(0编辑  收藏  举报