如何在控制器中使用Spring HttpRequest? [英] How can I use a Spring HttpRequest in my controller?

查看:709
本文介绍了如何在控制器中使用Spring HttpRequest?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经以此方式设置了测试

I've set up my test this way

@SpringBootTest
@AutoConfigureMockMvc
@RunWith( SpringRunner.class )
public class PublicControllerTest {

    @Autowired
    private MockMvc mvc;

这是我的控制器签名

@GetMapping( produces = MediaTypes.HAL_JSON_VALUE )
ResponseEntity<ResourceSupport> index( final HttpRequest request ) {

现在它似乎正在注入代理值,但是例如,如果调用request.getURI(),它似乎为空.

now it seems to be injecting a proxy value, but if you call request.getURI() for example, it seems to be null.

我正在尝试执行此操作,以便可以将请求传递给UriComponentsBuilder.fromHttpRequest( ),该请求由控制器中以前的linkTo方法调用,并且它们没有获得代理/空值.

I'm trying to do this so I can pass request to UriComponentsBuilder.fromHttpRequest( ), which is called by previous linkTo methods in my controller and they aren't getting a proxy/null.

如何获取HttpRequest? (注意:我不希望/不能使用HttpServletRequest,它可以很好地通过,但不是UriComponentsBuilder

How can I get HttpRequest? (note: I don't want/can't use HttpServletRequest which gets passed fine but is not the right interface for UriComponentsBuilder

推荐答案

所以我可以使用HttpServletRequest

@GetMapping( produces = MediaTypes.HAL_JSON_VALUE )
ResponseEntity<ResourceSupport> index( final HttpServletRequest request ) {

但是必须包装吗?通过ServletServerHttpRequest获得我想要的界面.

but it has to be wrapped? by ServletServerHttpRequest to get the interface I want.

HttpRequest httpRequest = new ServletServerHttpRequest( request ) 

这篇关于如何在控制器中使用Spring HttpRequest?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆