java获取 requestmapping的value url,java – Spring Boot – 如何获取请求的基本URL

本文介绍如何使用Spring Security中的SecurityContext存储和检索自定义信息,例如当前用户的域名。通过覆盖AbstractAuthenticationToken的setDetails方法,可以轻松地在应用程序中任何地方获取这些详细信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果您使用Spring Security,则可以将此信息存储在SecurityContext中.诀窍是getDetails()方法,你可以在那里放任何你想要的东西.我个人使用自定义对象来存储当前用户所需的基本信息.此示例只是放置一个代表您的域的简单字符串:

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AbstractAuthenticationToken;

import org.springframework.security.core.context.SecurityContext;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.stereotype.Component;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component

public class DomainInterceptor extends HandlerInterceptorAdapter {

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

String domain = null; // TODO extra domain from request here

SecurityContext context = SecurityContextHolder.getContext();

AbstractAuthenticationToken authentication = (AbstractAuthenticationToken) context.getAuthentication();

authentication.setDetails(domain);

return true;

}

}

然后,要在应用中的任何位置检索域(对于当前请求),您可以执行以下操作:

String domain = SecurityContextHolder.getContext().getAuthentication().getDetails().toString();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值