我正在运行一个spring boot,我的一些域名服务需要知道域名。
我知道我可以在控制器方法的应用层捕获它,如下所示:
@RequestMapping(value="/myMapping",method = RequestMethod.POST)
public ModelandView myAction(HttpServletRequest request) {
}
或者,如果我运行的是传统的Web应用程序,我可以配置一个像这样的监听器:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
然后像这样访问:
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
但我不想像我在控制器上捕获它那样传递参数,而且我没有使用web.xml运行战争。
我怎样才能吃蛋糕呢?
答案 0 :(得分:4)
如果您使用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();
答案 1 :(得分:3)
这就是我所做的:
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class RequestFetcher {
public 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;
}
}
答案 2 :(得分:0)
我不知道您所说的“我没有运行WAR”是什么意思,但是这个问题被标记为适用于Web应用程序的Spring-MVC。无论如何,这就是获取请求域的方法。当浏览器发出请求时,它将主机名作为HTTP请求标头的一部分发送,用于多域Web托管。对于HTTPS,Server Name Identification是同一件事。
@RequestMapping(value = "/server/path")
public void request(
@RequestHeader(name="Host", required=false) final String host,