Spring MVC basic Knowledge collation internationalization and exception handling

Source: Internet
Author: User
Tags i18n locale

Overview

   The spring Framework provides internationalization and exception handling mechanisms for Web projects. The so-called internationalization is a different nationality, showing the language and symbols of different nationalities. Exception handling, which is the ability to capture all exception information under a Web project, and to handle the mechanism of recording these exception information.

Internationalization

  Spring is configured to store the Internationalized language in the configuration file, and in the Springservletconfig.xml file, add the following statement:

<bean id="Messagesource" class="Org.springframework.context.support.ResourceBundleMessageSource"> <!--internationalization information file name-<property name="basename"Value="Messages"/> <!--If the corresponding code is not found in the Internationalized resource file, use this code as the name--<property name="Usecodeasdefaultmessage"Value="true"/> </bean>

Spring MVC is internationalized in a way that can be based on session or cookie, which is mainly based on session completion internationalization, in Springservletconfig.xml add the following interceptor configuration

<mvc:interceptors>          <!--international Operation Interceptor If you are using (Request/session/cookie), you must configure--         class=" Org.springframework.web.servlet.i18n.LocaleChangeInterceptor " />      </mvc:interceptors>      <!--based on session internationalization--    <bean id="  Localeresolver"class="  Org.springframework.web.servlet.i18n.SessionLocaleResolver" />

<!--based on cookie internationalization
<bean id= "Localeresolver" class= "Org.springframework.web.servlet.i18n.CookieLocaleResolver"/>-->

  In the current directory, add the following files, Messages.properties, messages_zh_cn.properties, messages_en_us.properties three files, of which messages.properties , Messages_zh_cn.properties;

Messages_en_us.properties:

umoney=moneyudate=date

Messages_zh_cn.properties:

umoney=  balance udate= Date

The controller code is as follows:

@RequestMapping ("/cuser")     PublicString Showuser (httpservletrequest request, HttpServletResponse Response,model Model,
@RequestParam (value="Langtype", defaultvalue="ZH") String langtype) {UserInfo Usermodel=NewUserInfo (); Sessionlang (Request, Langtype); //Cookielang (request,response,langtype);RequestContext rq=NewRequestContext (Request); Model.addattribute ("udate", Rq.getmessage ("udate")); Model.addattribute ("Umoney", Rq.getmessage ("Umoney")); return "Fuser/cuser"; } /** * @Title: Sessionlang * @Description: Session-based internationalization * @param @param request * @param @param langtype Set file * @return void return type * @throws*/ Public voidSessionlang (httpservletrequest request,string langtype) {if(Langtype.equals ("ZH") {locale locale=NewLocale ("ZH","CN"); Request.getsession (). SetAttribute (Sessionlocaleresolver.locale_session_attribute_name,locale); } Else if(Langtype.equals ("en") {locale locale=NewLocale ("en","US"); Request.getsession (). SetAttribute (Sessionlocaleresolver.locale_session_attribute_name,locale); } Elserequest.getsession (). SetAttribute (Sessionlocaleresolver.locale_session_attribute_name,localecontextholder . GetLocale ()); } /** * @Title: Cookielang * @Description: Cookie-based internationalization * @param @param request * @param @param response * @param @param langtype settings file * @return void return type * @throws*/ Public voidCookielang (httpservletrequest request,httpservletresponse response,string langtype) {locale locale=NULL; if(Langtype.equals ("ZH") {locale=NewLocale ("ZH","CN"); } Else if(Langtype.equals ("en") {locale=NewLocale ("en","US"); } Else{locale=Localecontextholder.getlocale (); } (Newcookielocaleresolver ()). SetLocale (Request, response, locale); }

Front JSP page

<% @taglib prefix="Spring"Uri="Http://www.springframework.org/tags"%>"Content-type"Content="text/html; Charset=utf-8"><title>insert title here</title>"Cuser?langtype=zh"> Chinese </a> | <a href="cuser?langtype=en"> English </a><br/>The following shows the internationalization information obtained in the background:<br/>${umoney}<br/>${udate}<br/> </body>

Exception handling

 There are 2 kinds of MVC Spring exception handling, one is to write a class inheritance handlerexceptionresolver, in the configuration file, add the bean configuration, another way, you can define the base class controller, write exception handling common methods, Subclass inherits the base class controller. The code is configured as follows

Write the base class controller:

 package Justin.com.controllers;import javax.servlet.http.HttpServletRequest; Import Org.springframework.web.bind.annotation.ExceptionHandler;  public   abstract  class   Basecontroller {@ExceptionHandler  public
     String exception (HttpServletRequest request,exception ex) {Request.setattri Bute (  exceptionmessage   "  return   "   ; }}

Subclass Inherits Basecontroller

Package Justin.com.controllers;import Javax.servlet.http.httpservletrequest;import Org.apache.catalina.connector.request;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.requestparam;import org.springframework.web.servlet.modelandview;@ Controller@requestmapping ("/helloworld") Public classHelloworldcontroller extends Basecontroller {@RequestMapping (value={"/*","/say"},method=requestmethod.get) PublicModelandview China () throws SQLException {Modelandview Modelandview=NewModelandview (); Modelandview.addobject ("message","Hello world!"); Modelandview.setviewname ("Helloworld/cindex"); intresult=Ten/0; returnModelandview; }}

When the page is opened, the page automatically jumps to the error controller and completes the data's exception capture and display.

  

Spring MVC basic Knowledge collation internationalization and exception handling

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.