在客户机和服务器之间进行请求-响应时,两种最常被用到的方法是:GET 和 POST。
(1)GET - 从指定的资源请求数据。
(2)POST - 向指定的资源提交要被处理的数据
新建一个web项目:
(1)TestServlet.java
```java
package sxx;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("DoGet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("DoPost");
}
@Override
public void destroy() {
System.out.println("destroy");
}
}
(2)web.xml
```java
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>T1</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>
<servlet-name>t1</servlet-name>
<servlet-class>sxx.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>t1</servlet-name>
<url-pattern>/t1.do</url-pattern>
</servlet-mapping>
</web-app>
(3)index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<a href="t1.do">我是超链接</a><br>
<form action="t1.do" method="get">
用户名: <input type="text" name="user">
<input type="submit" value="get提交">
</form>
<form action="t1.do" method="post">
用户名: <input type="text" name="user">
<input type="submit" value="post提交">
</form>
</body>
</html>
依次点击超链接、get、post后,控制台输出:DoGet DoGet DoPost
且get提交后网址为:http://127.0.0.1:8081/T1/t1.do?user=zs,而post为:http://127.0.0.1:8081/T1/t1.do
可以看出:
(1)超链接等价于URL直接访问,以get方式
(2)表单可以使用POST也可以使用GET方式