1.Request對象的作用是與客戶端交互,收集客戶端的Form、Cookies、超鏈接,或者收集服務器端的環境變量。
request對象是從客戶端向服務器發出請求,包括用戶提交的信息以及客戶端的一些信息。
客戶端可通過HTML表單或在網頁地址后面提供參數的方法提交數據,然后通過request對象的相關方法來獲取這些數據。
request的各種方法主要用來處理客戶端瀏覽器提交的請求中的各項參數和選項。
2.requset的常用命令設置
//1.獲取請求方式 String method = request.getMethod();
//2.獲得請求的資源
String requestURI = request.getRequestURI();
StringBuffer requestURL = request.getRequestURL();
//3.獲取web應用的名稱
String contextPath = request.getContextPath();
//4.地址后的參數字符串
String queryString = request.getQueryString();
//5.獲取客戶端信息--獲得IP地址
String remoteAddr = request.getRemoteAddr();
3.相應結果
4.完整代碼
.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="/WEB15/line" method="post"> 姓名:<input type="text" name="username"><br> 密碼:<input type="password" name="password"><br> <input type="submit" value="提交"><br> </form> </body> </html>
Lineservlet
package com.hdh.servlet; 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 LineServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.獲取請求方式 String method = request.getMethod(); System.out.println("method:" + method); // 2.獲得請求的資源 String requestURI = request.getRequestURI(); StringBuffer requestURL = request.getRequestURL(); System.out.println("uri:" + requestURI); System.out.println("url:" + requestURL); // 3.獲取web應用的名稱 String contextPath = request.getContextPath(); System.out.println("web應用名稱:" + contextPath); // 4.地址后的參數字符串 String queryString = request.getQueryString(); System.out.println("queryString:" + queryString); //5.獲取客戶端信息--獲得IP地址 String remoteAddr = request.getRemoteAddr(); System.out.println("remoteAddr:"+remoteAddr); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
5.注意事項
<form action="/WEB15/line" method="post">
action的提交路徑為LineServlet 在web.xml中的mapping的訪問路徑(url-pattern);