Is there a built-in Spring environment variable for the web context root?

可紊 提交于 2019-11-30 05:03:06

With Spring 3.0, you should be able to access the servlet context through the servletContext bean in the web application context:

<property name="locationUri" value="#{servletContext.contextPath}/webServices" />

If you're using pre-Spring-EL (before 3.0), you should be able to do

<bean name="servletContextBean" class="org.springframework.web.context.support.ServletContextFactoryBean" />
<bean name="contextPath" factory-bean="servletContextBean" factory-method="getContextPath" />
<bean name="locationUri" factory-bean="contextPath" factory-method="concat">
   <constructor-arg value="/webServices" />
</bean>

and inside your myWebservices bean

<property name="locationUri" ref="locationUri" />

EDIT:

I don't think getting the server name and port from the ServletContext, as depending on the setup the web container may not know the hostname (i.e. a HTTP server may be in front of the web container, e.g. tomcat may be behind an Apache web server or depending on the Websphere configuration).

However, the following may be part of a solution to get the hostname. With Spring 3.0, you could do the following:

<property name="host" 
          class="java.net.InetAddress" 
          factory-method="getLocalHost"/>

<property name="locationUri" 
          value="http://#{host.canonicalHostName}:8080/#{servletContext.contextPath}/webServices" />

I had a similar problem that you described, I use property files to do this

  • ws_dev.properties
  • ws_prod.properties

I configured my property file like this, The deployment property is java vm argument like

-Ddeployment=dev

<context:property-placeholder location="ws_${deployment}.properties"/>

May be late, but may some other need a solution too:

set property in servlet:

web.xml

<servlet>
<servlet-name>spring-ws</servlet-name>
    <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/spring-ws-context.xml</param-value>
    </init-param>
    <init-param>
        <param-name>transformWsdlLocations</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

The bean declaration in spring-ws-context.xml:

<bean id="WebService"
    class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition"
    p:portTypeName="App" p:locationUri="/WebServices" p:requestSuffix="Request"
    p:responseSuffix="Response">
    <property name="schema">
        <bean class="org.springframework.xml.xsd.SimpleXsdSchema" p:xsd="classpath:/requestTypes.xsd" />
    </property>
</bean>

You can add ApplicationContextAware interface to your bean, cast it to WebApplicationContext and then get ServletContext. Also see class org.springframework.web.context.ContextLoader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!