熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

struts標簽+jstl標簽之國際化實例

2022-06-13   來源: Java開源技術 

  Struts提供了國際化的功能對於一個面向各國的系統來說是非常有幫助的只需要提供每個國家的語言資源包配置後即可使用

  下面來用一個登錄實例來演示一下Struts的國際化配置和顯示

  創建一個login_in_exception的javaweb項目引入Struts的所有jar包以及jstljar和standardjar登錄界面無非就是輸入用戶名密碼所以ActionForm中只需要設置個屬性即可

  [java]

  package combjpowernodestruts;

  import orgapachestrutsactionActionForm;

  /**

  * 登錄ActionForm負責收集表單數據

  * 表單的數據必須和ActionForm的getset一致

  * @author Longxuan

  *

  */

  @SuppressWarnings(serial

  public class LoginActionForm extends ActionForm {

  private String username;

  private String password;

  public String getUsername() {

  return username;

  }

  public void setUsername(String username) {

  thisusername = username;

  }

  public String getPassword() {

  return password;

  }

  public void setPassword(String password) {

  thispassword = password;

  }

  }

  登錄時會驗證密碼是否正確需要提供異常處理本實例顯示個異常用戶名未找到密碼錯誤

  [java]

  package combjpowernodestruts;

  /**

  * 密碼錯誤異常

  * @author Longxuan

  *

  */

  @SuppressWarnings(serial

  public class PasswordErrorException extends RuntimeException {

  public PasswordErrorException() {

  // TODO Autogenerated constructor stub

  }

  public PasswordErrorException(String message) {

  super(message)

  // TODO Autogenerated constructor stub

  }

  public PasswordErrorException(Throwable cause) {

  super(cause)

  // TODO Autogenerated constructor stub

  }

  public PasswordErrorException(String message Throwable cause) {

  super(message cause)

  // TODO Autogenerated constructor stub

  }

  public PasswordErrorException(String message Throwable cause

  boolean enableSuppression boolean writableStackTrace) {

  super(message cause enableSuppression writableStackTrace)

  // TODO Autogenerated constructor stub

  }

  }

  package combjpowernodestruts;

  /**

  * 用戶未找到異常

  * @author Longxuan

  *

  */

  @SuppressWarnings(serial

  public class UserNotFoundException extends RuntimeException {

  public UserNotFoundException() {

  // TODO Autogenerated constructor stub

  }

  public UserNotFoundException(String message) {

  super(message)

  // TODO Autogenerated constructor stub

  }

  public UserNotFoundException(Throwable cause) {

  super(cause)

  // TODO Autogenerated constructor stub

  }

  public UserNotFoundException(String message Throwable cause) {

  super(message cause)

  // TODO Autogenerated constructor stub

  }

  public UserNotFoundException(String message Throwable cause

  boolean enableSuppression boolean writableStackTrace) {

  super(message cause enableSuppression writableStackTrace)

  // TODO Autogenerated constructor stub

  }

  }

  提供用戶管理類處理用戶的相關操作這裡主要處理用戶登錄

  [java]

  package combjpowernodestruts;

  /**

  * 用戶管理類

  * @author Longxuan

  *

  */

  public class UserManager {

  /**

  * 簡單處理登錄邏輯

  * @param username  用戶名

  * @param password  密碼

  */

  public void login(String usernameString password){

  if(!adminequals(username)){

  throw new UserNotFoundException()

  }

  if(! adminequals(password)){

  throw new PasswordErrorException()

  }

  }

  }

  現在寫LoginAction的處理

  [java]

  package combjpowernodestruts;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsactionActionMessage;

  import orgapachestrutsactionActionMessages;

  /**

  * 登錄Action 負責取得表單數據調用業務邏輯返回轉向信息

  *

  * @author Longxuan

  *

  */

  public class LoginAction extends Action {

  @Override

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response)

  throws Exception {

  //獲取數據

  LoginActionForm laf = (LoginActionForm) form;

  String username = lafgetUsername()

  String password = lafgetPassword()

  UserManager userManager = new UserManager()

  ActionMessages messages = new ActionMessages()

  try {

  //用戶登錄

  userManagerlogin(username password)

  //獲取登錄成功的國際化消息

  ActionMessage success= new ActionMessage(loginsuccessusername)

  messagesadd(login_success_success)

  //傳遞消息

  thissaveMessages(request messages)

  return mappingfindForward(success

  } catch (UserNotFoundException e) {

  eprintStackTrace()

  //獲取登錄成功的國際化消息

  ActionMessage error = new ActionMessage(loginusernotfoundusername)

  messagesadd(login_error_error)

  //傳遞消息

  thissaveErrors(request messages)

  } catch (PasswordErrorException e) {

  eprintStackTrace()

  //獲取登錄成功的國際化消息

  ActionMessage error = new ActionMessage(loginuserpassworderror

  messagesadd(login_error_error)

  //傳遞消息

  thissaveErrors(request messages)

  }

  return mappingfindForward(error

  }

  }

  來一個手動切換語言的類方便演示

  [java]

  package combjpowernodestruts;

  import javautilLocale;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  /**

  * 完成語言的手動切換

  * @author Longxuan

  *

  */

  public class ChangeLanguageAction extends Action {

  @Override

  public ActionForward execute(ActionMapping mapping ActionForm form

  HttpServletRequest request HttpServletResponse response)

  throws Exception {

  //獲取語言

  String lang = requestgetParameter(lang

  String[] split = langsplit(

  //設置語言

  Locale locale = new Locale(split[]split[])

  thissetLocale(request locale)

  return mappingfindForward(login

  }

  }

  新建國際化信息文件創建resource包創建 英文語言包MessageBundle_en_USproperties中文語言包MessageBundle_zh_CNproperties默認語言包MessageBundleproperties 這個語言包具體內容如下

  英文語言包和默認語言包設置成一樣的

  [java]

  # standard errors

  errorsheader=<UL>

  errorsprefix=<font color=red><LI>

  errorssuffix=</LI></font>

  errorsfooter=</UL>

  loginformfieldusername=User Name

  loginformfieldpassword=Password

  loginformbuttonlogin=Login

  loginsuccess={}Login Succedd!!

  loginusernotfound=Use cant be found! Username=[{}]

  loginuserpassworderror=Password  Error!

  中文語言包

  [java]

  # standard errors

  errorsheader=<UL>

  errorsprefix=<font color=red><LI>

  errorssuffix=</LI></font>

  errorsfooter=</UL>

  loginformfieldusername=\u\u\uD

  loginformfieldpassword=\uBC\u

  loginformbuttonlogin=\uB\uF

  loginsuccess={}\uFFC\uB\uF\u\uF\uFF

  loginusernotfound=\u\u\uA\uE\u\uFFC\u\u\uD\uFFA\u{}\u

  loginuserpassworderror=\uBC\u\u\uBEF

  把loginjsp源碼也貼出來

  [html]

  <%@ page language=java contentType=text/html; charset=GB

  pageEncoding=GB%>

  <%@ taglib uri=/tagsbean prefix=bean%>

  <%@ taglib uri=/tagshtml prefix=html%>

  <%@ taglib uri=/jsp/jstl/fmt prefix=fmt%>

  <! ${sessionScope[orgapachestrutsactionLOCALE]}可以獲取到當前設置的語言 >

  <fmt:setLocale value=${sessionScope[orgapachestrutsactionLOCALE]} />

  <fmt:setBundle basename=resourceMessageBundle />

  <html>

  <head>

  <meta httpequiv=ContentType content=text/html; charset=GB>

  <title>Struts登錄</title>

  </head>

  <body>

  <a >中文登錄</a>|

  <%<a >English Login</a><br>

  <html:link action=changelangdo?lang=zhcn>中文登錄</html:link>|%>

  <html:link action=changelangdo?lang=enus>English Login</html:link>

  <hr>

  <html:errors />

  <hr>

  <h>

  struts標簽讀取國際化文件

  </h>

  <form action=logindo method=post>

  <bean:message key=loginformfieldusername />

  :

  <input type=text name=username />

  <br />

  <bean:message key=loginformfieldpassword />

  :

  <input type=text name=password />

  <br />

  <input type=submit

  value=<bean:message key=loginformbuttonlogin/> />

  </form>

  <hr>

  <h>

  jstl讀取國際化文件

  </h>

  <form action=logindo method=post>

  <fmt:message key=loginformfieldusername />

  :

  <input type=text name=username />

  <br />

  <fmt:message key=loginformfieldpassword />

  :

  <input type=text name=password />

  <br />

  <input type=submit

  value=<fmt:message key=loginformbuttonlogin/> />

  </form>

  </body>

  </html>

  login_successjsp:

  [html]

  <%@ page language=java contentType=text/html; charset=GB

  pageEncoding=GB%>

  <%@ taglib uri=/tagshtml prefix=html %>

  <%@ taglib uri=/tagsbean prefix=bean %>

  <!DOCTYPE html PUBLIC //WC//DTD HTML Transitional//EN /TR/html/loosedtd>

  <html>

  <head>

  <meta httpequiv=ContentType content=text/html; charset=GB>

  <title>Insert title here</title>

  </head>

  <body>

  <! message 屬性設置為true則讀取message中的消息false則讀取error中的消息 saveMessages/saveErrors>

  <html:messages id=msg message=true>

  <bean:write name=msg/>

  </html:messages>

  </body>

  </html>

  最後的最後在webxml中配置一下struts:

  [html]

  <?xml version= encoding=UTF?>

  <webapp version=

  xmlns=/xml/ns/jee

  xmlns:xsi=//XMLSchemainstance

  xsi:schemaLocation=/xml/ns/jee

  /xml/ns/jee/webapp__xsd>

  <welcomefilelist>

  <welcomefile>loginjsp</welcomefile>

  </welcomefilelist>

  <servlet>

  <servletname>action</servletname>

  <servletclass>orgapachestrutsactionActionServlet</servletclass>

  <initparam>

  <paramname>config</paramname>

  <paramvalue>/WEBINF/strutsconfigxml</paramvalue>

  </initparam>

  <initparam>

  <paramname>debug</paramname>

  <paramvalue></paramvalue>

  </initparam>

  <initparam>

  <paramname>detail</paramname>

  <paramvalue></paramvalue>

  </initparam>

  <loadonstartup></loadonstartup>

  </servlet>

  <! Standard Action Servlet Mapping >

  <servletmapping>

  <servletname>action</servletname>

  <urlpattern>*do</urlpattern>

  </servletmapping>

  </webapp>

  在Strutsconfigxml中配置actionactionform等信息

  [html]

  <?xml version= encoding=ISO ?>

  <!DOCTYPE strutsconfig PUBLIC

  //Apache Software Foundation//DTD Struts Configuration //EN

  /struts/dtds/strutsconfig__dtd>

  <strutsconfig>

  <formbeans>

  <formbean name=loginForm type=combjpowernodestrutsLoginActionForm></formbean>

  </formbeans>

  <actionmappings>

  <action path=/login

  type=combjpowernodestrutsLoginAction

  name=loginForm

  scope=request >

  <forward name=success path=/login_successjsp></forward>

  <!<forward name=error path=/login_errorjsp></forward>>

  <forward name=error path=/loginjsp></forward>

  </action>

  <action path=/changelang

  type=combjpowernodestrutsChangeLanguageAction

  >

  <forward name=login path=/loginjsp redirect=true></forward>

  </action>

  </actionmappings>

  <messageresources parameter=resourceMessageBundle></messageresources>

  </strutsconfig>


From:http://tw.wingwit.com/Article/program/Java/ky/201311/27934.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.