实验_Struts2国际化 登录页面国际化的两种实现方法

1.实验名称
Struts2国际化

2.实验目的
(1)了解程序国际化的意义
(2)理解JAVA国际化的思路。会编写资源文件,并能使用Locale类和ResourceBundle类对程序进行国际化。

3.实验内容
这里写图片描述

4.文件描述:
ChangeLang.java:封装language属性。
Login.java:登陆相关模型驱动与处理、拦截方法
UserBean.java:封装用户名、密码属性
myMessage_en_US.properties:英文配置文件
myMessage_zh_CN.properties:中文配置文件
index.jsp:登录页
error.jsp:登陆报错页
welcome.jsp:登陆成功页
Struts.xml:struts2配置文件

5.实验源代码

  • ChangeLang.java
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.java
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 = "chenghaoran".equals( this.getModel().getUserName() );
    boolean rightPassWord = "12345678".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"));
        }
    }
}
  • UserBean.java
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;
    }
}
  • myMessage_en_US.properties
label_user = User: 
label_password = PassWord:
label_submit = Login
label_reset = Reset 
label_userError = userName\'s length can\'t less than six!
label_passwordError = passWord\'s length can\'t less than five!
welcome = Welcome !
  • myMessage_zh_CN.properties
label_user = \u7528\u6237\u540D:
label_password = \u5BC6\u7801:
label_submit = \u767B\u5F55
label_reset = \u91CD\u586B
label_userError = \u7528\u6237\u540D\u957F\u5EA6\u4E0D\u5F97\u5C11\u4E8E6\u4E2A\u5B57\u7B26
label_passwordError = \u5BC6\u7801\u957F\u5EA6\u4E0D\u5F97\u5C11\u4E8E5\u4E2A\u5B57\u7B26
welcome = \u6B22\u8FCE\u4F60
  • index.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 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>登录页</title>
</head>
<body>
<%
    String lang = (String)application.getAttribute("lang");
    if (lang == null)
    {
        lang = "zh_CN";
    }
    session.setAttribute("language", lang);
%>
<table  border="1">
    <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:password name="passWord" size="20"></s:password>
            </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="english" action="ChangeLang.action">
  <s:param name="language">en_US</s:param>
 </s:url>
 <s:a href="%{english}">英文</s:a>    
 <s:url id="zhongwen" action="ChangeLang.action">
    <s:param name="language">zh_CN</s:param>
 </s:url>
 <s:a href="%{zhongwen}">中文</s:a>
</body>
</html>
  • error.jsp
<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
<html>
<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>
  • Struts.xml
<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">/welcome.jsp</result>
            <result name="error">/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>
</struts>

第二种思路:

20171114_shiyan_newinternationallogin

  • /20171114_shiyan_newinternationallogin/src/nuc/sw/action/LoginAction.java
package nuc.sw.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

public class LoginAction extends ActionSupport {

    private String username;
    private String password;
    private String type;

    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;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

  // @Override
 // public void validate(){
     //if(username==null){
          //addFieldError("username","用户名不能为空");     }
         // if(password==null){ addFieldError("password","密码不能为空");
       //}
  // }
   // @Override
  // public void validate() {
    //   if(username.equals("admin") && password.equals("pass")){
       //     return;
    //  }else{
     //      addFieldError("username","用户名或密码不正确");
     //  }

 // }


    public String Login() throws Exception {

          if (username.equals("lv") && password.equals("pass")) {
              ActionContext.getContext().getSession().put("username", username);
              return SUCCESS;
          } else if (username.equals("chenghaoran") && password.equals("12345678")){
              ActionContext.getContext().getSession().put("username", username);
              return SUCCESS;
          }else{
              addFieldError("error",getText("用户名或密码不正确"));
          }


        return INPUT;
    }
}
  • /20171114_shiyan_newinternationallogin/src/nuc/sw/action/TransformAction.java
package nuc.sw.action;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.net.httpserver.Authenticator;

public class TransformAction extends ActionSupport {

    @Override
    public String execute()throws Exception{
        return SUCCESS;
    }

}
  • /20171114_shiyan_newinternationallogin/src/nuc/sw/action/LoginAction-validation.xml
<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message key="用户名不能为空"></message>
        </field-validator>
        <!--<field-validator type="expression">-->
            <!--<param name="expression"><![CDATA[username=="admin"]]></param>-->
            <!--<message key="用户名或密码不正确"></message>-->
        <!--</field-validator>-->
    </field>

    <field name="password">
        <field-validator type="requiredstring">
            <param name="trim">true</param>
            <message key="密码不能为空"></message>
        </field-validator>
    </field>

    <!--<field name="username">-->
        <!--<field-validator type="expression">-->
            <!--<param name="expression"><![CDATA[password=="pass"]]><![CDATA[username=="admin"]]></param>-->
            <!--<message key="用户名或密码不正确"></message>-->
        <!--</field-validator>-->
    <!--</field>-->
</validators>
  • /20171114_shiyan_newinternationallogin/src/messageResource_en_US.properties
username=username
password=password
login=login
usertype=usertype:
\u666E\u901A\u7528\u6237=user
\u7BA1\u7406\u5458=admin
welcome=welcome!{0}
\u4E2D\u6587\u7248=version of China
\u82F1\u6587\u7248=version of US
title=LoginPage
sucPage=successPage
\u7528\u6237\u540D\u6216\u5BC6\u7801\u4E0D\u6B63\u786E=Username or password incorrect\uFF01
\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A=username cannot be null !
\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A=password cannot be null !
url=Transform.action?request_locale=zh_CN
version=version of China
  • /20171114_shiyan_newinternationallogin/src/messageResource_zh_CN.properties
username=\u7528\u6237\u540D
password=\u5BC6\u7801
login=\u767B\u5F55
usertype=\u7528\u6237\u7C7B\u578B:
welcome=\u6B22\u8FCE\u60A8!{0}
\u82F1\u6587\u7248=\u82F1\u6587\u7248
\u4E2D\u6587\u7248=\u4E2D\u6587\u7248
\u666E\u901A\u7528\u6237=\u666E\u901A\u7528\u6237
\u7BA1\u7406\u5458=\u7BA1\u7406\u5458
title=\u767B\u5F55\u9875
sucPage=\u767B\u5F55\u6210\u529F\u9875
\u7528\u6237\u540D\u6216\u5BC6\u7801\u4E0D\u6B63\u786E=\u7528\u6237\u540D\u6216\u5BC6\u7801\u4E0D\u6B63\u786E\uFF01
\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A!
\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A\uFF01
url=Transform.action?request_locale=en_US
version=\u82F1\u6587\u7248
  • /20171114_shiyan_newinternationallogin/src/struts.properties
struts.custom.i18n.resources=messageResource
struts.i18n.encoding=utf-8
  • /20171114_shiyan_newinternationallogin/src/struts.xml
<struts>

    <package name="I18N" namespace="/" extends="struts-default">

        <!--<interceptors>-->
        <!--<interceptor name="LoginInterceptor" class="nuc.com.interceptor.LoginInterceptor"></interceptor>-->
        <!--</interceptors>-->


        <action name="Login" class="nuc.sw.action.LoginAction" method="Login">
            <result>/success.jsp</result>
            <result name="input">/login.jsp</result>
        </action>

        <action name="Transform" class="nuc.sw.action.TransformAction">
            <result>/login.jsp</result>
        </action>

    </package>

</struts>
  • /20171114_shiyan_newinternationallogin/WebContent/index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$
  </body>
</html>
  • /20171114_shiyan_newinternationallogin/WebContent/login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%--<s:i18n name="messageResource">--%>
<html>
<head>
    <title><s:text name="title"/></title>
</head>
<body>

    <s:fielderror fieldName="error" key=""/>
    <s:form action="Login" method="POST">
        <tr><td><s:textfield name="username" key="username"></s:textfield></td></tr>
        <tr><td><s:password name="password" key="password"></s:password></td></tr>
        <%--<s:select list="{'普通用户','管理员'}" name="type" key="usertype">--%>
        <%--</s:select>--%>
        <tr><td><s:text name="usertype"/></td>
            <td><select name="usertype">
                <option name="user"><s:text name="普通用户"/></option>
                <option name="admin"><s:text name="管理员"/></option>
            </select></td>
        </tr>
        <tr><s:submit key="login"></s:submit></tr>
    </s:form>

    <a href="<s:text name="url"/>"><s:text name="version"/></a>

<%--
    <a href="Transform.action?request_locale=zh_CN">
        <s:text name="中文版"/>
    </a>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="Transform.action?request_locale=en_US">
        <s:text name="英文版"/>
    </a>
--%>

</body>
</html>
<%--</s:i18n>--%>
  • /20171114_shiyan_newinternationallogin/WebContent/success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title><s:text name="sucPage"/></title>
</head>
<body>
<center>
        <s:text name="welcome">
            <s:param>
                <s:property value="username"></s:property>
            </s:param>
        </s:text>
</center>
</body>
</html>

第一种在英文和中文界面都可以看到两个切换按钮。
第二种在英文页面只能看到切换中文的按钮,中文亦然。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值