从Spring Web应用程序检索Servlet上下文路径 [英] Retrieving the servlet context path from a Spring web application

查看:115
本文介绍了从Spring Web应用程序检索Servlet上下文路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够动态服务Spring bean .

之所以这样做,是因为我想在将要发送给网站用户的电子邮件中使用此值.

The reason for this is that I want to use this value in email that are going to be sent to users of the website.

虽然从Spring MVC控制器执行此操作非常容易,但从Service Bean执行此操作并不是那么明显.

While it would be pretty easy to do this from a Spring MVC controller, it is not so obvious to do this from a Service bean.

有人可以建议吗?

附加要求:

我想知道是否没有在应用程序启动时检索上下文路径并使我的所有服务都可随时获取的路径?

I was wondering if there wasn't a way of retrieving the context path upon startup of the application and having it available for retrieval at all time by all my services?

推荐答案

如果使用ServletContainer> = 2.5,则可以使用以下代码获取ContextPath:

If you use a ServletContainer >= 2.5 you can use the following code to get the ContextPath:

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component

@Component
public class SpringBean {

    @Autowired
    private ServletContext servletContext;

    @PostConstruct
    public void showIt() {
        System.out.println(servletContext.getContextPath());
    }
}

这篇关于从Spring Web应用程序检索Servlet上下文路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆