动态切换Struts2的国际化


思路:

1.在struts.xml中配置好默认的语言:

<constant name="sturts.locale" value="zh_CN" />

2.在jsp页面中,设置一些链接(<a></a>),这些链接是Action类,然后通过这些链接,在Action中设置好相应的参数, 并将它保存在application对象中。

3.在跳转后的jsp页面中,通过获取application对象的相应的属性的值,以后在相应的表单中通过设置隐藏属性<input type="hidden" name="request_locale" value="<%= (String)application.getAttribute("language") />,这样子在以后的跳转页面都会显示相应的语言了。

4.具体的代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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=UTF-8">
<title>Login</title>
</head>
<body>
<%
    String lang = (String)application.getAttribute("lang");
    if (lang == null)
    {
        lang = "zh_CN";
    }
    session.setAttribute("language", lang);
%>
<table align="center" border="1">
    <caption>Login</caption>
    <s:form method="post" name="loginForm" action="Login"  namespace="/" validate="false">
        <tr>
            <td>
                <s:text name="label_user"></s:text>
            </td>
            <td>
                <s:textfield name="userName" size="20"></s:textfield>
            </td>
        </tr>
        
        <tr>
            <td>
                <s:text name="label_password"></s:text>
            </td>
            <td>
                <s:textfield name="passWord" size="20"></s:textfield>
            </td>
        </tr>
        <input type="hidden" name="request_locale" value="<%=(String)session.getAttribute("language")%>"/>
        <tr>
            <td colspan="2" align="center">
                <s:submit type="input" key="label_submit"></s:submit>
                <s:reset type="password" key="label_reset"></s:reset>
            </td>
        </tr>
        
        <tr>
            <td colspan="2">
                <s:fielderror>
                </s:fielderror>
            </td>
        </tr>
    </s:form>
</table>

<!--  这里是进行设置语言选择的 -->

<s:url id="zhongwen" action="ChangeLang.action">
    <s:param name="language">zh_CN</s:param>
</s:url>
<s:a href="%{zhongwen}">中文</s:a>

<s:url id="english" action="ChangeLang.action">
    <s:param name="language">en_US</s:param>
</s:url>
<s:a href="%{english}">英文</s:a>
</body>
</html>

//User Model

package yang.www;

public class UserBean
{
    private String userName;
    private String passWord;

    
    public UserBean(){}


    
    public String getUserName() {
        return userName;
    }
    public String getPassWord() {
        return passWord;
    }
    
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}


//进行语言的设置:

package yang.www;

import java.util.Locale;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ChangeLang extends ActionSupport
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String language;
    
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }
    public String execute()
    {
        String[] strings = this.getLanguage().split("_");
        Locale locale = new Locale(strings[0], strings[1]);
        ServletActionContext.getContext().setLocale(locale);
        ActionContext.getContext().getApplication().put("lang", this.getLanguage());
        return SUCCESS;
    }
}

//Login Action

package yang.www;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class Login extends ActionSupport implements ModelDriven<UserBean>
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private UserBean user = new UserBean();
    @Override
    public UserBean getModel() {
        // TODO Auto-generated method stub
        return user;
    }
    
    ActionContext context = ActionContext.getContext();
    public String execute()
    {
        boolean rightUser = "yangzhiyong".equals( this.getModel().getUserName() );
        boolean rightPassWord = "yangzhiyong".equals(this.getModel().getPassWord());
        if ( rightUser && rightPassWord )
        {
            context.getSession().put("username", this.getModel().getUserName());
            return SUCCESS;
        }
        else
        {
            return ERROR;
        }
    }
    
    public void validate()
    {
        if (this.getModel().getUserName().length() < 6 )
        {
            this.addFieldError("userName", this.getText("label_userError"));
        }
        if (this.getModel().getPassWord().length() < 5)
        {
            this.addFieldError("passWord", this.getText("label_passwordError"));
        }
    }
}


struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.locale" value="zh_CN" />
    <constant name="struts.custom.i18n.resources" value="i18n/myMessage" />
    
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.ui.templateDir" value="template" />
    <constant name="struts.ui.templateSuffix" value="ftl" />
    
    <package name="hello" extends="struts-default" namespace="/">
       <action name="Login" class="yang.www.Login">
               <result name="success">/jsp/welcome.jsp</result>
               <result name="error">/jsp/error.jsp</result>
               <result name="input">/index.jsp</result>
       </action>
       <action name="ChangeLang" class="yang.www.ChangeLang" >
               <result name="success">/index.jsp</result>
       </action>
    </package>
    
    <!-- Add packages here -->

</struts>


//error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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=UTF-8">
<title>Login Error</title>
</head>
<body>
    <h1>Sorry login failed!</h1>
</body>
</html>



//welcome.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Success!</title>
</head>
<body>
    <s:property value="#session.username"/>
    <h3>Welcome , you login  successfully !</h3>
    <s:text name="welcome"></s:text>
</body>
</html>

完整可运行的例子,可以到我的资源里下载。这样子可能会更加理解一点。

相关内容