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
Related
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.
I am trying to add a favicon.ico using spring mvc 4 and apache tomcat 7 (in firefox).
I examined many solutions but no one seems to work.
web.xml:
<mime-mapping>
<extension>ico</extension>
<mime-type>image/x-icon</mime-type>
</mime-mapping>
mvc-core-config.xml:
<mvc:default-servlet-handler/>
<!-- <mvc:resources mapping="/resources/**" location="/resources/css" /> -->
<mvc:resources location="/favicon.ico" mapping="/favicon.ico" />
jsp:
<link href="MYPROJECT/favicon.ico" rel="icon" type="image/x-icon">
(I also tried without MYPROJECT and other variations...).
I placed favicon.ico file right under webapps (tried in other folders as well).
When loading the page, no icon displayed.
Note: I tried to load directly the icon http://localhost:8080/MYPROJECT/favicon.ico but received the following error message: the image 'http://localhost:8080/MYPROJECT/favicon.ico' cannot be displayed because it contains errors. I downloaded other favicon.ico but the icon looks corrupted.
When inspecting elements in firefox I don't ant call to the favicon.ico.
Any suggestion?
Update:
in my eclipse console I see:
Looking up handler method for path /
15:48:05.622 [http-bio-8080-exec-6] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/]
15:48:05.622 [http-bio-8080-exec-6] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /
15:48:05.623 [http-bio-8080-exec-6] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/]
15:48:05.623 [http-bio-8080-exec-6] DEBUG o.s.w.s.h.SimpleUrlHandlerMapping - Mapping [/] to HandlerExecutionChain with handler [org.springframework.web.servlet.mvc.ParameterizableViewController#380baa3a] and 1 interceptor
Update2
mvc config xml:
<import resource="mvc-view-config.xml"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/>
<mvc:annotation-driven conversion-service="conversionService"/>
<context:component-scan base-package="controllers,logic.preprocess"/>
<mvc:view-controller path="/" view-name="index" />
<mvc:default-servlet-handler/>
<mvc:resources location="/favicon.ico" mapping="/favicon.ico" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages/messages"/>
</beans>
The included mvc-view-config.xml:
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="order" value="1"/> </bean>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="2" /> </bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order" value="3" />
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="controllers/TaskController">taskController</prop>
<prop key="controllers/ResultController">resultController</prop>
</props>
</property>
</bean>
update 3
I placed the file under resources/images and it seems to work PARTIALLY (without shortcut) only on chrome but not on firefox.
Thanks,
Mike
Tested in FireFox and Chrome: I had the same problem. Here is how to solve it. I've done what this answer suggested:
web.xml:
<mime-mapping>
<extension>ico</extension>
<mime-type>image/x-icon</mime-type>
</mime-mapping>
mvc-dispatcher-servlet.xml:
<mvc:resources mapping="/resources/**" location="/resources/mytheme/" />
(No need for <mvc:default-servlet-handler /> in my case)
genericpage.tag (I use templates, but this can be your jsp file):
<link rel="shortcut icon" href='<c:url value="/resources/images/favicon.ico" />' type="image/x-icon">
<link rel="icon" href='<c:url value="/resources/images/favicon.ico" />' type="image/x-icon">
NB: Note that you have to use the <c:rul value= bit in the href else it will not work.
Project structure:
Web pages
+--META-INF
+--WEB-INF
+--resources
+--mytheme
+--css
+--images
+--favicon.ico
For some reason it doesn't work when it is just in /resources/mytheme/
store favicon.ico - one up from WEB-INF directory.
<link href="/favicon.ico" rel="icon" type="image/x-icon">
You need to add below tag in your web application dispatcher servlet i.e.
springmvc-dispatcher-servlet.xml:
Specifying the Resource location to load JS, CSS, Images etc
<mvc:resources mapping="/resources/**" location="/resources/"
cache-period="45556999"/>
Your web application structure should be like below
Your web application WebContent folder structure should be like below
WebContent
+resources
-->images
-->favicon.ico
Put these line in your web application jsp pages in-between <header></header> tag like below
<head>
<link rel="shortcut icon" href='<c:url value="/resources/images/favicon.ico" />' type="image/x-icon">
<link rel="icon" href='<c:url value="/resources/images/favicon.ico" />' type="image/x-icon">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
<link href="<c:url value="/resources/css/bootstrap.css" />" rel="stylesheet">
<link href="<c:url value='/resources/css/app.css' />" rel="stylesheet">
</head>
I am a new Spring developer tried to develop sample web app with two languages support.I want to set the default locale to Arabic language and change the locale when the user clicks the desired language in JSP page.
Here is my mvc-dispatcher-servlet.xml,
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.benchmark.ushers.presentation.controller"/>
<bean id="internalResourceResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- resource bundle configuration-->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:locale/messages" />
<property name="fallbackToSystemLocale" value="false"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="ar" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"></property>
</bean>
</mvc:interceptors>
<!-- end of resource bundle configuration-->
And my JSP page as below,
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<tiles:insertDefinition name="defaultTemplate">
<tiles:putAttribute name="body">
<div class="body">
<h1>Ushers</h1>
lang : English | Arabic
<h3>
welcome.springmvc :
<spring:message code="footer.content" text="default text" />
</h3>
<h3>
hello :
<spring:message code="footer.hello" text="default text" />
</h3>
</div>
</tiles:putAttribute>
</tiles:insertDefinition>
I do not know what is wrong in my code while the only displayed the English text only.
The above configuration in the question is correct. The problem was in the requested page sets as welcome page in web.xml file so it is executed without any interceptors.
Every thing works fine after comment this part in web.xml
<!-- <welcome-file-list>
<welcome-file>/WEB-INF/pages/adminHome.jsp</welcome-file>
</welcome-file-list>-->
I guess you need DefaultAnnotationHandlerMapping to mapping with #RequestMapping it will check for any locale change request. See also Spring Internationalization.
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
Read this topic to avoid mixing it with <mvc:annotation-driven/>
In my case, I was using the java config version and it didn't worked until I added the "localeResolver" bean name. The internationalization beans I created are listed below. You can check it works by changing the lang parameter in the URL: /some-page.do?lang=ro
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
...
#Bean(name="localeResolver")
public LocaleContextResolver getLocaleContextResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getLocaleChangeInterceptor());
}
#Bean
public LocaleChangeInterceptor getLocaleChangeInterceptor() {
final LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
return interceptor;
}
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.
In my application context I have defined properties file:
<context:property-placeholder location="classpath:application.properties" />
I want to get value of the property defined in that file on JSP page. Is there a way to do that in the way
${something.myProperty}?
PropertyPlaceholderConfigurer can only parse placeholders in Spring configuration (XML or annotations). Is very common in Spring applications use a Properties bean. You can access it from your view this way (assuming you are using InternalResourceViewResolver):
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list><value>classpath:config.properties</value></list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="exposedContextBeanNames">
<list><value>properties</value></list>
</property>
</bean>
Then, in your JSP, you can use ${properties.myProperty} or ${properties['my.property']}.
After Spring 3.1, you can use <spring:eval /> tag with SpEL like this:
<spring:eval expression="#applicationProps['application.version']"
var="applicationVersion"/>
To use with multiple locations in a list which might not be present as can be done with the context:property-placeholder bean:
<beans:bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<beans:property name="ignoreResourceNotFound" value="true" />
<beans:property name="locations">
<beans:list>
<beans:value>classpath:application.properties</beans:value>
<beans:value>classpath:environment.properties</beans:value>
<beans:value>classpath:environment-${env}.properties</beans:value>
</beans:list>
</beans:property>
</beans:bean>
To use recursive property placeholder expansion in views, you need a different solution, take a look at this answer:
https://stackoverflow.com/a/10200249/770303
`<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
id="messageSource"
p:basenames="WEB-INF/i18n/site"
p:fallbackToSystemLocale="false"/>`
Now this is your Properties File
`site.name=Cool Bananas`
And.
Here goes your JSP
`<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
<head>
<title><spring:message code="site.name"/></title>
</head>
<body>
</body>
</html>`
This will show you the tables of the current schema (which you are logged in):
select table_name from user_tables order by table_name;
This will show you the tables of schema , for which you have select rights at least:
select owner, table_name from all_tables where owner='<owner>' order by owner, table_name;