java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot获取HttpServletRequest

SpringBoot获取HttpServletRequest的3种方式总结

作者:太空眼睛

这篇文章主要给大家介绍了关于SpringBoot获取HttpServletRequest的3种方式,在Spring boot项目中经常要用到Servlet的常用对象如HttpServletRequest request,HttpServletResponse response,HttpSession session,需要的朋友可以参考下

方法一: Controller中增加request参数

@RestController
public class DemoController { 
    @RequestMapping("/demo")
    public void demo(HttpServletRequest request) {        
        System.out.println(request.getParameter("hello"));
    }
}

方法二: 自动注入

@Slf4j
@RequestMapping(path = "/request")
@RestController
public class DemoRequestController {
    @Resource
    private HttpServletRequest request1;
    @RequestMapping(path = "/demo")
    public String demo(HttpServletRequest request2) {
        log.info("request1: {}", request1.getClass());
        log.info("request2: {}", request2.getClass());
        return "Hello, world!";
    }
}

方法三: 基类中自动注入

本质与方法二类似

public class BaseController {   
   @Autowired 
   protected HttpServletRequest request;
}

方法四: 手动调用

@Slf4j
@RequestMapping(path = "/request")
@RestController
public class DemoRequestController {
    @Resource
    private HttpServletRequest request1;
    @RequestMapping(path = "/demo")
    public String demo(HttpServletRequest request2) {
        HttpServletRequest request3 = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        log.info("request1: {}", request1.getClass());
        log.info("request2: {}", request2.getClass());
        log.info("request3: {}", request3.getClass());
        return "Hello, world!";
    }
}

总结

获取HttpServletRequest共有三种方式

建议使用继承来减少代码冗余

适合在非Bean中获取

到此这篇关于SpringBoot获取HttpServletRequest的3种方式的文章就介绍到这了,更多相关SpringBoot获取HttpServletRequest内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文