springboot中如何获得请求头里面的信息

1.直接在controller层里面获得 request,然后传给service层的

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Autowired
private HttpServletRequest request;

request.getHeader("token");

public class UserRequest {
	public static String getCurrentToken() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String token = request.getHeader("token");
		return token;
	}
}

不从controller层传到service层,直接在service层获取

ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

直接在service层里面注入 HttpServletRequest ,然后通过这个直接获得请求里面的信息,这种方法其实是和第一种是一样的

你可能感兴趣的:(spring)