Servlet-请求重定向

一、什么是请求重定向?

请求重定向是指客户端给服务器发请求,然后服务器告诉客户端说,

我给你一个新地址,你去新地址访问,这叫请求重定向。

 

 

相关代码

package com.orzjiangxiaoyu.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author orz
 * @create 2020-09-10 23:54
 */
public class Response1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //方法一
//        //1.设置响应状态码302,表示重定向
//        resp.setStatus(302);
//        //2.设置响应头,说明新地址在哪里
//        resp.setHeader("Location","http://localhost:8090/Servlet_GetPost_war_exploded/response2");

        //方法二
        resp.sendRedirect("http://localhost:8090/Servlet_GetPost_war_exploded/response2");
    }
}
View Code
package com.orzjiangxiaoyu.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author orz
 * @create 2020-09-10 23:55
 */
public class Response2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        writer.write("Response2 hello");
    }
}
View Code

 

posted @ 2020-09-11 00:01  orz江小鱼  阅读(137)  评论(0编辑  收藏  举报