modelsaveaction.java

来自「一个非常好的FRAMWRK!是一个外国组织做的!不!」· Java 代码 · 共 206 行

JAVA
206
字号
/**
 * Copyright 2003-2005 the original author or authors.
 * 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 com.jdon.strutsutil;

import javax.servlet.ServletContext;
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;

import com.jdon.container.finder.ComponentKeys;
import com.jdon.controller.WebAppUtil;
import com.jdon.controller.events.EventModel;
import com.jdon.controller.model.Model;
import com.jdon.model.ModelForm;
import com.jdon.model.ModelHandler;
import com.jdon.model.ModelKey;
import com.jdon.model.ModelManager;
import com.jdon.model.mapping.ModelMapping;
import com.jdon.util.Debug;
import com.jdon.util.UtilValidate;

/**
 * Accept the datas that user submited, and 
 * handle them to service layer, service maybe persistence them.
 * it is just like a  handler. all functions delegate Modelhandler
 * 
 * 
 * configure in jdonframework.xml:
 * 
 * <action name="productForm" type="com.jdon.strutsutil.ModelSaveAction" input="/admin/product.jsp"  scope="request" path="/admin/saveProductAction">
 *    <forward name="success" path="/admin/productOk.jsp" />
 *    <forward name="failure" path="/admin/productOk.jsp" />
 * </action>
 *
 * @author banq
 */
public class ModelSaveAction extends Action {

  private final static String module = ModelSaveAction.class.getName();
  private ModelManager modelManager;


  public ActionForward execute(ActionMapping actionMapping,
                               ActionForm actionForm,
                               HttpServletRequest request,
                               HttpServletResponse response) throws
      Exception {

    if (modelManager == null){
      ServletContext sc = this.getServlet().getServletContext();
      modelManager = (ModelManager)WebAppUtil.getComponentInstance(ComponentKeys.MODEL_MANAGER, sc);
    }
    init(actionMapping, request);

    EventModel em = null;
    String formName = FormBeanUtil.getFormName(actionMapping);

    ModelHandler modelHandler = modelManager.borrowtHandlerObject(formName);
    try {
      ModelForm form = getModelForm(modelHandler,actionForm,request);
      Model model = makeModel(actionMapping, actionForm, request, modelHandler);
      modelHandler.formCopyToModel(form, model);

      em = new EventModel(); //创建一个事件,与EJB实现通讯,并从事件中获取处理出错情况
      em.setActionName(module);
      em.setModel(model); //将model数据赋予事件
      em.setActionType(FormBeanUtil.actionTransfer(form.getAction())); //设置事件操作类型

      Debug.logVerbose(" save data to database ... ", module);
      //deleagte the Modelhandler's serviceAction
      modelHandler.serviceAction(em, request);
      
      modelHandler.modelCopyToForm(model,form);

    } catch (Exception ex) {
      Debug.logError("please check your ejb 、 model or form :" + ex, module);
      throw new Exception("System error! please call system Admin." + ex);
    } finally {
      modelManager.returnHandlerObject(modelHandler);
    }

    if (em.getErrors() != null) { //处理出错
      Debug.logError(" save error!! " + em.getErrors(), module);
      ActionMessages errors = new ActionMessages();
      ActionMessage error = new ActionMessage(em.getErrors());
      errors.add(ActionMessages.GLOBAL_MESSAGE, error);
      saveErrors(request, errors);
      
      ActionForward af = actionMapping.findForward(FormBeanUtil.FORWARD_FAILURE_NAME);
      if (af != null) return af;
      else  return actionMapping.findForward(FormBeanUtil.FORWARD_SUCCESS_NAME);
    } else {
//      clearModelCache(em);
      Debug.logVerbose(" save successfully ... ", module);
      return actionMapping.findForward(FormBeanUtil.FORWARD_SUCCESS_NAME);
    }

  }

  private void init(ActionMapping actionMapping, HttpServletRequest request) throws
      Exception {
//    FormBeanUtil.removeActionForm(actionMapping, request);
    checkConfigName(actionMapping);

  }

  /**
   * 由ModelHandler的initForm生成一个新的ModelForm
   * 将载有用户数据
   * @param modelHandler
   * @param actionForm
   * @param request
   * @return
   * @throws java.lang.Exception
   */
  private ModelForm getModelForm(ModelHandler modelHandler,
                                 ActionForm actionForm,
                                 HttpServletRequest request) throws Exception {

    if (actionForm == null){
         throw new Exception(" must define a name value in action config.");
    }
    ModelForm strutsForm = (ModelForm) actionForm;
    String action = strutsForm.getAction();
    if ( (action == null) || (action.length() == 0))
       throw new Exception(" Need a field : <html:hidden property=action /> in jsp's form! ");


//    ModelForm newForm = modelHandler.initForm(request);
//    PropertyUtils.copyProperties(newForm, strutsForm);
    return strutsForm;

  }

  /**
   *
   * @param actionMapping
   * @param actionForm
   * @param request
   * @return Model
   * @throws java.lang.Exception
   */
  private Model makeModel(ActionMapping actionMapping, ActionForm actionForm,
                          HttpServletRequest request, ModelHandler modelHandler) throws Exception {
    Model model = null;
    try {
        String formName = actionMapping.getName();
        if (formName == null)
          throw new Exception("no define the FormName in struts_config.xml");

        ModelMapping modelMapping = modelHandler.getModelMapping();
        String keyName = modelMapping.getKeyName();
        String keyValue = request.getParameter(keyName);
        if (keyValue == null){
            Debug.logError("Need a model's key field : <html:hidden property=MODEL EKY /> in jsp's form! ", module);            
        }

        ModelKey modelKey = new ModelKey(keyValue, formName);
        model = modelManager.getCache(modelKey);
        if (model != null) {//有缓存,则清除对应的缓存
           modelManager.removeCache(keyValue);
        }else{//缓存没有,则生成新的空白的model
          Debug.logVerbose(" no model cache, keyName is " + keyName, module);
          model = modelManager.getModelObject(formName);
        }
    } catch (Exception e) {
        Debug.logError(" makeModel error: " + e);
        throw new Exception(e);
    }
    return model;
  }


  private void checkConfigName(ActionMapping actionMapping) throws Exception {
    if (actionMapping.findForward(FormBeanUtil.FORWARD_FAILURE_NAME) == null)
      Debug.logError(
          "not found the forward name '" + FormBeanUtil.FORWARD_FAILURE_NAME +
          "' in struts-config.xml", module);
    else if (actionMapping.findForward(FormBeanUtil.FORWARD_SUCCESS_NAME) == null)
      Debug.logError(
          "not found the forward name '" + FormBeanUtil.FORWARD_SUCCESS_NAME +
          "' in struts-config.xml", module);

  }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?