Day03【Response】设置响应头

response-设置响应头

  • (1)响应头是什么?
    响应头是一组键值对
  • (2)设置响应头有什么用?
    1)设置自己的键值对 name:jack
    2)修改系统已经存在的键值对
  • (3)设置方法
	void setHeader(String name, String value)
	//设置响应头的名字:Content-Type的值
   	 void setHeader("Content-Type", String value)
	void setContentType(String type)
	//设置响应头,5秒钟之后,页面自动跳转到/day14login/index.html
	response.setHeader("Refresh", "5;url=/day14login/index.html");	
 	setHeader("Content-Disposition", String value)

src\com\wzx\pack02_sethead\Demo02SetHeadServlet.java

@WebServlet("/set_head")
public class Demo02SetHeadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1:在响应头里面添加自己定义的key-value
        response.setHeader("name","jack");
        response.setHeader("gf","rose");

        //2:修改key-value的值
        //Content-Type: text/html;charset=utf-8
        //response.setHeader("Content-Type","text/html;charset=utf-8");

        response.setContentType("text/html;charset=utf-8");

        response.getWriter().println("中国");

    }
}

response-重定向**

  • (1)什么叫重定向?
    两次请求,两次响应
    在这里插入图片描述

浏览器访问一个Servlet1,Servlet1没有我想要的资源,Servlet1让浏览器找Servlet2

  • (2)重定向的核心
    响应码302
    响应头Location
  • 案例
    src\com\wzx\pack03_redirect\Demo01Servlet.java
    编写重定向的代码,使用了两种方式,要求掌握第二种
@WebServlet("/demo01")
public class Demo01Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //我没有资源 你访问Servlet2
        //设置重定向的参数  302  Location

        //1:设置302
        //response.setStatus(302);
        //2:设置Location
        //response.setHeader("Location","/web01_reponse/demo02");

        response.sendRedirect("/web01_reponse/demo02");
    }
}

src\com\wzx\pack03_redirect\Demo02Servlet.java
当前只是一个正常的Servlet

@WebServlet("/demo02")
public class Demo02Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //我有资源
        System.out.println("demo02");
    }
}


猜你喜欢

转载自blog.csdn.net/u013621398/article/details/108482622