繁体   English   中英

如何在 Springboot 应用程序中获取 HTTPServletRequest

[英]How do I get the HTTPServletRequest in Springboot application

要获取请求 URL,请在堆栈溢出中找到以下方法。

第一种方法:

@Autowired
private HttpServletRequest request;

public void getURL(){
String url=request.getRequestURL().toString();
}

第二种方法:

public void getURL(){
String url=ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString();
}

第三种方法:

public void getURL(){
HttpServletRequest request= 
((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
String url=request.getRequestURL().toString();
}

我很困惑在 Spring Boot 应用程序中使用哪一个来获取请求 URL。

如果我采用第三种方法,那么我是否需要在 Configuration 类中创建 RequestContextListener 的 bean,如下所示?

@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}

其实很简单。 创建一个注释为@RestController的类,并在其中创建一个处理映射的方法。 在该方法中列出HttpServletRequest request作为您的参数。 就是这样,在这种方法中,您将获得它作为参数并可以使用它。 下面是我的一个工作示例,它就是这样做的。

@RestController
@RequestMapping("/upload")
public class UploadTestController {
    @PostMapping
    public ResponseEntity<String> uploadTest(HttpServletRequest request) {
        try {
            String lengthStr = request.getHeader("content-length");
            int length = TextUtils.parseStringToInt(lengthStr, -1);
            if(length > 0) {
                byte[] buff = new byte[length];
                ServletInputStream sis =request.getInputStream();
                int counter = 0;
                while(counter < length) {
                    int chunkLength = sis.available();
                    byte[] chunk = new byte[chunkLength];
                    sis.read(chunk);
                    for(int i = counter, j= 0; i < counter + chunkLength; i++, j++) {
                        buff[i] = chunk[j];
                    }
                    counter += chunkLength;
                    if(counter < length) {
                        TimeUtils.sleepFor(5, TimeUnit.MILLISECONDS);
                    }
                }
                Files.write(Paths.get("C:\\Michael\\tmp\\testPic.jpg"), buff);
            }
        } catch (Exception e) {
            System.out.println(TextUtils.getStacktrace(e));
        }
        return ResponseEntity.ok("Success");
    }

}

在springboot中,如果使用@Restcontroller,则HttpServletRequest已经存在于controler方法的第一个参数中

@PostMapping(value = "/abc")
public ResponseEntity<?> abcMethod(HttpServletRequest req){
   // Do anything with HttpServletRequest here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM