1. 程式人生 > >http傳遞引數資訊和傳遞方式post、get

http傳遞引數資訊和傳遞方式post、get

注:本文為慕課網課程知識整理

step 1:
1.開啟Java EE eclipse

2.Window > Preferences > Server > Runtime Environment >Add > 選擇Apache Tomcat(任意版本)>Next > directory的檔案地址修改為Tomcat的本地地址(需提前下載好Tomcat)>finish

//建立一個web
3.new > Dynamic Web Project > 取名為 web 即可 > next > next > 勾選“Generate web.xml deployment descriptor”> finish

//建立一個頁面
4.右鍵單擊web建立一個JSP File,取名為 index

//建立一個sevrlet
5.右鍵單擊web建立一個Servlet,取名為 index
Java package : com.imooc.servlet
class name:MyServlet

6.重寫MyServlet的doGet()及doPost()方法

具體程式碼如下:

package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
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 MyServlet */ //@WebServlet("/MyServlet") public class MyServlet extends HttpServlet { private
static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String age = request.getParameter("age"); PrintWriter out = response.getWriter(); out.println("name="+name+" age="+age); System.out.println("name="+name); System.out.println("age="+age); } }

修改index頁面,修改body標籤內的具體程式碼如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form action="MyServlet" method="get">
       name:<input type="text" name="name"><br>
       age:<input type="text" name="age"><br>
       sumbit:<input type="submit" value ="submit"><br>
    </form>
</body>
</html>

WebContent > WEB-INF > web.xml(如果沒有這個檔案,大概是少了步驟3的勾選)如果該檔案不完整,需補充。(正常情況下,會自動補全,實現對映),具體程式碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
      <description></description>
      <display-name>MyServlet</display-name>
      <servlet-name>MyServlet</servlet-name>
      <servlet-class>com.ilove.servlet.MyServlet</servlet-class>
  </servlet>

  <servlet-mapping>
      <servlet-name>MyServlet</servlet-name>
      <url-pattern>/MyServlet</url-pattern>
  </servlet-mapping>
</web-app>

Andriod程式程式碼如下

public class MainActivity extends AppCompatActivity {

    EditText age;
    EditText name;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        age = (EditText)findViewById(R.id.age) ;
        name = (EditText)findViewById(R.id.name);
        button = (Button)findViewById(R.id.button);
    }

    public void register(View view) {
        String url ="http://192.168.31.108:8080/web/MyServlet";
/*
Java EE執行的網頁上可看到網址(當name為jian且age為23時)為:http://localhost:8080/web/MyServlet?name=jian&age=23
需要將localhost修改具體ip地址,否知手機無法識別。

192.168.31.108為電腦ip地址,可在cmd輸入ip config 獲取 ip地址
*/

        new HttpThread(url,name.getText().toString(),age.getText().toString()).start();
    }
}

---------------------------------------

public class HttpThread extends Thread {
    String url;
    String name;
    String age;


    public HttpThread(String url, String name, String age) {
        this.url = url;
        this.name = name;
        this.age = age;
    }

    private void doGet() {
        url = url + "?name=" + name + "&age=" + age;

        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String str;
            StringBuffer sb = new StringBuffer();

            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
            Log.v("伺服器返回內容",sb.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        doGet();
    }
}

執行java EE上的web(run on Server,啟動伺服器),確保在同一WiFi,可在Console看到在手機端輸入的引數(name 及 age)。