Servlet+Tomcat搭建Http服務

1、下載Tomcat

Tomcat官網下載:http://tomcat.apache.org/
要確保TomcatJDK版本對應,此文中採用的是Tomcatv8.0JDK1.7
查看各版本對應:http://tomcat.apache.org/whichversion.html


2、建web項目

打開eclipse
File -> New -> Dynamic Web Project
-> 輸入Project name: MyServlet -> New Runtime… -> Apache Tomcat v8.0
-> Next->Browse -> 選擇Tomcat v8.0安裝目錄 -> 確定 -> Finish
-> Next -> Next -> Generate web.xml…前打鉤 -> Finish


3、建Servlet.java

src下新建package: servletTest
servletTest下新建: ServletServer.java

項目文件如下:

這裏寫圖片描述


4.ServletServer.java

  1. package servletTest;
  2.     
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7.     
  8. import java.io.BufferedReader;
  9. import java.io.IOException;
  10. import java.io.PrintWriter;
  11. import java.net.URLDecoder;
  12.     
  13. public class ServletServer extends HttpServlet {
  14.     
  15.     private static final long serialVersionUID = -8007568372864896315L;
  16.     
  17.     protected void doPost(HttpServletRequest request, HttpServletResponse response)
  18.             throws ServletException, IOException {
  19.         request.setCharacterEncoding("UTF-8");
  20.         response.setContentType("text/html;charset=utf-8");
  21.         PrintWriter out = response.getWriter();
  22.         
  23.         BufferedReader bufferReader = request.getReader();
  24.         StringBuffer buffer = new StringBuffer();
  25.         String line = "";
  26.         while ((line = bufferReader.readLine()) != null) {
  27.             buffer.append(line);
  28.         }
  29.         String postData = buffer.toString();
  30.         postData = URLDecoder.decode(postData, "utf-8");
  31.         String[] params = postData.split("&");
  32.         
  33.         String id = null;
  34.         String name = null;
  35.         
  36.         for (int index = 0; index < params.length; index = index + 1) {
  37.             if (params[index].startsWith("id=")) {
  38.                 id = params[index].substring(params[index].indexOf("id=") + "id=".length());
  39.             }
  40.             if (params[index].startsWith("name=")) {
  41.                 name = params[index].substring(params[index].indexOf("name=") + "name=".length());
  42.             }
  43.         }
  44.         
  45.         if (!((null == id || id.isEmpty()) && (null == name || name.isEmpty()))) {
  46.             String ret = "id" + id + ";name" + name;
  47.             out.print(ret);
  48.             out.flush();
  49.             out.close();
  50.         } else {
  51.             out.print("無數據");
  52.             out.flush();
  53.             out.close();
  54.         }
  55.     }
  56.     
  57.     protected void doGet(HttpServletRequest request, HttpServletResponse response)
  58.             throws ServletException, IOException {
  59.         doPost(request, response);
  60.     }
  61.     
  62. }

5、web.xml配置

這裏寫圖片描述


6、運行SercletServer.java

Eclipse會自動彈出一個瀏覽器,效果如圖:

這裏寫圖片描述


7、HttpRequest

從網上隨便找一個HttpRequest來測試一下

  1. package httpTest;
  2.     
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.net.URLEncoder;
  11.     
  12. public class HttpRequest {
  13.     
  14.     public static void main(String[] args) throws UnsupportedEncodingException {
  15.         String data="id=521&name=";
  16.         data=URLEncoder.encode(data, "utf-8");
  17.         String sr = HttpRequest.sendPost("http://localhost:8080/MyServlet/", data);
  18.         System.out.println(sr);
  19.     }
  20.     
  21.    /**
  22.     * 向指定 URL 發送POST方法的請求
  23.     * 
  24.     * @param url
  25.     *            發送請求的 URL
  26.     * @param param
  27.     *            請求參數,請求參數應該是name1=value1&name2=value2 的形式。
  28.     * @return 所代表遠程資源的響應結果
  29.     */
  30.    public static String sendPost(String url, String param) {
  31.        PrintWriter out = null;
  32.        BufferedReader in = null;
  33.        String result = "";
  34.        try {
  35.            URL realUrl = new URL(url);
  36.            // 打開和URL之間的連接
  37.            URLConnection conn = realUrl.openConnection();
  38.            // 設置通用的請求屬性
  39.            conn.setRequestProperty("accept", "*/*");
  40.            conn.setRequestProperty("connection", "Keep-Alive");
  41.            conn.setRequestProperty("user-agent",
  42.                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT5.1;SV1)");
  43.            // 發送POST請求必須設置如下兩行
  44.            conn.setDoOutput(true);
  45.            conn.setDoInput(true);
  46.            // 獲取URLConnection對象對應的輸出流
  47.            out = new PrintWriter(conn.getOutputStream());
  48.            // 發送請求參數
  49.            out.print(param);
  50.            // flush輸出流的緩衝
  51.            out.flush();
  52.            // 定義BufferedReader輸入流來讀取URL的響應
  53.            in = new BufferedReader(
  54.                    new InputStreamReader(conn.getInputStream()));
  55.            String line;
  56.            while ((line = in.readLine()) != null) {
  57.                result += line;
  58.            }
  59.        } catch (Exception e) {
  60.            System.out.println("發送 POST 請求出現異常!"+e);
  61.            e.printStackTrace();
  62.        }
  63.        //使用finally塊來關閉輸出流、輸入流
  64.        finally{
  65.            try{
  66.                if(out!=null){
  67.                    out.close();
  68.                }
  69.                if(in!=null){
  70.                    in.close();
  71.                }
  72.            }
  73.            catch(IOException ex){
  74.                ex.printStackTrace();
  75.            }
  76.        }
  77.        return result;
  78.    }    
  79.    
  80. }

8、http測試結果

這裏寫圖片描述


9、war包

右鍵項目 -> Export -> WAR file
把導出的war包放在Tomcat安裝目錄下的webapps文件夾下
進入Tomcat安裝目錄下的bin文件夾,雙擊startup.bat運行
運行剛纔的HttpRequest.java,可以得到相同的結果


10、Tomcat?湯姆貓?喵~

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章