I am using spring-mvc framework in my current project. ROOT folder has lots of web folders containing html, jsp, css, js etc. My spring mvc configuration is as follows:
<context:annotation-config />
<bean id="comicControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.ComicController" />
<bean id="dashboardControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.DashBoardController" />
<bean id="genericControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.GenericController" />
<bean id="channelControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.ChannelController" />
<!-- <context:component-scan base-package="tv.cinemacraft.videogramwebapp.springmvc.controllers" /> -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
<property name="order" value="0" />
</bean>
And I have mapping defined in my java controller. But this is causing static content like any image to vanish. If I request for any image inside any folder by accessing ROOT//.jpg, it gives me 404 response code although image exists.
If I remove spring-mvc, image gets displayed.
Note that spring-mvc's resources attribute works for static content but that need my static content to be present inside particular folder e.g. resouce folder. So this approach is not useful for me.
Let’s say you have a directory (/resources/my_images/) that contains some product images, and you want to serve these images upon request. For example, if the requested URL is http://localhost:8080/ mystore/resource/my_images/P123.png, then you would like to serve the image with the P123.png name. Similarly, if the requested URL is http://localhost:8080/mystore/resource/images/P1234.png, then an image with the name P1234.png needs to be served.
Now how you can serve static images with Spring MVC?
Place some images under the src/main/webapp/resources/my_images/ directory;
Add the following tag in our web application context’s configuration
DispatcherServlet-context.xml file: <mvc:resources location="/resources/" mapping="/resource/**"/>
run your application and enter
http://localhost:8080/mystore/resource/images/P123.png (change the
image name in the URL based on the images you placed
FYI: <mvc:resources> tag in the web application context configuration to tell Spring where these image files are located in our project so that spring can serve those files upon request.
Related
Ok, I have been fighting this too long, time to ask for help. HELP!!!
I'm deploying an indipendent jar maven project that will be used as dependency into other projects.
I need that this jar loads its own properties file ("versione.properties" released inside the jar) when the application that will use it, will start up but I want that the application doesn't care about it. This should be in charge on the lib.
I want that who will use this lib, will have just to
include the right dependency inside his pom.xml
add <import resource="classpath*:*-context.xml" /> inside his spring app-context.xml to be sure to include also the lib-context.xml during the spring-context initialization
For this reason, the jar has its own spring lib-context.xml file as the following:
<context:component-scan base-package="it.eng.inps.comppsr" />
<bean id="propertyPlaceholderConfigurer2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="false" />
<property name="locations">
<list>
<value>classpath:versione.properties</value>
</list>
</property>
</bean>
<bean id="version" class="it.eng.inps.comppsr.util.Versione">
<property name="buildVersion" value="${comppsrutil.build.version}"/>
<property name="buildDate" value="${comppsrutil.build.timestamp}"/>
</bean>
As you can immagine, "versione.properties" file contains comppsrutil.build.version and comppsrutil.build.timestamp.
During my tests, I've tried also <value>classpath*:versione.properties</value>, <value>classpath:/versione.properties</value> and <value>classpath:*/versione.properties</value> but with no luck.
This library is used by a web-service application (a war inside an ear file) and this application has got its own spring app-context.xml that loads it own properties file as described by the following code snippet
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" depends-on="lookupPropertiesInitializer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
<property name="ignoreResourceNotFound" value="false" />
<property name="locations">
<list>
<value>file:///#{lookupPropertiesInitializer.pathToProperties}</value>
<value>classpath*:version.properties</value>
</list>
</property>
</bean>
<context:component-scan base-package="it.eng.inps.util, it.eng.inps.comppsr" />
<import resource="classpath*:*-context.xml" />
When I start the application (it runs inside JBoss EAP 7.3), I get this error:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'comppsrutil.build.version' in value "${comppsrutil.build.version}"
So, it seems that something goes wrong within the lib initialization.
If I rename the "versione.properties" file in "version.properties" (so with the same name used by the app properties file), this error desappear, I think, because it is loaded by the application PropertyPlaceholderConfigurer, so the lib property file is well located.
For this reason I think that the bean propertyPlaceholderConfigurer2 defined inside lib-context.xml, doesn't work as I expected but I didn't understand why.
Does anyone give me any tips?
I want to use CDN to serve static content like CSS, JavaScript and images in a project created with Spring MVC. But I didn't how to do it.
I'm new to Spring and I have seen some posts on the web:
JSP/Spring MVC and CDN?
How to use property from property file specified in PropertyPlaceholderConfigurer in JSP
How to show values from property file in JSP in a spring MVC app
http://tshikatshikaaa.blogspot.com/2012/11/serving-static-resources-with-spring-mvc.html
But they didn't explain how to implement it.
For example:
In the past, I use <c:url> tags:
<img src="<c:url value="/path/to/image" />" alt="desc" />
When I use CDN, I may use following code:
<img src="${env.cdnUrl}/mypath/pic.jpg" />
But where should I put ${env.cdnUrl}(in web.xml or dispatcher-servlet.xml(the configuration of Spring MVC))? And how to get the parameter in JSP?
Please help me. Thanks.
I implemented CDN service in Spring using following steps:
Add following lines in dispatcher-servlet.xml (Your Spring Configuration)
<util:properties id="propertyConfigurer" location="classpath:/app.properties"/>
<context:property-placeholder properties-ref="propertyConfigurer" />
Of course, you need to add DOM for spring-util at the top of the file:
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.1.xsd"
Setup in app.properties
cdn.url=//cdn.domain.com/path/to/static/content
Use CDN in JSP files
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="#propertyConfigurer.getProperty('cdn.url')" var="cdnUrl" />
<link rel="stylesheet" type="text/css" href="${cdnUrl}/css/semantic.min.css" />
<link rel="stylesheet" type="text/css" href="${cdnUrl}/css/font-awesome.min.css" />
Good luck!
approaches summarized:
use request.setAttribute("env", ) in controller and access the same in jsp.
create a servlet filter and do the same activity described above.
write the env value to properties file and try to access that in jsp pages. if using InternalResourceViewResolver then exposedContextBeanNames can help with exposing properties in jsp.
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list><value>property_file</value></list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="exposeContextBeansAsAttributes" value="true"/>
<property name="exposedContextBeanNames">
<list>
<value>properties</value>
</list>
</property>
</bean>
and access the values in jsp as ${properties.env}
You could also accomplish this via an interceptor.
<mvc:interceptors>
<!-- path interceptor adds servlet path as an attribute -->
<bean class="com.test.myInterceptor" />
Then in the interceptor code, you can have the attribute be set
#Override
public boolean preHandle(final HttpServletRequest request,
final HttpServletResponse response,
final Object handler) {
// set the attribute for URL
I'm facing an issue with spring placeholder configuration. I've searched the web trying to find a solution but nothing worked for me at all.
We had used to use spring configurer for loading our .properties files and everything worked fine since the configfiles where located in META-INF dir.
Now we need to have our config files located in /etc/sep/properties directory or in some other filesystem directory.
I tried to use
<context:property-placeholder location="file:/etc/sep/properties/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="${jdbc.initialPoolSize}" />
</bean>
the content of /etc/sep/properties/jdbc.properties is following:
cat /etc/sep/properties/jdbc.properties
jdbc.driverClassName= org.postgresql.Driver
jdbc.dialect=org.hibernate.dialect.PostgreSQLDialect
jdbc.databaseurl=jdbc:postgresql://localhost:5432/sep?characterEncoding=utf8&autoReconnect=true
jdbc.username=****
jdbc.password=****
I also tried using another approach as folows, but it worked for me neither.
<context:property-placeholder properties-ref="prop" />
<util:properties id="prop" location="reso"/>
<bean id="reso" class="org.springframework.core.io.FileSystemResource">
<constructor-arg index="0" value="/etc/sep/properties/jdbc.properties" />
</bean>
I don't know if it matters but we are using maven building, so that the application-context.xml is placed in core-lib.jar which is used in our web-app as dependency. Other config, such as logging work great.
I would be grateful for any suggestions.
This is just an idea but it may work,
Have you checked that the .property file has the correct access rights? I mean, is it accessible by the user that runs your Spring application?
It would help a lot if you show the error displayed.
Ok, I've finally resolved it. There were two things about it.
At First: My tomcat server was not updating deployed files properly.
And finally I'm not pretty sure if it helped, but we added one more slash after file: specification, so that the result was:
<context:property-placeholder location="file:///etc/sep/properties/*.properties" />
Now it is loading all config files properly.
I'm making a spring web app with i18n support. Right now the way the app works is that if there is a language defined in the URL parameter it'll use that, and if the parameter doesn't exist or is empty it will use the default. However I'm not satisfied with having the parameter there and I'm wondering if there's a way I can store the locale in session so it's behind the scenes and persists over all pages in the web app(because now if there is no locale parameter in the URL it'll use the defaultLocale).
My current configuration is:
applicationConfig.xml
<beans ... >
...
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="hr" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" >
<property name="paramName" value="locale" />
</bean>
</mvc:interceptors>
</beans>
I've managed to solve my problem by using instead of tags so I'll consider this question resolved. Thanks for the help.
I have faced the problem when decided to create a web-app without JSPs, but using only HTML-pages which are under directory WEB-INF/pages.
I've made the view resolver:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/pages/"/>
<property name="suffix" value=""/>
</bean>
Also I've imported all the resources in WEB-INF/pages:
<mvc:resources mapping="/**" location="WEB-INF/pages/"/>
My controller have the following view:
#PreAuthorize("isAuthenticated()")
#RequestMapping("/")
public String indexPage() {
return "redirect:/index.html";
}
It works fine for mapping "/" (redirects to login page if not authenticated), but it is not secured for url "/index.html" due to importing of this page as static resource (but it will not work at all if not import it).
Finally, I found the solution. Maybe, it will be interesting to anybody. The main servlet mapping that I had, had url-pattern: /**
And that was my problem. As I understood the main servlet in someway intercepted viewResolver even if it had such configuration: <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".html"/>
</bean>
When I make the configuration of servlet make as the next one:
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
everything became ok.
i dont know why you want to do that ..... as putting pages under web-inf is a wrong practice.......
also the container cant access the static contents that are under web-inf folder. I have faced exactly same problem see resource problem post.
what i have found from googling is you can access dynamic resources under web-inf folder but not the static. I have tried even regestring all the static contents (ie. css, js,html, etc) in xml at the first place but nothing worked. finally i moved my pages out and it worked with no configuration ....
so try moving the resources out of web-inf and under webcontent
tell me if you got some extras on this.
thanks.