Showing posts with label Spring MVC. Show all posts
Showing posts with label Spring MVC. Show all posts

Monday, 14 October 2013

Internationalization Using Spring MVC



Spring MVC Internationalization

Questions:-What is i18n (internationalization) and L10n (localization)?

Answer:- According to computer vocabulary, i18n means internationalization and L10n means localization. Here, in i18n -18 belongs to the number of letters between the first i and the last n in the word internationalization. Similarly, In L10n - 10 belongs to the number between the first L and last n in the word localization.
                                                            With the help of internationalization and localization, we can make software in different languages; even we can use it in our regional languages. A process through which software can adapt to various languages and regions without re- engineering is known as internationalization. Similarly, A process through which internationalized software can adapt a specific region or language by adding locale-specific components and translating text.
Spring MVC module, comes with few “LocaleResolver” which support s the internationalization or multiple languages features.

Spring Configuration
 
if we want to use Spring MVC module for supporting the internationalization, then in this case we have to register two beans.

Local Resolvers
 
it’s a component capable of resolving the locale and offer internationalized views which is used by a client. org.springframework.web.servlet.i18nis the package where Locale resolvers and interceptors are available and are configured in your application context in the normal way like other beans. All Known Implementing Classes are AbstractLocaleResolver, AcceptHeaderLocaleResolver,  CookieLocaleResolver, FixedLocaleResolver, SessionLocaleResolver

 SessionLocaleResolver

We have to register a “SessionLocaleResolver” bean. While registering this resolver the bean-id should be exactly the same as “localeResolver”, because it’s a predefined attribute from user’s session. For example:-
<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en"/>
</bean>

AcceptHeaderLocaleResolver

Important Fact:

If we will not register any “localeResolver”, then the default AcceptHeaderLocaleResolver will be used, which resolves the locale by checking the accept-language header in the HTTP request. This header field contains the locale of the client's operating system. This is the default locale resolver and in order to use this locale resolver, we don't require configuring anything in spring configuration file.This locale resolver inspects the accept-language header in the request that was sent by the browser of the client.


CookieLocaleResolver

This locale resolver inspects a Cookie that might exist on the client, to see if a locale is specified. If so, it uses that specific locale. Using the properties of this locale resolver, you can specify the name of the cookie, as well as the maximum age. Find below an example of defining a CookieLocaleResolver.

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">

    <property name="cookieName" value="clientlanguage"/>
   
    <!-- in seconds. If set to -1, the cookie is not persisted (deleted when browser shuts down) -->
    <property name="cookieMaxAge" value="100000">

</bean>

CookieLocaleResolverproperties

Property
Default
Description
cookieName
classname + LOCALE
The name of the cookie
cookieMaxAge
Integer.MAX_INT
The maximum time a cookie will stay persistent on the client. If -1 is specified, the cookie will not be persisted. It will only be available until the client shuts down his or her browser.
cookiePath
/
Using this parameter, you can limit the visibility of the cookie to a certain part of your site. When cookiePath is specified, the cookie will only be visible to that path, and the paths below it.

  
LocaleChangeInterceptor

This Interceptor will allow for changing the current locale on every request, via a configurable request parameter. We have to register a “LocaleChangeInterceptor” and reference it to any handler mapping that need to supports the multiple languages. The “paramName” is the parameter value that’s used to set the locale. It calls setLocale() on the LocaleResolver that also exists in the context. All calls containing a parameter named siteLanguage will now change the locale. So a request for the following URL, http://localhost:7075/SpringMVCInternationalization/index.htm?siteLanguage=es will change the site language to Spanish.

Note: - siteLanguage is the value which we are passing against paramName attribute of LocaleChangeInterceptor.


Method Summary
 boolean
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
          This implementation always returns true.
 void
setParamName(String paramName)
          Set the name of the parameter that contains a locale specification in a locale change request.


In this case,

index.htm?
siteLanguage=en – Get the message from English properties file.
index.htm?
siteLanguage=es – Get the message from Spanish properties file.


<bean id="localeChangeInterceptor"
      class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="siteLanguage"/>
</bean>
 
<bean id="localeResolver"
    class=" org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
 
<bean id="urlMapping"
      class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="localeChangeInterceptor"/>
        </list>
    </property>
</bean>

<!-- Registering the bean -->
            <bean class="com.gaurav.spring.internationalization.controller.WelcomeController" />

            <!-- Registering the message properties files-->

            <bean id="messageSource"                  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
                         <property name="basenames">  
 <list>  
<value>/WEB-INF/resourcebundle/messages</value>  
</list>  
                        </property>                
<property name="defaultEncoding" value="UTF-8"/>
            </bean>

            <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    

welcome_en.properties

welcome.springmvcinternationalization = Welcome in England

welcome_es.properties

welcome. springmvcinternationalization = Welcome in Spain

We have to code Like below in the JSP page in order to use Internationalization.

<spring:message code=" welcome.springmvcinternationalization " text="default text"/>  

Saturday, 7 September 2013

Spring MVC Flow Description

About Spring MVC






Figure Description:- A registration request is sent by DispatchServlet to the RegsitrationController(as figure out or directed by BeanNameUrlHandlerMapping). As a result, InternalResourceViewResolver directs the request to reg.jsp to render the page output.

Spring MVC flow steps:-
  • DispatcherServlet receives a request whose URL pattern is /reg.htm. This is the first stop in the request’s travels. This works on the Front Controller design pattern. It is a common web-application pattern where a servlet delegates responsibility for a request to other components of an application to perform the actual processing. Here the DispatcherServlet job is to send the request on to a spring MVC controller. A controller is nothing but a spring component that processes the request. But an application contains multiple controllers and then DispatcherServlet needs help to decide which controller can able to serve the coming request.
  • DispatcherServlet consults BeanNameUrlHandlerMapping(as per the above case) to find the corresponding controller whose bean name is /reg.htm and it finds the RegistrationController bean.
  • DispatcherServlet dispatches the request to RegistrationController for processing.
  • The logic performed by a controller often results in some required information that needs to be carried back to the client/user and displayed in the browser. This information is reffered to as the model. But sending the raw information is not the sufficient and correct way. It needs to be formatted in a user-friendly format. So the last thing that the controller will do is packaging the model data and the name of a view into a ModelAndView object. RegistrationController then returns a ModelAndView object with a logical view name that is reg.jsp. As the name implies, ModelAndView object containsboth the model data as well as a hint to what view should be returned to render the screen.
  • The ModelAndView object does not contain the actual JSP, it only carries a logical name that will be used to look up the actual view. So once the ModelAndView object is delivered to the DispatcherServlet then the DispatcherServlet take helps of ViewResolver to find the actual JSP. The DispatcherServlet consults its view resolver(configured as InternalResourceViewResolver in the above case) to find a view whose logical name is reg. InternalResourceViewResolver returns the path to /WEB-INF/jsp/reg.jsp.
  • Now the DispatcherServlet knows which view will render the results, so the final stop is at the view implementation where it delivers the model data. Now the view will use the model data to render a page that will be carried back to the client by the response object. In the above scenario, DispatcherServlet forwards the request to the JSP at /WEB-INF/jsp/reg.jsp to render the user page as the response.
 
More on WebServices                                                                                                More on Spring Core