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

      Struts提供了國際化的功能,對於一個面向各國的系統來講,是很是有幫助的。只須要提供每一個國家的語言資源包,配置後便可使用。html


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


      建立一個login_i18n_exception的javaweb項目,引入Struts的全部jar包以及jstl.jar和standard.jar。登陸界面無非就是輸入用戶名,密碼,因此ActionForm中只須要設置2個屬性便可。node

package com.bjpowernode.struts;

import org.apache.struts.action.ActionForm;

/**
 * 登陸ActionForm,負責收集表單數據
 * 表單的數據必須和ActionForm的get,set一致
 * @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) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

      登陸時會驗證密碼是否正確,須要提供異常處理,本實例顯示2個異常:用戶名未找到,密碼錯誤。web

package com.bjpowernode.struts;
/**
 * 密碼錯誤異常
 * @author Longxuan
 *
 */
@SuppressWarnings("serial")
public class PasswordErrorException extends RuntimeException {

	public PasswordErrorException() {
		// TODO Auto-generated constructor stub
	}

	public PasswordErrorException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public PasswordErrorException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

	public PasswordErrorException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public PasswordErrorException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

}



package com.bjpowernode.struts;
/**
 * 用戶未找到異常
 * @author Longxuan
 *
 */
@SuppressWarnings("serial")
public class UserNotFoundException extends RuntimeException {

	public UserNotFoundException() {
		// TODO Auto-generated constructor stub
	}

	public UserNotFoundException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public UserNotFoundException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

	public UserNotFoundException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public UserNotFoundException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

}

      提供用戶管理類,處理用戶的相關操做,這裏主要處理用戶登陸:

package com.bjpowernode.struts;
/**
 * 用戶管理類
 * @author Longxuan
 *
 */
public class UserManager {
	
	/**
	 * 簡單處理登陸邏輯
	 * @param username	用戶名
	 * @param password	密碼
	 */
	public void login(String username,String password){
		
		if(!"admin".equals(username)){
			throw new UserNotFoundException();
		}
		if(! "admin".equals(password)){
			throw new PasswordErrorException();
		}
	}
}

      如今寫LoginAction的處理:

package com.bjpowernode.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * 登陸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 = laf.getUsername();
		String password = laf.getPassword();

		UserManager userManager = new UserManager();
		ActionMessages messages = new ActionMessages();
		
		try {
			//用戶登陸
			userManager.login(username, password);
			
			//獲取登陸成功的國際化消息
			ActionMessage success= new ActionMessage("login.success",username);
			messages.add("login_success_1",success);
			
			//傳遞消息
			this.saveMessages(request, messages);
			
			return mapping.findForward("success");
			
		} catch (UserNotFoundException e) {
			
			e.printStackTrace();
			
			//獲取登陸成功的國際化消息
			ActionMessage error = new ActionMessage("login.user.not.found",username);
			messages.add("login_error_1",error);
			
			//傳遞消息
			this.saveErrors(request, messages);			
			
		} catch (PasswordErrorException e) {
			
			e.printStackTrace();
			
			//獲取登陸成功的國際化消息
			ActionMessage error = new ActionMessage("login.user.password.error");
			messages.add("login_error_2",error);
			
			//傳遞消息
			this.saveErrors(request, messages);
			
		}		
		return mapping.findForward("error");
	}

}


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

package com.bjpowernode.struts;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * 完成語言的手動切換
 * @author Longxuan
 *
 */
public class ChangeLanguageAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//獲取語言
		String lang = request.getParameter("lang");		
		String[] split = lang.split("-");
		
		//設置語言
		Locale locale = new Locale(split[0],split[1]);
		this.setLocale(request, locale);

		return mapping.findForward("login");
	}	
}

      新建國際化信息文件:建立resource包,建立 英文語言包MessageBundle_en_US.properties,中文語言包MessageBundle_zh_CN.properties,默認語言包MessageBundle.properties 這3個語言包。具體內容以下:

英文語言包和默認語言包設置成同樣的:apache

# -- standard errors --
errors.header=<UL>
errors.prefix=<font color="red"><LI>
errors.suffix=</LI></font>
errors.footer=</UL>
login.form.field.username=User Name
login.form.field.password=Password
login.form.button.login=Login
login.success={0},Login Succedd!!
login.user.not.found=Use cant be found! Username=[{0}]
login.user.password.error=Password  Error!
中文語言包:
# -- standard errors --
errors.header=<UL>
errors.prefix=<font color="red"><LI>
errors.suffix=</LI></font>
errors.footer=</UL>
login.form.field.username=\u7528\u6237\u540D
login.form.field.password=\u5BC6\u7801
login.form.button.login=\u767B\u5F55
login.success={0}\uFF0C\u767B\u5F55\u6210\u529F\uFF01
login.user.not.found=\u7528\u6237\u672A\u627E\u5230\uFF0C\u7528\u6237\u540D\uFF1A\u3010{0}\u3011
login.user.password.error=\u5BC6\u7801\u9519\u8BEF

      把login.jsp源碼也貼出來:

<%@ page language="java" contentType="text/html; charset=GB18030"
	pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<!-- ${sessionScope['org.apache.struts.action.LOCALE']}能夠獲取到當前設置的語言 -->
<fmt:setLocale value="${sessionScope['org.apache.struts.action.LOCALE']}" />
<fmt:setBundle basename="resource.MessageBundle" />
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
		<title>Struts登陸</title>
	</head>
	<body>
		<a href="changelang.do?lang=zh-cn">中文登陸</a>|
		<%--<a href="changelang.do?lang=en-us">English Login</a><br>
    <html:link action="changelang.do?lang=zh-cn">中文登陸</html:link>|--%>
		<html:link action="changelang.do?lang=en-us">English Login</html:link>
		<hr>
		<html:errors />
		<hr>
		<h3>
			struts標籤讀取國際化文件
		</h3>

		<form action="login.do" method="post">

			<bean:message key="login.form.field.username" />
			:
			<input type="text" name="username" />
			<br />
			<bean:message key="login.form.field.password" />
			:
			<input type="text" name="password" />
			<br />
			<input type="submit"
				value="<bean:message key="login.form.button.login"/>" />
		</form>
		<hr>
		<h3>
			jstl讀取國際化文件
		</h3>
		<form action="login.do" method="post">
			<fmt:message key="login.form.field.username" />
			:
			<input type="text" name="username" />
			<br />
			<fmt:message key="login.form.field.password" />
			:
			<input type="text" name="password" />
			<br />
			<input type="submit"
				value="<fmt:message key="login.form.button.login"/>" />
		</form>

	</body>
</html>
login_success.jsp:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<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>

      最後的最後,在web.xml中配置一下struts:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  
</web-app>

在Struts-config.xml中配置action,actionform等信息:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
	<form-beans>
		<form-bean name="loginForm" type="com.bjpowernode.struts.LoginActionForm"></form-bean>
	</form-beans>
	
	<action-mappings>
		<action path="/login" 
				type="com.bjpowernode.struts.LoginAction"
				name="loginForm"
				scope="request" >
			<forward name="success" path="/login_success.jsp"></forward>
			<!--<forward name="error" path="/login_error.jsp"></forward>-->
			<forward name="error" path="/login.jsp"></forward>
		</action>
		<action path="/changelang"
				type="com.bjpowernode.struts.ChangeLanguageAction"
				>
			<forward name="login" path="/login.jsp" redirect="true"></forward>
		</action>
	</action-mappings>
	
	
	<message-resources parameter="resource.MessageBundle"></message-resources>
</struts-config>

      到此實例結束。點擊這裏查看效果。也能夠下載源碼。最後來2張效果圖吧。


   





版權聲明:本文爲博主原創文章,未經博主容許不得轉載。tomcat

相關文章
相關標籤/搜索