java - Spring Boot - 如何获取请求的基本 url

标签 java spring spring-mvc spring-boot

我正在运行 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/

相关文章:

java - 关于清理/删除 Tomcat 临时目录中存在的文件的建议

java - Spring MVC : please explain difference between @RequestParam and @ModelAttribute

java - 从 Selenium 的下拉列表中选择一个项目

java - DefaultMessageListenerContainer : is it possible to cache consumer when using global transactions

java - 可以在后端运行 spring boot 应用程序吗?

java - 将pre-json编码的字符串输出到spring框架

java - 无法在 JAVA API springs 中执行带有 json 值的 URL

java - 剥离 java 字符串中的 url

java - 在Java中使用文件锁复制文件

java - 如何让底部Sheet在不同屏幕尺寸下调整大小?