前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring boot 获取 request

spring boot 获取 request

作者头像
一个会写诗的程序员
发布2019-03-15 16:20:31
2.6K0
发布2019-03-15 16:20:31
举报

1. Controller中

1.1 通过静态方法获取

代码语言:javascript
复制
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

但我在使用过程中发现遇到了一个警告

代码语言:javascript
复制
 Method invocation 'getRequest' may produce 'java.lang.NullPointerException' less... (Ctrl+F1)
 Inspection info: This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
 Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report NullPointerException (NPE) errors that might be produced.
 More complex contracts can be defined using @Contract annotation, for example:
 @Contract(", null -> null") — method returns null if its second argument is null @Contract(", null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise @Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it
 The inspection can be configured to use custom @Nullable
 @NotNull annotations (by default the ones from annotations.jar will be used)
 

如此使用可能会造成空指针异常,所以建议添加Objects.requireNonNull,如果为空,抛出异常。

代码语言:javascript
复制
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

附Objects.requireNonNull源码

代码语言:javascript
复制
public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

1.2 通过参数直接获取

在参数上添加后,springboot会帮你绑定,之后可以直接使用

代码语言:javascript
复制
@GetMapping(value = "")
public String center(HttpServletRequest request,HttpServletResponse response) {
    //...
}

1.3 自动注入

通过@Autowired自动注入,这样就不用每个方法都写了

代码语言:javascript
复制
@Autowired
private HttpServletRequest request;

@Autowired
private HttpServletResponse response;

@GetMapping(value = "")
public String center() {
    //...
}

2.controller以外部分

见1.1

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.03.11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Controller中
    • 1.1 通过静态方法获取
      • 1.2 通过参数直接获取
        • 1.3 自动注入
          • 2.controller以外部分
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档