struts初步

来源:互联网 发布:网络最新流行语2017 编辑:程序博客网 时间:2024/06/05 21:13

  Struts框架有几个类,其中ActionServlet控制整个处理流程。当服务器收到一个request的时候,ActionServlet首先查阅ActionMapping,找到处理该请求URL所需要的Action,  ActionForm, ActionForward。然后ActionServlet选择找到的Action来处理请求,所需要的参数从ActionFrom(java bean的实现)中获得,当Action处理完毕后,需要把结果返回,这时候通过ActionForward把处理结果传给负责表示的JSP页面,最后由web服务器把页面返回给用户完成一次处理。  而这些Action, ActionForm, ActionForward, ActionMapping,

 

和一些其他的东西都是在struts-config.xml文件中声明的。当收到request的时候,ActionServlet读取这个配置文件,然后创建一个存放对象数据库,对象中含有配置信息。在运行时,ActionServlet读取的事数据库中的对象,而不是配置文件本身。

       ActionServlet收到Form中传递过来的参数后,将参数名与ActionForm的属性名相比较,如果相符则调用该属性的setter方法将参数值赋给该属性,以便Action调用。

 

The centerpiece of Struts is an MVC-style Controller. The Struts Controller bridges the gap between Model and View.

 

 

 

 

 

Struts Taglib

 

 

JSTL差不多,只要在web.xml中定义Taglib的名称和对应的tld文件地址映射,在需要使用Taglib的网页首部应用一下Taglib名称就OK了。<html:form>没有name属性,struts会根据<html:form>action属性找到对应的Action,用该Actionname属性作为表单的name,这个name同时也必须跟对应ActionFormname属性一致。这样做也避免了手工填写formname属性导致与ActionForm名称不一致的问题。

 

 

 

Struts 国际化

下午还试了一下struts的国际化,其实也不难,首先保证每个jsp网页都有<%@ page language="java" pageEncoding="UTF-8"%>,也就是网页用UTF-8做编码。配置文件都不用怎么改,struts会根据客户端浏览器的locale找到对应的properties文件,读取里面的静态文本信息。中文properties文件命名方式是原有properties文件名+“_zh_CN”+“.properties”。第一个“_”后面的字母表示语言,zh表示Chinese,第二个“_”后面的字母表示国家,CN表示China。注意中文properties文件必须用Unicode保存,做到这一点可以用jdk自带的native2ascii命令转换格式,格式为 native2ascii Cencoding 原文件编码方式 原文件名 输出UTF-8编码格式文件名。Windows操作系统中默认的原文件编码方式一般为gb2312或者gbk.

为了让用户可以自由选择界面显示的语言,可以做两个链接改变session里的一个locale相关变量,就可以改变语言了。具体做法如下:

首先建立一个action类处理locale转换,我取名为LocaleAction,代码如下:(其实是我在 struts的例子里面抄的...)

/*
 * $Header: /home/cvs/jakarta-struts/src/examples/org/apache/struts/webapp/validator/LocaleAction.java,v 1.3 2004/03/14 06:23:49 sraeburn Exp $
 * $Revision: 1.3 $
 * $Date: 2004/03/14 06:23:49 $
 *
 * Copyright 2000-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package app;

import java.util.Locale;

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

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


/**
 * Implementation of <strong>Action</strong> that changes the user's
 * @link(java.util.Locale and forwards to a page, based on request level
 * parameters that are set  (language, country, &amp; page).
 *
*/
public final class LocaleAction extends Action {

    /**
     * Commons Logging instance.
    */
    private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());

    /**
     * <p>
     * Change the user's @link(java.util.Locale) based on @link(ActionForm)
     * properties.
     * </p>
     * <p>
     * This <code>Action</code> looks for <code>language</code> and
     * <code>country</code> properties on the given form, constructs an
     * appropriate Locale object, and sets it as the Struts Locale for this
     * user's session.
     * Any <code>ActionForm, including a @link(DynaActionForm), may be used.
     * </p>
     * <p>
     * If a <code>page</code> property is also provided, then after
     * setting the Locale, control is forwarded to that URI path.
     * Otherwise, control is forwarded to "success".
     * </p>
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @return Action to forward to
     * @exception java.lang.Exception if an input/output error or servlet exception occurs
     */
    public ActionForward execute(ActionMapping mapping,
                 ActionForm form,
                 HttpServletRequest request,
                 HttpServletResponse response)
    throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();
    Locale locale = getLocale(request);

    String language = null;
    String country = null;
    String page = null;

    try {
            language = (String)
              PropertyUtils.getSimpleProperty(form, "language");
            country = (String)
              PropertyUtils.getSimpleProperty(form, "country");
            page = (String)
              PropertyUtils.getSimpleProperty(form, "page");
        } catch (Exception e) {
           log.error(e.getMessage(), e);
        }

        if ((language != null && language.length() > 0) &&
            (country != null && country.length() > 0)) {
           locale = new java.util.Locale(language, country);
        } else if (language != null && language.length() > 0) {
           locale = new java.util.Locale(language, "");
  }

        session.setAttribute(Globals.LOCALE_KEY, locale);

  System.out.print("aaaaaaaaaa");
  System.out.print(page);
  System.out.println("bbbbbbbbbb");

        if (null==page||page.equals("")) return mapping.findForward("success");
        else return new ActionForward(page);

//  return mapping.findForward("success");
    }

}

我在里面做了一点小小的修改,就是 if (null==page||page.equals("")) 这里原本没有判断page=="",结果tomcat报错说ActionForward(page)有错误。

当然有了Action还得有ActionForm和对应的Forward吧,不过为它再写一个java源文件感觉不值得,就再struts-config.xml里面添加一个动态Form吧,内容如下:


  <form-bean name="localeForm" type="org.apache.struts.action.DynaActionForm">
    <form-property name="language" type="java.lang.String" />
    <form-property name="country" type="java.lang.String" />
    <form-property name="page" type="java.lang.String" />
  </form-bean>

当然上面几行语句要被包含再<form-beans>标签对里。

在<action-mapping>标签对里面添加

  <action path="/locale" type="app.LocaleAction" name="localeForm" scope="request">
         <forward name="success" path="/welcome.do" />
         </action>

最后只要再首页上添加超级链接就可以,在链接里加上language和country的值。比如:

<html:link action="/locale?language=en"><bean:message key="locale.en"/></html:link>
       <html:link action="/locale?language=zh&country=CN"><bean:message key="locale.zh_CN"/></html:link>