1、Servlet最主要的作用就是处理客户端请求,并向客户端做出响应。
针对Servlet的每次请求,Web服务器在调用service()方法之前,都会创建两个对象:
- HttpServletRequest用于封装HTTP请求消息,简称request对象。
- HttpServletResponse用于封装HTTP响应消息,简称response对象。
request对象和response对象在请求Servlet过程中至关重要。
2、HttpServletResponse接口
(1)HttpServletResponse接口,它继承自ServletResponse接口,专门用来封装HTTP响应消息。
(2)HTTP响应消息分为状态行、响应消息头、消息体 三部分
(3)HttpServletResponse接口中定义了向客户端发送响应状态码、响应消息头、响应消息体的方法
3、发送状态码相关的方法
当Servlet向客户端回送响应消息时,需要在响应消息中设置状态码。在HttpServletResponse接口中,定义了两个发送状态码的方法
1.setStatus(int status)方法
该方法用于设置HTTP响应消息的状态码,并生成响应状态行。
HTTP/1.1 200 OK
状态描述信息直接与状态码相关,而HTTP版本由服务器确定,正常情况下,Web服务器会默认产生一个状态码为200的状态行。
2.sendError(int sc)方法
用于发送表示错误信息的状态码,
例如,404状态码表示找不到客户端请求的资源。
public void sendError(int code) throws java.io.IOException;
public void sendError(int code,String message) throws java.io.IOException;
重载的两个方法:
第一个方法只是发送错误信息的状态码。
第二个方法除了发送状态码外,还可以增加一条用于提示说明的文本信息,该文本信息将出现在发送给客户端的正文内容中。(如上述代码所示)
4、发送响应消息头相关方法
在HTTP响应消息中,大量的数据都是通过响应消息体传递的,定义了两个与输出流相关的方法:
1.getOutputStream()方法
该方法所获取的字节输出流对象为ServletOutputStream类型,是OutputStream的子类。要想输出二进制格式的响应正文, 就需要使用getOutputStream()方法。
public class ChineseServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
String data = "itcast";
// 获取字节输出流对象
OutputStream out = response.getOutputStream();
out.write(data.getBytes());// 输出信息
}
public void doPost(….){….}
}
2.getWriter()方法
该方法所获取的字符输出流对象为PrintWriter类型。要想输出内容全为字符文本的网页文档, 需要使用getWriter()方法。
public class ChineseServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
String data = “itcast";
//使用getWriter()方法发送消息体
PrintWriter out = response.getWriter();
out.println(data);
}
}
注意:两个方法不能同时使用。
5、获取请求行信息的相关方法
6、获取请求消息头的相关方法
7、获取请求参数
最常用:
.getParameter();
.getParameterValues();
示例:
<form action="/chapter04/RequestParamsServlet" method=“POST">
用户名:<input type="text" name="username"><br>
密 码:
<input type="password" name="password"><br>
爱好:
<input type="checkbox" name="hobby" value="sing">唱歌
<input type="checkbox" name="hobby" value="dance">跳舞
<input type="checkbox" name="hobby" value="football">足球<br>
<input type="submit" value="提交">
</form>
public void doGet(request, response)throws ServletException, IOException {
String name = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("用户名:" + name);
System.out.println("密 码:" + password); String[] hobbys =
request.getParameterValues("hobby");
System.out.print("爱好:");
for (int i = 0; i < hobbys.length; i++) {
System.out.print(hobbys[i] + ",");
}}