[英]How do I get the HTTPServletRequest in Springboot application
To get the request URL, found below approaches in stack overflow.要获取请求 URL,请在堆栈溢出中找到以下方法。
1st approach:第一种方法:
@Autowired
private HttpServletRequest request;
public void getURL(){
String url=request.getRequestURL().toString();
}
2nd approach:第二种方法:
public void getURL(){
String url=ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString();
}
3rd approach:第三种方法:
public void getURL(){
HttpServletRequest request=
((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
String url=request.getRequestURL().toString();
}
I am confused which one to use to get the request URL in the spring boot application.我很困惑在 Spring Boot 应用程序中使用哪一个来获取请求 URL。
if i go with 3rd approach, then should i need to create bean of RequestContextListener in Configuration class as shown below?如果我采用第三种方法,那么我是否需要在 Configuration 类中创建 RequestContextListener 的 bean,如下所示?
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
Actually it is very simple.其实很简单。 Create a class that is annotated as
@RestController
and in it create a method that is handling your mapping.创建一个注释为
@RestController
的类,并在其中创建一个处理映射的方法。 In that method list HttpServletRequest request
as your parameter.在该方法中列出
HttpServletRequest request
作为您的参数。 That's it, in this method you will get it as parameter and can use it.就是这样,在这种方法中,您将获得它作为参数并可以使用它。 Below is one of my working examples that does just that.
下面是我的一个工作示例,它就是这样做的。
@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");
}
}
In springboot, if use are using @Restcontroller, HttpServletRequest already exist in first paramester of controler method在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.