我在中创建servlet ServletContextInitializer
通过一些简化的配置动态地添加与该servlet相关的更多数据。
@Configuration
@EnableConfigurationProperties(value = ConformanceProperties.class)
public class Initializer implements ServletContextInitializer {
@Autowired
private ConformanceProperties conformanceProperties;
// ...
public void onStartup(ServletContext container) throws ServletException {
for (ConformanceProperties.Capability capability : conformanceProperties.getCapabilities()) {
ProxyServlet proxy = new ProxyServlet();
ServletRegistration.Dynamic registration = container.addServlet(capability.getName(), proxy);
registration.setLoadOnStartup(1);
registration.addMapping(capability.getBase());
registration.setInitParameter("foo", "bar");
}
}
}
稍后在服务bean中,我想从当前servlet上下文(如果可用)获取数据:
@Service
public class FooAdapter implements ResourceService {
public static Optional<HttpServletRequest> getCurrentHttpRequest() {
return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
.filter(ServletRequestAttributes.class::isInstance).map(ServletRequestAttributes.class::cast)
.map(ServletRequestAttributes::getRequest);
}
@Override
public Promise bar() {
// ...
HttpServletRequest request = getCurrentHttpRequest().get();
if (request != null) {
String foo = request.getServletContext().getInitParameter("foo");
}
// ...
}
}
不幸的是,在服务bean中,我总是得到应用程序上下文,而不是servlet上下文。因此 foo
是 null
而不是 bar
. 如何直接在服务bean中获取servlet上下文而不是上层应用程序上下文?
暂无答案!
目前还没有任何答案,快来回答吧!