請求request
在java中獲取到前端的資料
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
@WebServlet("/test2")
public class a02Servlet_Test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取請求行
//獲取請求方式
System.out.println("--------------------------");
System.out.println("請求方式:" + req.getMethod());
//獲取虛擬目錄(專案訪問路徑)
System.out.println("獲取虛擬目錄(專案訪問路徑):" + req.getContextPath());
//獲取URL(統一資源定位符)
System.out.println("獲取URL(統一資源定位符):" + req.getRequestURL());
//獲取URI(統一資源識別符號)
System.out.println("獲取URI(統一資源識別符號):" + req.getRequestURI());
//獲取請求引數
System.out.println("獲取請求引數:" + req.getQueryString());
System.out.println("--------------------------");
//獲取請求頭
System.out.println("user-agent:" + req.getHeader("user-agent"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取請求體
//獲取字元輸入流
System.out.println("---------------------------");
BufferedReader reader = req.getReader();
String s = reader.readLine();
System.out.println(s);
}
}
request物件提供的方法:
- 獲取所有引數Map集合
Map<String,String[]> getParameterMap()
- 根據名稱獲取引數值(陣列)
String[] getParameterValues(String name)
- 根據名稱獲取引數值(單個值)
String getParameter(String name)
//請求方式POST,解決request中文亂碼
req.setCharacterEncoding("UTF-8");
//請求方式POST,GET通用解決中文亂碼方式
username = new String(username.getBytes(StandardCharsets.ISO_8859_1));
請求轉發:一種在伺服器內部資源跳轉方式
req.getRequestDispatcher("資源B路徑").forward(req,resp);