我正在运行 spring boot,我的一些域服务需要知道域名。
我知道我可以像这样在 Controller 方法中的应用程序层捕获它:
@RequestMapping(value="/myMapping",method = RequestMethod.POST)
public ModelandView myAction(HttpServletRequest request) {
}
或者,如果我正在运行一个带有 war 的传统 Web 应用程序,我可以像这样配置一个监听器:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
然后像这样访问它:
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
但我不想像我在 Controller 上捕获它时那样传递参数,而且我没有与 web.xml 进行 war 。
我怎样才能既吃蛋糕又吃蛋糕?
最佳答案
如果您使用 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();
关于java - Spring Boot - 如何获取请求的基本 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21239517/