HttpServletResponse类、重定向
Tomcat服务器每次接收到一个请求都会和HttpServletRequest类一样创建一个HttpServletResponse对象,用来设置给客户端回传的响应信息
1.以流的形式向客户端传输数据
public class Web06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决响应中文乱码问题
resp.setContentType("text/html;charset=utf-8");
//获取字节流
//ServletOutputStream outputStream = resp.getOutputStream();
//获取字符流
PrintWriter writer = resp.getWriter();
writer.write("哈哈哈哈");
}
}
2.重定向
客户端向服务端发送Servlet1程序的请求,Servlet1程序将Servlet2程序的请求地址回传给客户端,让客户端发送Servlet2的请求
public class Response1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
req.setAttribute("key", username);
resp.sendRedirect("http://localhost:8090/myWebApp/res2");
}
}
public class Response2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置客户端与服务器的编码都为utf-8
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("重定向成功");
}
}
1)重定向相当于客户端发送两次请求
2)地址栏会发生改变
3)不会共享request对象
4)重定向的请求需要填写绝对路径