1. 首页
  2. 软件开发
  3. JAVA
  4. SpringBoot请求转发的方式

SpringBoot请求转发的方式

  • 发布于 2024-08-14
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

概论

想要使用 SpringBoot 进行请求的转发,我们一共是有两大类(四种方法),一种是 controller 控制器转发一种是使用 HttpServletRequest 进行转发,这里每个方式都有两种转发方式一种内部转发一种外部转发

controller 控制器转发

package com.example.requestplay.demos.web.RequestPlay1;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:24
 * @Title:
 */

@RestController
public class GetPlay {
    @RequestMapping("/r1")
    public String r1(){
        return "收到请求rt1";
    }
    @RequestMapping("/r2")
    public String r2(){
        return "收到请求rt2";
    }
}
package com.example.requestplay.demos.web.RequestPlay1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:24
 * @Title:
 */

@Controller
public class ToGetPlay {

    @RequestMapping("/tr1")
    public String r1(){
        return "forward:/r1";
    }

    @RequestMapping("/tr2")
    public String r2(){
        return "redirect:/r2";
    }
}

切记转发不能使用 RestController 要不然不会被 view 解析会直接返回对应的字符串到页面

HttpServleRequest 转发

package com.example.requestplay.demos.web.RequestPlay2;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:40
 * @Title:
 */

@RestController
public class GetRequest {

    @RequestMapping("/ghr1")
    public String ghr1(){
        return "收到转发的请求";
    }

    @RequestMapping("/ghr2")
    public String ghr2(){
        return "ghr2收到转发完毕";
    }
}
package com.example.requestplay.demos.web.RequestPlay2;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:39
 * @Title:
 */

@RestController
public class ToRequest {

    @RequestMapping("/thr1")
    public String r1(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

        RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher("/ghr1");
        requestDispatcher.forward(httpServletRequest,httpServletResponse);

        return "转发完毕";
    }

    @RequestMapping("/thr2")
    public String r2(HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.sendRedirect("/ghr2");
        return "转发完毕!";
    }
}

注意到底是 HttpServleRequest 还是 HttpServleResponse,并且注意外部转发和内部转发的优缺点。