程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Java-->服務器的響應(Servlet--doGet&doPost),javaservletdoget

Java-->服務器的響應(Servlet--doGet&doPost),javaservletdoget

編輯:JAVA綜合教程

Java-->服務器的響應(Servlet--doGet&doPost),javaservletdoget


--> Servelet: 用於接收請求(客戶端,浏覽器),做出響應的,服務器端的,java類

--> ServletLogin -- Web項目服務器響應的Java實現

package com.dragon.java.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletLogin
 */
@WebServlet("/ServletLogin")
public class ServletLogin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String user = parse(request.getParameter("user"));
        String pwd = parse(request.getParameter("pwd"));
        System.out.println(user + ":" + pwd);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(user + "登陸成功!");
        // 服務器會自動關流
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); // 只解決post 請求亂碼問題
        doGet(request, response);
    }

    public String parse(String msg) throws UnsupportedEncodingException {
        return new String(msg.getBytes("iso8859-1"), "utf-8");
    }
}

1、doGet 方法:

--> HttpURLConnectionUtil 工具類

package com.dragon.java.urlbyget;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionUtil {
    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            // 用這個方法可以設置http的請求頭
            // conn.addRequestProperty("Accept", "......");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 獲取編碼
                // String contentType = conn.getContentType();
                // String string = contentType.split("=")[1];

                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

--> Test 測試類

package com.dragon.java.urlbyget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) {
        InputStream inputStreamByGet = HttpURLConnectionUtil
                .getInputStreamByGet("http://www.baidu.com");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    inputStreamByGet, "gb2312"));
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

----------------------------------邪惡的分割線------------------------------------

2、doPost 方法

--> HttpURLConnectionUtil 工具類

package com.dragon.java.urlbypost;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionUtil {
    private static String charset;

    public static InputStream getInputStreamByPost(String url, String parms) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(parms.getBytes());
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String contentType = conn.getContentType();
                charset = contentType.split("=")[1];

                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCharset() {
        return charset;
    }
}

--> InputStreamUtil 流到String的轉換類

package com.dragon.java.urlbypost;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamUtil {

    public static String inputStreamToString(InputStream is, String charset) {
        StringBuffer sb = new StringBuffer();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is,
                charset));) {
            char[] buffer = new char[1024];
            int len = -1;
            while ((len = br.read(buffer)) != -1) {
                sb.append(buffer, 0, len);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

--> Test 測試類

package com.dragon.java.urlbypost;

import java.io.InputStream;

public class Test {
    public static void main(String args[]) {

    // 需要對URL中的中文參數進行編碼。
    String user = URLEncoder.encode("張三", "utf-8");
    String pwd = URLEncoder.encode("你好", "utf-8");
    InputStream inputStreamByPost = HttpURLConnectionUtil
        .getInputStreamByPost(
            "http://192.168.2.11:8080/08-23/ServletLogin", "user="
                + user + "&pwd=" + pwd);

        System.out.println(InputStreamUtil.inputStreamToString(
                inputStreamByPost, HttpURLConnectionUtil.getCharset()));
    }
}

---> 注意先將Web項目導入到服務器並運行...

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved