spring framework mvc localization - spring

I am trying to add Internationalization and Localization support to our Spring MVC application.
I made encoding like this in *-servlet.xml
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
But I found wrong character like below
I cannot figure out what problem I should fix it. If possible, please let me know.
I've already added in jsp page like this:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
But it doesn't work.

The defaultEncoding property of ReloadableResourceBundleMessageSource is used to
Set the default charset to use for parsing properties files. Used if
no file-specific charset is specified for a file.
It has no bearing on how the client is reading the response. If you are generating your response with a jsp, you can give it this line at the start
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
so that the client knows that you are providing data encoded with the UTF-8 charset.
If you are not using a jsp, there are other ways to set the content-type or content-encoding, directly from HttpServletResponse or from a returned ResponseEntity object.

update your default encoding with:
<property name="defaultEncoding" value="ISO-8859-1" />
and this should work for rendering characters with accents.
At least it works on my spring projects (french and european languages/users)
If this is not an option for you (bigger audience of targetted users) try to add this in your jsp:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
...
</head>

Related

fmt formatNumber type="currency" shows "¤" instead of actual currency symbol

I have the following code to show an amount as currency:
<fmt:formatNumber type="currency" value="${camp.montoTotal}"/>
When I run the application in Eclipse (actually I am using STS), it looks good: "$500".
But when I deploy the WAR file to the server (using Tomcat8 on Ubuntu LTS 14.04), it shows "¤500", i.e., shows the generic currency marker instead of the actual sign. I tried to force the locale with:
<META http-equiv="Content-Language" content="es-AR">
<fmt:setLocale value="es-AR"/>
but with the same result. Why can it be?
I finally found the answer!!
Originally I had the messageSource bean configured in the app-config xml. When I moved it to the applicationContext xml, the problem was solved. I had to do this because I also had problems when trying to access message properties in the controller with getMessage function.
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
Conclusion: messageSource must be configured in the application context, not in the root configuration xml.
first, you need to import the tag library:
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
next, set the country with setLocale
<fmt:setLocale value="es-AR"/>
then you can format the number with formatNumber tag
<fmt:formatNumber value="${camp.montoTotal}" type="currency" currencySymbol="$"/>
in the attribute you can add the currencySymbol that you want to use.
Hope it helps you.
Regards,

How to use Spring Webflow popup="true" with Primefaces?

Until now we were using Spring Webflow 2.3, which brought the "sf" namespace and Spring.js, which could be used to display view-states in a popup.
Webflow 2.4 deprecated Spring.js and removed the taglib with the following statement:
Previous releases of Spring Web Flow shipped with a component library which provided Ajax and client-side validation capabilities for JSF 1.2 environments. Applications using these components will need to switch to a 3rd party JSF component library such as PrimeFaces or RichFaces.
See: http://docs.spring.io/spring-webflow/docs/current/reference/htmlsingle/#spring-faces-upgrade-from-swf23-components
Now i have added a dependency to Primefaces 5.2 to my pom.xml and everything seems to work fine, except for SWF Popups, which simply redirect to the new view-state.
First page:
<ui:composition template="#{templatePath}"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<ui:define name="content">
<h:form id="formDashboard">
<p:commandButton id="addWidget" value="Hinzufügen" action="add-widget"/>
</h:form>
</ui:define>
</ui:composition>
Second page (should be rendered in a popup):
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:fragment id="popupFragment">
abc
</ui:fragment>
</ui:composition>
Flow definition:
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow.xsd">
<view-state id="start" view="dashboard.xhtml">
<transition on="add-widget" to="popup-addWidget"/>
</view-state>
<view-state id="popup-addWidget" view="popup-addWidget.xhtml" popup="true">
<on-render>
<render fragments="popupFragment"/>
</on-render>
</view-state>
</flow>
Spring configuration:
<bean class="org.springframework.faces.webflow.JsfFlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor"/>
</bean>
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry"/>
</bean>
<webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">
<webflow:flow-execution-listeners>
<webflow:listener ref="facesContextListener"/>
</webflow:flow-execution-listeners>
</webflow:flow-executor>
<webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices"/>
<!-- Populates the flowRegistry on startup. Removing this and manually adding all flows changes nothing. -->
<bean class="config.FlowRegisteringBeanPostProcessor"/>
<faces:flow-builder-services id="flowBuilderServices"/>
<faces:resources/>
<bean id="facesContextListener" class="org.springframework.faces.webflow.FlowFacesContextLifecycleListener"/>
I'm not including the web.xml, since there is nothing special.
Using Mojarra 2.2, Primefaces 5.2, Spring 4.2 and Webflow 2.4.1.
Using Firebug i can see that the server POST response issues to redirect, which JSF/Primefaces honors and does a full redirect to the new view-state instead of showing a popup:
<?xml version='1.0' encoding='UTF-8'?>
<partial-response id="j_id1"><redirect url="/Demo/spr/dashboard?execution=e1s2"></redirect></partial-response>
If anybody managed to get popup="true" working with these versions, with or without Spring.js, i'd be happy to hear about it.
We ended up using Primefaces' p:dialog and p:confirmDialog, instead of Webflow popups.
This doesn't really answer my question, but i can't see an answer to this seeing that Webflow sends the same response no matter if popup is set to true or false.

Can Spring help to prevent caching of html pages on the browser?

I have a Java/Spring 3.x webapp that uses ExtJS and I use the Sencha Architect to create the front end which results in an automatically generated app.html file that loads in the JS and CSS resources that looks like this:
<!DOCTYPE html>
<!-- Auto Generated with Sencha Architect -->
<!-- Modifications to this file will be overwritten. -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ui</title>
<script src="ext/ext-all.js"></script>
<script src="ext/ext-theme-neptune.js"></script>
<link rel="stylesheet" href="ext/resources/ext-theme-neptune/ext-theme-neptune-all.css">
<link rel="stylesheet" href="css/custom.css">
<script type="text/javascript" src="app.js"></script>
</head>
<body></body>
</html>
I want to protect this html file with Spring security and this seems to work except that it is often cached in the browser so that it appears to reload even when the user is not logged in. Here is my Spring XML that configures security for my webapp:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/ui/app.html" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/ui/**" access="permitAll" />
<form-login
login-page="/login"
default-target-url="/ui/app.html"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<csrf/> <!-- enable csrf protection -->
</http>
<authentication-manager>
<authentication-provider >
<user-service>
<user name="test" password="test" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
As you can see I have configured it to protect the ui/app.html resource as well as redirect to that page after log in. This works fine until the browser caches the page and causes confusion when the user is logged out and tries to access the same URL.
I was wondering if Spring MVC could be used to load the page via a controller, perhaps modifying the HTTP headers to force the page to expire, but as this is a page that is normally delivered directly by the servlet container and not MVC I'm not sure how I would configure that.
I'd also like to be able to leave my app.html file in-situ as it uses resources that are relative to it, and it's also easier to leave it there when working with Sencha Architect.
This will prevent browser caching:
<http>
<!-- ... -->
<headers>
<cache-control />
</headers>
</http>
It adds Cache-Control, Pragma and Expires headers for every response. More information can be found in reference documentation, section Security HTTP Response Headers.
Update: This answer was written for version 3.2 of Spring Security. As of version 4, these headers are included by default.
You can choose one of the below which depends on how your application is going to serve the resource requests.
Using Spring Security
http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html#headers-cache-control
Using Extjs
http://www.sencha.com/forum/showthread.php?257086-Is-there-a-simple-way-to-disable-caching-for-an-entire-ExtJS-4-application
Using HTML
http://www.htmlgoodies.com/beyond/reference/article.php/3472881

Internationaization with Spring3

I am kind of struck here and wondering if there is any way out of this with less overhead. The issue I am facing is I have a JSP page with userID/Password textfileds and language as a dropdown box with two languages "EN", "ES".
When I provide user/password and select "ES" from the drop down I do a POST to the #Controller method save the values to DB for that user. Then I am adding the changed language to the the model object as
model.addAttribute("language", request.getParameter("language"));
The return type of the method is STRING (name of the next JSP page).
The expectation is the next JSP page should show up in Spanish. But it does not happen. I have the "LocaleChangeResolver" defined in my myapp-servlet.xml as below:
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
In my JSP I have the tablib defined:
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
The label I am trying to read from properties files is
<spring:message code="label.formName"/>
Can anyone help me here why the change of language is not being picked up by the JSP instead still shows the text in English instead of Spanish....
Thanks in Advance.
There are several things to do if you want your program to "speak" in different languages.
For example I have the following configuration in my applicationContext.xml:
<!-- Locale settings -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- My file with messages are: messages_en.properties (for English) and messages_lt.properties (for Lithuanian) -->
<property name="basename" value="classpath:messages"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"/>
</bean>
<!-- I'm resolving my locale according to browser's Cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="lt"/>
</bean>
In my case I have two files: messages_lt.properties and messages_en.properties. In your case you need to create files called messages_en.properties (for English) and messages_es.properties (for Spanish). Each file should contain:
# messages_en.properties
label.formName=My form
and
# messages_es.properties
label.formName=Mi forma
Then (as you mentioned) you need to add taglib in your JSP page and use it:
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<...>
<spring:message code="label.formName"/>
Hope this helps :)
EDIT: Nice tutorial at MKYONG.com: http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/

Character-encoding problem spring

I am stuck in a big problem with encoding in my website!
I use spring 3, tomcat 6, and mysql db. I want to support German and Czech along with English in my website, I created all the JSPs as UTF-8 files, and in each jsp I include the following:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
I created messages.properties (the default which is Czech), messages_de.properties, and messages_en.properties. And all of them are saved as UTF-8 files.
I added the following to web.xml:
<filter>
<filter-name>encodingFilter</filter-name>
<filterclass>
org.springframework.web.filter.CharacterEncodingFilter</filterclass>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<locale-encoding-mapping-list>
<locale-encoding-mapping>
<locale>en</locale>
<encoding>UTF-8</encoding>
</locale-encoding-mapping>
<locale-encoding-mapping>
<locale>cz</locale>
<encoding>UTF-8</encoding>
</locale-encoding-mapping>
<locale-encoding-mapping>
<locale>de</locale>
<encoding>UTF-8</encoding>
</locale-encoding-mapping>
</locale-encoding-mapping-list>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And add the following to my applicationContext.xml:
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basenames="messages"/>
<!-- Declare the Interceptor -->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
p:paramName="locale" />
</mvc:interceptors>
<!-- Declare the Resolver -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
I set the useBodyEncodingForURI attribute to true in the element of server.xml under: %CATALINA_HOME%/conf, also another time tried to add URIEncoding="UTF-8" instead.
I created all the tables and fields with charset [utf8] and collection [utf8_general_ci]
The encoding in my browser is UTF-8 (BTW, I have IE8 and Firefox 3.6.3)
When I open the MYSQL Query browser and insert manually Czech or German data, it's being inserted correctly, and displayed correctly in my app as well.
So, here's the list of problems I have:
By default the messages.properties (Czech) should load, instead the messages_en.properties loads by default.
In the web form, when I enter Czech data, then click submit, in the Controller I print out the data in the console before to save it to db, what's being printed is not correct having strange chars, and this is the exact data that saves to db.
I don't know where's the mistake! Why can't I get it working although I did what people did and worked for them! don't know..
Please help me, I am stuck in this crappy problem since days, and it drives me crazy!
Thank you in advance.
First, if your project is using Maven, make sure that the Maven Resources Plugin has UTF-8 set as its character encoding scheme, otherwise the message properties files could be written to your target with an incorrect encoding.
Second, you're using ResourceBundleMessageSource, which uses the standard java.util.ResourceBundle and java.util.Properties, which only support ISO-8859-1 encoding. You can instead use ReloadableResourceBundleMessageSource like:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
which I discovered from this Cake Solutions blog post.
If this still does not work and you're using Tomcat as your application server try to set the following option on every <Connector> element in the server.xml:
<Connector URIEncoding="UTF-8" ...>
...
</Connector>
This did the trick for me. There might be similar options for other application servers, so you might want to check the server documentation.
1: By default the messages.properties (Czech) should load, instead the messages_en.properties loads by default.
I don't do Spring, so here's a shoot in the dark: maybe because English is ordered first and/or your platform/browser uses English as default locale? Rearrange the configuration and check accept-language in the HTTP request header to exclude one and other.
2: In the web form, when I enter Czech data, then click submit, in the Controller I print out the data in the console before to save it to db, what's being printed is not correct having strange chars, and this is the exact data that saves to db.
Is the console configured to use UTF-8 to display data? It would use the platform default encoding otherwise. In for example Eclipse you can configure it by Window > Preferences > General > Workspace > Text File Encoding.
Is the data access layer configured properly to handle the data as UTF-8? MySQL JDBC driver is known to be a bit non-smart in this. It won't use the DB-specified encoding, but the client platform default encoding. To the point, you'd like to use the useUnicode=true and characterEncoding=UTF-8 properties in the JDBC connection string. E.g.
jdbc:mysql://localhost/some_db?useUnicode=yes&characterEncoding=UTF-8

Resources