- 工具类
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
public class HeadUtil {
public static HttpServletRequest getRequest() {
return Optional.ofNullable(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())).orElseThrow(() -> new RuntimeException("未获取到当前请求信息")).getRequest();
}
public static String getHeadKey(String key) {
String value = HeadUtil.getRequest().getHeader(key);
if (StringUtils.isEmpty(value)) {
throw new RuntimeException("无法获取"+key);
}
return value;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- demo
@RestController
@RequestMapping("head")
public class HeadController {
@GetMapping
public void test(){
String headKey = HeadUtil.getHeadKey("test-test");
System.out.println(headKey);
}
}
