Spring and SPRINGMVC internationalization applications

Source: Internet
Author: User
Tags getmessage i18n

Objective:

@1 the text displayed in the view layer is internationalized

@2 Show internationalization after data validation

@3 allows customers to automatically select internationalization via hyperlink parameters

1: Configure internationalization classes in Spring.xml to allow container management internationalization

2: Display internationalization on the page: You can use the spring label <st:message code= "UserName" ></st:message>

@2 Data validation

1: Code-level Data validation: Automatic assembly Messagesource source Java code layer gets error messages in different languages based on different regions and adds error messages to the results

2: Attribute class data validation: Use custom data validation annotations, create bean,l in springmvc.xml to set attribute data validation, and reference internationalized Messagesource to make data validation internationalized

@3: Use the Localechangeinterceptor interceptor to intercept the value of the specified parameter, and then use the Sessionlocaleresolver override to store the value of the locale by default in the session

Spring.xml

<!--internationalization ID must be the second two words, the first word---    <bean id= "Messagesource"        class= " Org.springframework.context.support.ResourceBundleMessageSource ">        <property name=" basename ">            <value>/ui</value>        </property>    </bean>

Jsp

<% @pageImport= "java.util.List"%><%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding= "UTF-8"%><% @taglib uri= "Http://www.springframework.org/tags/form" prefix= "s"%> <% @taglib uri= "/http Www.springframework.org/tags "prefix=" St "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >function $ (name) {returndocument.getelementsbyname (name); }  /*front-end authentication reduces server stress by verifying poor security before jumping to a background server*/function Checkform () {var userName=$ ("UserName") [0].value; /**if (username==null | | username== ") {alert (' Please enter user name ');      Return }**/document.forms[0].submit (); }</script>Mail<input type= "text" name= "email"/> <font color= "Red" ><s:errors path= "User.email" ></s:errors> </font><br/>Password<input type= "password" name= "password"/><s:errors path= "User.password" ></s:errors><br/>Password again<input type= "Password" name= "Repassword"/> <s:errors path= "User.repassword" ></s:errors><br/ > <input type= "button" onclick= "Checkform ()" value= "Commit"/><br/> &LT;/FORM&GT;&LT;/BODY&GT;&LT;/HTML&G T

@2: Automatic assembly

 PackageCom.crazy.goods.tools.validator;ImportJava.util.HashMap;ImportJava.util.Locale;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportJavax.validation.Valid;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.context.MessageSource;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;ImportOrg.springframework.ui.ModelMap;ImportOrg.springframework.validation.BindingResult;ImportOrg.springframework.validation.FieldError;ImportOrg.springframework.web.bind.annotation.ModelAttribute;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView; @Controller Public classvaldaction {@AutowiredPrivateMessagesource Source; /*** When the entity validation fails for the @valid annotation * All error messages are injected into the Bindingresult object * You can also use ${userinfo.name} on the JSP to get the value of the object * display Error when the path of the SPRINGMVC tag is by the object name (the first letter of the class name is lowercase). The Property name * @ModelAttribute ("user") can be used alone, without having to use the property with @valid to modify the object name on the page using the object's properties gets the value is placed in the The request area * @ Sessionattribute exists in the session area, generally does not use * 3 ways to pass data into the model * 1:new Modelandview (" Vald/suc ", map) * 2:model.addattribute () * 3:modelmap.put () He is a subclass of HashMap * *@paramUser *@paramresult *@return* @Valid Note: When the SPRINGMVC call, see the parameter has this annotation, will run to the attribute class to verify, if the validation fails, will be the failure of information in the Bindingresult class * @Valid UserInfo user such as @modelattribute (name= "user") the first letter of the object is lowercase userInfo*/@RequestMapping (Value= "/formvalidate")     PublicString User (@ModelAttribute (name= "User") @Valid UserInfo user,bindingresult Result,locale Locale) {if(!User.getpassword (). Equals (User.getrepassword ())) {
Get error messages for different languages based on different regions and add error messages to the results String errormsg=source.getmessage ("Passworderror",NULL, Locale); Result.adderror (NewFielderror ("User", "Repassword", errormsg)); } if(Result.haserrors ()) {return"Vald/form"; } return"Vald/suc"; } @RequestMapping (Value= "/formvalidate1") PublicString uploadpage () {return"Vald/form"; } /*** Demonstrates the non-coupled way to pass data * Request.setattribute () coupling *//model pass the key value pair actually store request.setattribute ("Sex", "male"); * @paramUser *@paramresult *@return */@RequestMapping (Value= "/model") PublicModelandview Model (HttpServletRequest request) {//request.setattribute ("Sex", "male");Map map=NewHashMap (); Map.put ("Age", 100); Map.put ("Sex", "male"); Modelandview Mav=NewModelandview ("Vald/suc", map);//The key-value pairs passed by model actually store request.setattribute ("Sex", "male"); returnMav; } /*** Demonstrates the non-coupled way to pass data * Request.setattribute () coupling * *@paramUser *@paramresult *@return */@RequestMapping (Value= "/model1") PublicString Model (model Model,modelmap mm) {//request.setattribute ("Sex", "male");Model.addattribute ("Age", 100); Model.addattribute ("Sex", "male"); Mm.put ("Name", "ZS"); return"Vald/suc"; } }

@2 2//springmvc.xml set attribute data validation, and reference internationalization Messagesource, to enable data validation to achieve international results

<!-- SPRINGMVC The default validation is to instantiate an instance of Localvalidatorfactorybean that does not achieve internationalization by manually creating an instance         of the class-    <bean Id= "Myvlidat"        class= "Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" >        <property name= "Validationmessagesource" ref= "Messagesource" ></property>    </bean>  

@3

<!-- If this class is referenced, then the value that the i18n interceptor obtains is called Acceptheaderlocaleresolver storage does not support         storage SetLocale--    <bean id= "Localeresolver"        class= "Org.springframework.web.servlet.i18n.SessionLocaleResolver" ></bean >    <mvc:interceptors>        <!-- defines the i18n interceptor used to get the locale object in the request header ZH_CN by default gets the value of Request_locale called Acceptheaderlocaleresolver             --        class= " Org.springframework.web.servlet.i18n.LocaleChangeInterceptor ">            <property name=" paramname "value=" Request_locale "></property>        </bean>    </mvc:interceptors>-

Action

 PackageCom.crazy.goods.tools.validator;ImportJava.util.HashMap;ImportJava.util.Locale;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportJavax.validation.Valid;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.context.MessageSource;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;ImportOrg.springframework.ui.ModelMap;ImportOrg.springframework.validation.BindingResult;ImportOrg.springframework.validation.FieldError;ImportOrg.springframework.web.bind.annotation.ModelAttribute;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.servlet.ModelAndView; @Controller Public classvaldaction {@AutowiredPrivateMessagesource Source; /*** When the entity validation fails for the @valid annotation * All error messages are injected into the Bindingresult object * You can also use ${userinfo.name} on the JSP to get the value of the object * display Error when the path of the SPRINGMVC tag is by the object name (the first letter of the class name is lowercase). The Property name * @ModelAttribute ("user") can be used alone, without having to use the property with @valid to modify the object name on the page using the object's properties gets the value is placed in the The request area * @ Sessionattribute exists in the session area, generally does not use * 3 ways to pass data into the model * 1:new Modelandview (" Vald/suc ", map) * 2:model.addattribute () * 3:modelmap.put () He is a subclass of HashMap * *@paramUser *@paramresult *@return* @Valid Note: When the SPRINGMVC call, see the parameter has this annotation, will run to the attribute class to verify, if the validation fails, will be the failure of information in the Bindingresult class * @Valid UserInfo user such as @modelattribute (name= "user") the first letter of the object is lowercase userInfo*/@RequestMapping (Value= "/formvalidate")     PublicString User (@ModelAttribute (name= "User") @Valid UserInfo user,bindingresult Result,locale Locale) {if(!User.getpassword (). Equals (User.getrepassword ())) {String errormsg=source.getmessage ("Passworderror",NULL, Locale); Result.adderror (NewFielderror ("User", "Repassword", errormsg)); }        if(Result.haserrors ()) {return"Vald/form"; }        return"Vald/suc"; } @RequestMapping (Value= "/formvalidate1")     PublicString uploadpage () {return"Vald/form"; }        /*** Demonstrates the non-coupled way to pass data * Request.setattribute () coupling *//model pass the key value pair actually store request.setattribute ("Sex", "male"); * @paramUser *@paramresult *@return     */@RequestMapping (Value= "/model")     PublicModelandview Model (HttpServletRequest request) {//request.setattribute ("Sex", "male");Map map=NewHashMap (); Map.put ("Age", 100); Map.put ("Sex", "male"); Modelandview Mav=NewModelandview ("Vald/suc", map);//The key-value pairs passed by model actually store request.setattribute ("Sex", "male");        returnMav; }                /*** Demonstrates the non-coupled way to pass data * Request.setattribute () coupling * *@paramUser *@paramresult *@return     */@RequestMapping (Value= "/model1")     PublicString Model (model Model,modelmap mm) {//request.setattribute ("Sex", "male");Model.addattribute ("Age", 100); Model.addattribute ("Sex", "male"); Mm.put ("Name", "ZS"); return"Vald/suc"; }            }

Spring and SPRINGMVC internationalization applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.