Struts提供了国际化的功能,对于一个面向各国的系统来说,是非常有帮助的。只需要提供每个国家的语言资源包,配置后即可使用。
下面来用一个登录实例来演示一下Struts的国际化配置和显示。
创建一个login_i18n_exception的javaweb项目,引入Struts的所有jar包以及jstl.jar和standard.jar。登录界面无非就是输入用户名,密码,所以ActionForm中只需要设置2个属性即可。
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个异常:用户名未找到,密码错误。
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个语言包。具体内容如下:
英文语言包和默认语言包设置成一样的:
# -- 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张效果图吧。