1.response的状态码和响应头设置
package com.test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应状态码 response.setStatus(302); // 页面刷新,重定向 response.setHeader("Refresh", "5;url=http://www.baidu.com"); response.sendRedirect("http://www.baidu.com"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
response.getWriter().write("jack 杰克");向客户端输出文本形式
2.重定向转发的区别
Content-Type: text/html; charset=utf-8 告诉浏览器以什么样的方式打开资源,和使用编码集
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("<h1>哈哈哈<h1>");
效果:
如果设置普通文本形式:text/plain
response.setContentType("text/plain;charset=utf-8");
response.getWriter().write("<h1>哈哈哈<h1>");
效果: