favicon.ico doesn't displayed in spring mvc - java

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>

Related

HTTP 403 Forbidden - Auth JASS Spring Camel

I have the following configuration to connect to an active directory with username/password to authenticate a REST DSL service in Camel. http://localhost:3000/api/data/1234
<!-- Jetty Security handling -->
<bean id="loginService" class="org.eclipse.jetty.jaas.JAASLoginService">
<property name="name" value="nameAuth"/>
<property name="loginModuleName" value="ldap-login-module"/>
</bean>
<bean id="identityService" class="org.eclipse.jetty.security.DefaultIdentityService"/>
<bean id="constraint" class="org.eclipse.jetty.util.security.Constraint">
<property name="name" value="BASIC"/>
<property name="roles" value="Admin" />
<property name="authenticate" value="true"/>
</bean>
<bean id="constraintMapping" class="org.eclipse.jetty.security.ConstraintMapping">
<property name="constraint" ref="constraint"/>
<property name="pathSpec" value="/*"/>
</bean>
<bean id="securityHandler" class="org.eclipse.jetty.security.ConstraintSecurityHandler">
<property name="authenticator">
<bean class="org.eclipse.jetty.security.authentication.BasicAuthenticator"/>
</property>
<property name="constraintMappings">
<list>
<ref bean="constraintMapping"/>
</list>
</property>
<property name="loginService" ref="loginService"/>
<property name="identityService" ref="identityService"/>
</bean>
When sending correct credentials it returns 403:
<body>
<h2>HTTP ERROR 403</h2>
<p>Problem accessing /api/data/1234. Reason:
<pre> Forbidden</pre>
</p>
<hr><i><small>Powered by Jetty://</small></i>
<hr />
</body>
When changing them and sending wrong credentials returns 401
<body>
<h2>HTTP ERROR 401</h2>
<p>Problem accessing /api/data/1234. Reason:
<pre> Unauthorized</pre>
</p>
<hr><i><small>Powered by Jetty://</small></i>
<hr />
</body>
Can it be caused by the role or something?
I appreciate if you know of any solution.
I resolved it using netty4 and not jetty.
https://camel.apache.org/components/2.x/netty4-http-component.html
restConfiguration()
//.component("jetty")
.component("netty4-http")
//.endpointProperty("handlers", "#securityHandler")
.endpointProperty("securityConfiguration.realm", "ldap-login-module")

Locale only getting values for default locale while other locale is not displaying

hi I am working on spring locale but it is still getting values from one locale not from other here is my code so far
dispatcherServlet
<mvc:annotation-driven enable-matrix-variables="true" />
<context:component-scan base-package="com.*" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>/com/resources/messages_en</value>
<value>/com/resources/messages_nl</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
</mvc:interceptors>
and this is I am using in my page.jsp
<%# taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<p>
<b><h3>
English| Dutch
</h3></b>
</p>
<spring:message code="tagline"></spring:message>
<hr>
</body>
</html>
For English, everything works fine but while clicking on Dutch its also showing English too, how to resolve that?
this is only data in my files :
1 message_en.properties
tagline=This is English
2 message_nl.properties
tagline=This is dutch
Please Help
Do you have <mvc:annotation-driven /> in you config. Also your <mvc:interceptors> should be like below.
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
</mvc:interceptor>
</mvc:interceptors>
And MessageSource bean
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
Your properties file should be like below.
messages.properties
messages_en_US.properties
messages_zh_CN.properties
Check this post.

How to delete useless JSP

On the website that I'm developping, I'm using a lot of Ajax calls to display informations.
Theses Ajax Call are as follow :
function deleteBookingAjax(rowId) {
$.ajax({
url : "deleteRent.htm",
type : "GET",
data : {
"rentId" : rowId
},
dataType : 'json',
cache : false,
success : function(response) {
if(response.error) {
showPopupMessage(response.error, true);
}
},
statusCode : {
500 : function() {
loggingMessage('Error 500');
reloadBookingTable();
},
404 : function() {
loggingMessage('Error 404');
reloadBookingTable();
}
}
});
}
To perform this call, I have also Controllers as follow :
#RequestMapping(value = "/deleteRent.htm")
public String deleteRent(Long rentId, HttpServletRequest request, HttpServletResponse response) {
if (rentId == null) {
return null;
}
try {
rentService.deleteRent(rentId);
} catch (Exception e) {
LOGGER.error(e);
}
response.setStatus(HttpStatus.SUCCESS);
return ViewNames.BOOKINGS_PAGE;
}
But my problem is that : to perform this Ajax call, I need to create a useless JSP file : WEB-INF/jsp/deleteRent.jsp
<%#page import="net.****.****.web.controllers.RentControllers"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
If I don't create theses files, the Ajax call is not working...
When the file is not in the WEB-INF/ The Ajax call returns :
GET http://127.0.0.1/deleteRent.htm?rowId=1 404 (Not Found)
And the logs are showing :
2015-07-31 10:47:39,084 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Could not complete request
javax.servlet.ServletException: File "/WEB-INF/jsp/deleteRent.jsp" not found
at org.apache.jasper.servlet.JspServlet.handleMissingResource(JspServlet.java:417)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:384)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
....
How can I make it work without theses files (I assume it will be in configurations... but where exactly and how ?), because it's not convinient to have a lot of JSP files but when only few of them have contents...
EDIT
Here is the content of my context.xml, if the errror is located there, we never know :
<!-- resources exclusions from servlet mapping -->
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/scripts/**" location="/scripts/" />
<mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**" />
<!-- Enables the Spring MVC #Controller programming model -->
<context:component-scan base-package="net.****.****.web" />
<context:annotation-config />
<mvc:annotation-driven />
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:/META-INF/messages_en.properties</value>
</list>
</property>
</bean>
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/jsp directory -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<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/jsp/" />
<property name="suffix" value=".jsp" />
<property name="alwaysInclude" value="true" />
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>
<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
Thanks in advance. :)
I am not quite sure if you are looking for this, but you can include below into your applicationContext.xml or your *****-servlet.xml file.
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Add this into your pom. Now you can return String from your method.
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.10</version>
</dependency>
The answer is stupid :) but at least it's fixed now :
Putting : void to the function fixed the problem.
I deleted the empty file and working without :).
#RequestMapping(value = "/deleteRent.htm")
public void deleteRent(Long rentId, HttpServletRequest request, HttpServletResponse response) {
if (rentId == null) {
return null;
}
try {
rentService.deleteRent(rentId);
} catch (Exception e) {
LOGGER.error(e);
}
response.setStatus(HttpStatus.SUCCESS);
}

How to use CDN in Spring MVC

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

Spring MVC the default Locale and Locale change doesn't work

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;
}

Categories