Spring MVC國際化和整合Freemarker的國際化
阿新 • • 發佈:2019-01-28
package com.lwp.controller; import java.io.IOException; import java.util.Locale; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.support.RequestContext; @Controller @RequestMapping("/locale") public class LocaleController { @RequestMapping("/login") public String login(){ return "/login"; } @Autowired private LocaleResolver localeResolver; @RequestMapping("/change") @ResponseBody public String setSession(HttpServletRequest request,HttpServletResponse response,String locale){ try { //這兩個配置任選其一,可以不加if判斷刪除其一 我這裡是任意配置session或者cookie修改配置後不需變程式碼 //<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/> if(localeResolver instanceof org.springframework.web.servlet.i18n.SessionLocaleResolver){ String[] localeArr = locale.split("_"); Locale l = null; if(localeArr.length == 1){ l = new Locale(localeArr[0]); }else{ l = new Locale(localeArr[0],localeArr[1]); } localeResolver.setLocale(request, response, l); //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, l); //功能同上 System.out.println("SessionLocaleResolver"); } //<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/> if(localeResolver instanceof org.springframework.web.servlet.i18n.CookieLocaleResolver){ Cookie cookie = new Cookie(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, new Locale(locale).toString()); cookie.setMaxAge(5); response.addCookie(cookie); response.flushBuffer(); System.out.println("CookieLocaleResolver"); } } catch (Exception e) { e.printStackTrace(); return "error"; } return "success"; } /** * 後臺根據國際化編碼返回資訊 * @param response * @param request */ @RequestMapping("returnMessage") public void returnMessage(HttpServletResponse response,HttpServletRequest request){ RequestContext rc = new RequestContext(request); String w = rc.getMessage("loginFrom.username"); //根據locale不同返回不同語言 try { response.getWriter().write(w); } catch (IOException e) { e.printStackTrace(); } } }