本文整理汇总了Java中org.springframework.web.context.request.RequestContextHolder类的典型用法代码示例。如果您正苦于以下问题:Java RequestContextHolder类的具体用法?Java RequestContextHolder怎么用?Java RequestContextHolder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
RequestContextHolder类属于org.springframework.web.context.request包,在下文中一共展示了RequestContextHolder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doBefore
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
示例2: doBefore
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Before("loginHandle()")
public void doBefore(JoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Principal principal = request.getUserPrincipal();
if (principal != null && principal instanceof Pac4jPrincipal) {
logger.debug("准备判断用户绑定状态");
Pac4jPrincipal pac4jPrincipal = (Pac4jPrincipal) principal;
//获取认证客户端
String clientName = (String) pac4jPrincipal.getProfile().getAttribute("clientName");
//获取客户端策略
ClientStrategy clientStrategy = clientStrategyFactory.getClientStrategy().get(clientName);
if (clientStrategy != null) {
//判断该客户端是否已经有绑定用户
if (!clientStrategy.isBind(pac4jPrincipal)) {
logger.debug("用户[" + pac4jPrincipal.getProfile().getId() + "]通过" + clientStrategy.name() + "登录尚未绑定");
//未绑定给予处理
clientStrategy.handle(pjp, pac4jPrincipal);
}
}
}
}
示例3: getConnectionFactory
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Override
public ConnectionFactory<?> getConnectionFactory(String providerId) {
HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
String domain = TenantContext.getCurrent().getDomain();
Optional<SocialConfig> config = socialConfigRepository.findOneByProviderIdAndDomain(providerId, domain);
if (config.isPresent()) {
SocialConfig sc = config.get();
switch (sc.getProviderId()) {
case "facebook":
return new FacebookConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
case "google":
return new GoogleConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
case "twitter":
return new TwitterConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
case "linkedin":
return new LinkedInConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
default:
break;
}
}
throw new IllegalArgumentException("No provider config found for " + providerId);
}
示例4: delPointcut
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Around("classPointcut() && delPointcut() && @annotation(mapping)")
public String delEmployee(ProceedingJoinPoint joinPoint, RequestMapping mapping) throws Throwable{
HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
logger.info("executing " + joinPoint.getSignature().getName());
int userId = (Integer)req.getSession().getAttribute("userId");
System.out.println("userId" + userId);
List<RolePermission> permission = loginServiceImpl.getPermissionSets(userId);
if(isAuthroize(permission)){
logger.info("user " + userId + " is authroied to delete");
joinPoint.proceed();
return "menu";
}else{
logger.info("user " + userId + " is NOT authroied to delete");
return "banned";
}
}
示例5: doBefore
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("请求地址 : " + request.getRequestURL().toString());
logger.info("请求方法类型 : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
}
示例6: process
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
/**
* 查询物品最低价时统计物品查询
* @param point 切点
* @return 切面方法返回值
* @throws Throwable 异常
*/
@Around("execution(public * com.bnade.wow.controller.CheapestAuctionController.findAll(..))")
public Object process(ProceedingJoinPoint point) throws Throwable {
// 获取方法参数
CheapestAuction cheapestAuction = null;
Object[] args = point.getArgs();
if (args != null && args.length == 1) {
cheapestAuction = (CheapestAuction)args[0];
}
// 实际方法运行
Object returnValue = point.proceed();
if (cheapestAuction != null && returnValue != null && returnValue instanceof List) {
// 当有返回数据时才统计
if (((List) returnValue).size() > 0) {
// 获取httprequest
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String ip = IPUtils.getIp(request);
// 统计物品搜索
logger.debug("记录ip: {}, item: {}", ip, cheapestAuction.getItemId());
statisticService.recordItemSearchedByIp(ip, "" + cheapestAuction.getItemId());
}
}
return returnValue;
}
示例7: readAll
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
/**
* Function to read all users
*
* @return ResponseEntity<DtoUsers>
*/
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<DtoList<DtoUser>> readAll() {
if (!this.getLoggedInUser().isAdmin()) {
LOGGER.error(() -> "Users can only be read by system administrators");
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
if(false) {
ServletRequestAttributes attr = (ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true); // true == allow create
}
/**
* As well as the standard user data we want to include statistics for number of users and groups
* (as well as number of open invitations)
*/
final DtoList list = new DtoList<DtoUser>();
this.serviceUser.getAll().forEach(u -> {
list.add(getDtoUser(u));
});
return new ResponseEntity<>(list, HttpStatus.OK);
}
示例8: printHead
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
public static void printHead(Model model) {
HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
UserAuthDO userAuthDO = UserAuth.getCurrentUser(httpServletRequest);
if (userAuthDO != null) {
model.addAttribute("user", userAuthDO);
}
}
示例9: getCurrentRequest
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
/**
* Obtain the request through {@link RequestContextHolder}.
* @return the active servlet request
*/
protected static HttpServletRequest getCurrentRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
return servletRequest;
}
示例10: interceptor
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
TccTransactionContext tccTransactionContext;
//如果不是本地反射调用补偿
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
String context = request == null ? null : request.getHeader(CommonConstant.TCC_TRANSACTION_CONTEXT);
tccTransactionContext =
GsonUtils.getInstance().fromJson(context, TccTransactionContext.class);
return tccTransactionAspectService.invoke(tccTransactionContext, pjp);
}
示例11: findUser
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
protected User findUser() {
try {
RequestAttributes reqAttr = RequestContextHolder.currentRequestAttributes();
if (reqAttr instanceof ServletRequestAttributes) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) reqAttr;
HttpServletRequest request = servletRequestAttributes.getRequest();
if (request != null) {
Object obj = request.getAttribute(User.class.getName());
if (obj instanceof User) {
return (User) obj;
}
}
}
} catch (IllegalStateException e) {
log.debug("Unable to obtain request context user via RequestContextHolder.", e);
}
return null;
}
示例12: doVerify
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Before("verify()")
public void doVerify() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//查询cookie
Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
if (cookie == null) {
log.warn("【登录校验】Cookie中查不到token");
throw new SellerAuthorizeException();
}
//去redis里查询
String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
if (StringUtils.isEmpty(tokenValue)) {
log.warn("【登录校验】Redis中查不到token");
throw new SellerAuthorizeException();
}
}
示例13: interceptor
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
MythTransactionContext mythTransactionContext = TransactionContextLocal.getInstance().get();
if (Objects.nonNull(mythTransactionContext) &&
mythTransactionContext.getRole() == MythRoleEnum.LOCAL.getCode()) {
mythTransactionContext = TransactionContextLocal.getInstance().get();
} else {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
String context = request == null ? null : request.getHeader(CommonConstant.MYTH_TRANSACTION_CONTEXT);
if (StringUtils.isNoneBlank(context)) {
mythTransactionContext =
GsonUtils.getInstance().fromJson(context, MythTransactionContext.class);
}
}
return mythTransactionAspectService.invoke(mythTransactionContext, pjp);
}
示例14: list
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@RequiresPermissions("admin:index")
@ResponseBody
@RequestMapping(value = "/admins", method = RequestMethod.GET)
public ResponseDTO list() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Integer pageSize = Integer.valueOf(Objects.nonNull(request.getParameter("pageSize")) ? request.getParameter("pageSize") : "20");
Integer pageNumber = Integer.valueOf(Objects.nonNull(request.getParameter("pageIndex")) ? request.getParameter("pageIndex") : "1");
String userName = request.getParameter("userName");
String email = request.getParameter("email");
String reservation = request.getParameter("reservation");
logger.info("查询条件为,userName:{},email:{},reservation:{}", userName, email, reservation);
Map<String, Object> params = new HashMap();
if (!StringUtils.isEmpty(userName)) {
params.put("userName", userName);
}
if (!StringUtils.isEmpty(email)) {
params.put("userEmail", email);
}
Pagination<AdminDO> pagination = adminService.pageAdminsByConditions(pageNumber, pageSize, params);
return new ResponseDTO(0, "success", pagination);
}
示例15: execution
import org.springframework.web.context.request.RequestContextHolder; //导入依赖的package包/类
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping) && execution(public * *(..))")
public Object log(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes())
.getRequest();
Object value;
try {
value = proceedingJoinPoint.proceed();
} catch (Throwable throwable) {
throw throwable;
} finally {
log.info(
"{} {} from {}",
request.getMethod(),
request.getRequestURI(),
request.getRemoteAddr(),
request.getHeader("user-id"));
}
return value;
}