HttpServletRequest
作用:它代表客户端的请求。用户访问服务器,请求中携带的所有数据会被封装到HttpServletRequest里,我们可以通过HttpServletRequest获取从客户端带来的所有信息。
常见应用:
获取前端传递的参数(重点)
写一个简单的登录表单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="FifthServlet" method="post">
<p>用户名:
<input type="text" name="username">
</p>
<p>密码:
<input type="password" name="password">
</p>
<p>爱好:
<input type="checkbox" name="hobby" value="eat">吃
<input type="checkbox" name="hobby" value="drink">喝
<input type="checkbox" name="hobby" value="play">玩
<input type="checkbox" name="hobby" value="merry">乐
</p>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
再写servlet:
public class FifthServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过request.getParameter()获取单个值
String username = request.getParameter("username");
String password = request.getParameter("password");
response.getWriter().println(username);
response.getWriter().println(password);
//通过getParameterValues()获取多个值
String[] hobbies = request.getParameterValues("hobby");
for (String hobby : hobbies) {
response.getWriter().println(hobby);
}
}
请求转发(重点)
public class SixthServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/FirstServlet").forward(request,response);
}
之前学习ServletContext的时候,ServletContext也能实现请求转发,这个可以仅做了解。request实现的请求转发是使用的最多的。