cnblogs/dcrenl/SpringBoot三种获取Request和Response的方法.html

32 lines
2.0 KiB
HTML
Raw Normal View History

2024-09-24 12:43:01 +08:00
<p>通过静态方法获取,你也可以封装一个静态方法出来</p>
<div class="cnblogs_code">
<pre>@GetMapping(value = ""<span style="color: #000000;">)
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String center() {
ServletRequestAttributes servletRequestAttributes </span>=<span style="color: #000000;"> (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request </span>=<span style="color: #000000;"> servletRequestAttributes.getRequest();
HttpServletResponse response </span>=<span style="color: #000000;"> servletRequestAttributes.getResponse();
</span><span style="color: #008000;">//</span><span style="color: #008000;">...</span>
}</pre>
</div>
<p>通过参数直接获取只要在你的方法上加上参数Springboot就会帮你绑定你可以直接使用。如果你的方法有其他参数把这两个加到后面即可。</p>
<div class="cnblogs_code">
<pre>@GetMapping(value = ""<span style="color: #000000;">)
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String center(HttpServletRequest request,HttpServletResponse response) {
</span><span style="color: #008000;">//</span><span style="color: #008000;">...</span>
}</pre>
</div>
<p>注入到类,这样就不用每个方法都写了</p>
<div class="cnblogs_code">
<pre><span style="color: #000000;">@Autowired
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> HttpServletRequest request;
@Autowired
</span><span style="color: #0000ff;">private</span><span style="color: #000000;"> HttpServletResponse response;
@GetMapping(value </span>= ""<span style="color: #000000;">)
</span><span style="color: #0000ff;">public</span><span style="color: #000000;"> String center() {
</span><span style="color: #008000;">//</span><span style="color: #008000;">...</span>
}</pre>
</div>
<p>&nbsp;</p>
<p>转自https://blog.csdn.net/jiulanhao/article/details/83068952</p>