【问题标题】:Setting webapprootkey no-web.xml设置 webapprootkey no-web.xml
【发布时间】:2013-07-09 10:40:46
【问题描述】:

我正在将一个 Web 应用程序迁移到 Spring 3.2,并且正在享受无 web.xml 的配置。 剩下的一部分是设置 webapp 根密钥,我之前在 web.xml 中这样做过:

<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapproot</param-value>
</context-param>

我知道 Spring 创建了一个默认密钥,但在我的情况下,我正在运行同一个战争的多个版本,并且需要在每个版本中将密钥设置为不同的值。所以最理想的情况是,我想从属性文件中获取一个值并将其用作根键。

我想我会在这里的某个地方这样做:

public class WebAppInitializer implements WebApplicationInitializer {
    private static final Logger logger = Logger.getLogger(WebAppInitializer.class);

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    // Create the root appcontext
       AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
       rootContext.register(AppConfig.class);

       servletContext.addListener(new WebAppRootListener());

    // Manage the lifecycle of the root appcontext
       servletContext.addListener(new ContextLoaderListener(rootContext));
       //servletContext.setInitParameter("defaultHtmlEscape", "true");

    // The main Spring MVC servlet.
       ServletRegistration.Dynamic springapp = servletContext.addServlet(
          "springapp", new DispatcherServlet(rootContext));
            springapp.setLoadOnStartup(1);
       Set<String> mappingConflicts = springapp.addMapping("/");
...etc...

感谢任何可以提供建议的人!

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    第一部分很简单:

    servletContext.setInitParameter("webAppRootKey", getRootKey());
    

    并获取根密钥,在这种情况下,它由 maven 构建添加到 application.properties 文件中,

    private String getRootKey() {
        Properties prop = new Properties();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();           
        InputStream stream = loader.getResourceAsStream("application.properties");
        String key=null;
        try {
            prop.load(stream);
            key = prop.getProperty("rootKey");
        } catch  (Exception e) {
            throw new RuntimeException("Cannot load webapprootkey", e);
        }
        return key;
    }
    

    【讨论】:

    • 你能分享 application.properties 中的内容吗?我有一个场景,运行从同一个 Maven 快速入门创建的两个 web 应用程序,如果同时在服务器上添加两个应用程序会导致问题。这是我的问题:stackoverflow.com/q/18543317/1654823,请你看看
    猜你喜欢
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多