博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring boot获取request
阅读量:5775 次
发布时间:2019-06-18

本文共 2092 字,大约阅读时间需要 6 分钟。

1. Controller中

1.1 通过静态方法获取

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

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

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,如果为空,抛出异常。

HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

附Objects.requireNonNull源码

public static 
T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; }

1.2 通过参数直接获取

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

@GetMapping(value = "")public String center(HttpServletRequest request,HttpServletResponse response) {    //...}

1.3 自动注入

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

@Autowiredprivate HttpServletRequest request; @Autowiredprivate HttpServletResponse response; @GetMapping(value = "")public String center() {    //...}

2.controller以外部分

见1.1

转载于:https://www.cnblogs.com/rosa-king/p/10136029.html

你可能感兴趣的文章
晶澳向埃及11MW混合发电项目供应光伏组件
查看>>
国产x86 CPU性能达Intel的80%?
查看>>
用友网络陈强兵:企业互联网需解决五大问题
查看>>
SMA推出Powerwall兼容Sunny Boy Storage逆变器
查看>>
云路由 vyatta 体验(二)NAT
查看>>
C++、Java、JavaScript中迭代器的用法
查看>>
jackson not marked as ignorable异常
查看>>
Python version 2.7 required, which was not foun...
查看>>
android 模拟器 横竖屏切换
查看>>
centos7.3 下安装 composer,解决Failed to decode zlib stream错误
查看>>
Git 常用命令
查看>>
在Postgres 数据库中生成36位的UUID代码
查看>>
小黑小波比.功能测试登录用户
查看>>
Java enum用法详解
查看>>
去云端的多条途径
查看>>
Docker容器从一知半解到入门
查看>>
关于“方法参数”
查看>>
Redis命令总结
查看>>
unable to write 'random state'错误解决
查看>>
win7 wamp 下安装pear phpunit
查看>>