HttpServletRequest接口
Web服务器收到客户端的http请求时,会针对每一次请求,创建一个用于代表请求的HttpServlet类型的Request对象,并将“Http请求协议”的完整内容封装到该对象中。开发者拿到request对象后就可以获取客户端发送给 服务器的 请求数据了。
**简而言之:Request对象中 由服务器对象创建 并封装了 来自 客户端浏览器发送过来的数据 **
例子:
创建一个html里面写一些表单信息,注意form表单的action后面的内容;method方法默认为get,可以写成post注意二者的区别::
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>提交表单1</title>
</head>
<body>
<form action='/HttpServletResponseTest' method='post'>
用户名:<input name="username" type="text"><br>
密码:<input name="password" type="password"><br>
爱好:
<input type="checkbox" name="hobby" value="basketball">排球
<input type="checkbox" name="hobby" value="football">足球
<input type="checkbox" name="hobby" value="volleyball">篮球
<br>
<input type="submit" value="提交">
</form>
</body>
</html>
创建一个Servlet来接收用户提交的数据:
public class HttpServletRequestTest01 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//根据html中的name的名字获取用户在input中的名字
String username = request.getParameter("username");
String password = request.getParameter("password");
//获取用户勾选的checkbox的值
String[] hobby = request.getParameterValues("hobby");
System.out.println(username);
System.out.println(password);
for(String s:hobby) {
System.out.println(s);}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
HTTPServletResponse接口
Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.
Web 服务器收到客户端的http请求,会针对每一次请求,创建一个用于代表响应的HttPServletResponse类型的response对象,开发者可以将要向客户端返回的数据封装到response对象中。
HttpServletResponse向客户端发送数据
ServletResponse接口有一个方法getWriter(),用于获取到一个输出流对象PrintWriter,该输出流对象是专门用于向 客户端浏览器 中输出字符数据的,称为 标准输出流。
总结:
将 web 浏览器中的内容 提交到服务器,服务器读取 用户端(浏览器的数据)(request) 对其进行数据的读取与分析,然后 将处理结果会送给用户 (response)
常用的提交数据方法:在web中进行表单的提交,注意 action 与 method 方法如何使用?