> Java > java지도 시간 > 본문

Struts1 ActionMapping 예제 설명

巴扎黑
풀어 주다: 2017-09-06 09:34:42
원래의
1596명이 탐색했습니다.

이 기사는 Struts1 튜토리얼의 ActionMapping을 주로 소개합니다. 편집자는 이것이 꽤 좋다고 생각합니다. 이제 공유하고 참고용으로 제공하겠습니다.

우선 중단점은 processpath 메서드에서 벗어났습니다.

이 메서드는 문자열을 가로채는 데 사용됩니다. 방법---프로세스 매핑.

그 전에 ActionMapping에 대해 간단히 이야기해 보겠습니다. 가장 중요한 속성은 mvc 소형 인스턴스의 ActionMapping과 유사하며 주로 해당 스트럿입니다. config 구성 파일은 이 구성 파일의 정보를 메모리에 저장하는 것입니다.

특정 mvc 소형 인스턴스의 ActionMapping 코드는 다음과 같습니다.


package com.cjq.servlet; 
import java.util.Map; 
public class ActionMapping { 
  private String path; 
  private Object type; 
  private Map forwardMap; 
  public String getPath() { 
    return path; 
  } 
  public void setPath(String path) { 
    this.path = path; 
  }  
  public Object getType() { 
    return type; 
  } 
 
  public void setType(Object type) { 
    this.type = type; 
  } 
 
  public Map getForwardMap() { 
    return forwardMap; 
  } 
 
  public void setForwardMap(Map forwardMap) { 
    this.forwardMap = forwardMap; 
  } 
}
로그인 후 복사

그리고 Struts의 Actionconfig 코드는 다음과 같습니다(ActionMapping이 이 ActionConfig를 상속하므로 ActionConfig를 더 직접적으로 살펴봅니다).

코드의 이 두 부분으로 판단하면 처음에 작성한 작은 mvc 예제가 Struts 프레임워크의 프로토타입이라는 것이 추가로 확인됩니다.

ActionMapping의 내용에 대해 이야기해 보니 ActionMapping에 대해 어느 정도 이해가 된 것 같습니다. 그러면 시스템에서 ActionMapping을 어떻게 생성하고 어떻게 ActionMapping을 찾을 수 있을까요? 오늘 제가 이야기하고 싶은 내용은 다음과 같습니다.

web에서 2의 구성 정보를 살펴보겠습니다. 구성 파일의 정보를 ActionMapping에 넣습니다. 따라서 서버를 실행할 때 이미 메모리에 struts-config 구성 파일 정보에 해당하는 ActionMapping이 있습니다. 오늘은 processMapping을 통해 이 ActionMapping 클래스를 읽어보겠습니다.

중단점 디버깅을 입력하고 먼저 processMapping 메서드에 중단점을 설정하세요.

소스 코드 입력:


/** 
   * <p>Select the mapping used to process theselection path for this request 
   * If no mapping can be identified, createan error response and return 
   * <code>null</code>.</p> 
   * 
   * @param request The servlet request weare processing 
   * @param response The servlet response weare creating 
   * @param path The portion of the requestURI for selecting a mapping 
   * 
   * @exception IOException if an input/outputerror occurs 
   */ 
  protectedActionMapping processMapping(HttpServletRequestrequest, 
                     HttpServletResponse response, 
                     String path) 
    throws IOException { 
  
    // Is there a mapping for this path? 
    ActionMapping mapping = (ActionMapping) 
      moduleConfig.findActionConfig(path); 
  
    // If a mapping is found, put it in the request and return it 
    if (mapping != null) { 
      request.setAttribute(Globals.MAPPING_KEY, mapping); 
      return (mapping); 
    } 
  
    // Locate the mapping for unknown paths (if any) 
    ActionConfig configs[] = moduleConfig.findActionConfigs(); 
    for (int i = 0; i < configs.length; i++) { 
      if (configs[i].getUnknown()) { 
        mapping = (ActionMapping)configs[i]; 
        request.setAttribute(Globals.MAPPING_KEY, mapping); 
        return (mapping); 
      } 
    } 
  
    // No mapping can be found to process this request 
    String msg = getInternal().getMessage("processInvalid"); 
    log.error(msg + " " + path); 
    response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); 
     
    return null; 
  }
로그인 후 복사

먼저 이전 단계에서 차단한 경로를 전달하고, moduleConfig의 findAction 메서드를 통해 ActionConfig를 찾고, ActionMapping을 반환합니다. 구체적인 코드는 다음과 같습니다.


ActionMapping mapping =(ActionMapping) 
   moduleConfig.findActionConfig(path);
로그인 후 복사

발견된 경우 ActionMapping이 요청 컨텍스트에 저장됩니다. 코드:


if (mapping != null) { 
      request.setAttribute(Globals.MAPPING_KEY, mapping); 
      return (mapping); 
    }
로그인 후 복사

경로를 통해 매핑을 찾을 수 없는 경우 Actionconfig를 탐색하여 알 수 없는 경로에 대한 매핑을 찾으면 요청에 저장됩니다. 구체적인 코드는 다음과 같습니다.


// Locate the mapping for unknownpaths (if any) 
    ActionConfig configs[] = moduleConfigfindActionConfigs(); 
    for (int i = 0; i < configslength; i++) { 
      if (configs[i].getUnknown()) { 
        mapping = (ActionMapping)configs[i]; 
        request.setAttribute(Globals.MAPPING_KEY, mapping); 
        return (mapping); 
      } 
    } 
  
    // No mapping can be found to process this request 
    String msg = getInternal().getMessage("processInvalid"); 
    log.error(msg + " " + path); 
    response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); 
     
    return null;
로그인 후 복사

문자열을 가로채서 문자열을 기반으로 ActionMapping을 얻는 경우 ActionServlet의 메소드인 processActionForm을 살펴보겠습니다. 기사)에서는 ActionMapping을 사용하여 ActionForm을 생성하고 관리를 위해 요청 또는 세션에 ActionForm을 넣을 것입니다.

먼저 struts에서 processActionForm 메서드의 구체적인 구현을 살펴보겠습니다.


/** 
   * <p>Retrieve and return the <code>ActionForm</code> associatedwith 
   * this mapping, creating and retaining oneif necessary. If there is no 
   * <code>ActionForm</code> associated with this mapping,return 
   * <code>null</code>.</p> 
   * 
   * @param request The servlet request weare processing 
   * @param response The servlet response weare creating 
   * @param mapping The mapping we are using 
   */ 
  protectedActionForm processActionForm(HttpServletRequestrequest, 
                     HttpServletResponse response, 
                     ActionMapping mapping) { 
    // Create (if necessary) a form bean to use 
    ActionForm instance = RequestUtilscreateActionForm 
      (request, mapping, moduleConfig, servlet); 
    if (instance == null) { 
      return (null); 
    } 
 
      // Store the new instance in the appropriate scope 
    if (log.isDebugEnabled()) { 
      log.debug(" Storing ActionForm bean instance in scope &#39;" + 
       mapping.getScope() + "&#39; under attribute key &#39;" + 
       mapping.getAttribute() + "&#39;"); 
    } 
    if ("request".equals(mapping.getScope())) { 
      request.setAttribute(mapping.getAttribute(), instance); 
 
    } else { 
 
      HttpSession session =requestgetSession(); 
 
      session.setAttribute(mapping.getAttribute(), instance); 
 
    } 
 
    return (instance); 
 
  
 
}
로그인 후 복사

이 메서드의 일반적인 프로세스는 다음과 같습니다. ActionMapping의 이름을 기반으로 ActionForm을 찾습니다. ActionForm이 구성된 경우 요청으로 이동합니다. 또는 세션을 검색하면 해당 요청이나 세션에 생성된 ActionForm이 있으면 반환됩니다. 존재하지 않는 경우 ActionForm의 완료 경로에 따라 리플렉션을 사용하여 생성한 후 생성된 ActionForm을 요청 또는 세션에 배치한 후 ActionForm을 반환합니다.

구체적으로, 중단점 디버깅을 따라가면 이 메서드가 어떻게 실행되는지 확인할 수 있습니다.

먼저 중단점을 설정한 다음 processActionForm 메서드를 입력하세요.

첫 번째 단계는 ActionForm을 생성하는 것입니다.


// Create (if necessary) a formbean to use 
 
    ActionForm instance = RequestUtils.createActionForm 
 
      (request, mapping, moduleConfig, servlet); 
 
    if (instance == null) { 
 
      return (null); 
 
    }
로그인 후 복사

RequestUtils.createActionForm 메소드를 호출하여 ActionMapping의 ActionForm 문자열에서 객체를 생성하고 반환합니다. 다음 코드를 입력하세요.


publicstaticActionForm createActionForm( 
 
      HttpServletRequest request, 
 
      ActionMapping mapping, 
 
      ModuleConfig moduleConfig, 
 
      ActionServlet servlet) { 
 
  
 
    // Is there a form bean associated with this mapping? 
 
    String attribute = mappinggetAttribute(); 
 
    if (attribute == null) { 
 
      return (null); 
 
    } 
 
  
 
    // Look up the form bean configuration information to use 
 
    String name = mapping.getName(); 
 
    FormBeanConfig config =moduleConfigfindFormBeanConfig(name); 
 
    if (config == null) { 
 
      log.warn("No FormBeanConfig found under &#39;"+ name + "&#39;"); 
 
      return (null); 
 
    } 
 
  
 
    ActionForm instance = lookupActionForm(request,attribute, mappinggetScope()); 
 
  
 
    // Can we recycle the existing form bean instance (if there is one)? 
 
    try { 
 
      if (instance != null && canReuseActionForm(instance,config)) { 
 
        return (instance); 
 
      } 
 
    } catch(ClassNotFoundException e) { 
 
      log.error(servlet.getInternal().getMessage("formBean",config.getType()), e); 
 
      return (null); 
 
    } 
 
  
 
    return createActionForm(config,servlet); 
 
}
로그인 후 복사

메소드는 먼저 변수 이름을 정의하고 인스턴스의 LoginForm 문자열인 String name = mapping.getName();에서 값을 가져옵니다. 이후 FormBeanConfig config =moduleConfig.findFormBeanConfig(name);을 호출하여 해당 LoginForm 문자열을 해당 객체에 생성합니다.

여기서 설명하고 싶은 것은 struts-config 구성 파일에 다음과 같은 레이블 정보를 구성했다는 것입니다.


<form-beans> 
 
    <form-bean name="loginForm" type=".struts.LoginActionForm"/> 
 
  </form-beans>
로그인 후 복사

这个标签在服务器一启动的时候就会利用digester读取这里的配置信息,并且放在FormBeanConfig类中,这样我们可以通过上面那一句话就可以把LoginForm字符串生成相应的对象。

之后调用了ActionForm instance = lookupActionForm(request,attribute, mapping.getScope());这个方法,这个方法主要是查找scope属性中有没有存在ActionForm。具体实现:


if ("request".equals(scope)){ 
 
      instance = (ActionForm)request.getAttribute(attribute); 
 
    } else { 
 
      session = request.getSession(); 
 
      instance = (ActionForm)session.getAttribute(attribute); 
 
    }
로그인 후 복사

这里判断scope属性值是否为request,如果是则从request中读出ActionForm,如果不是则从session中读出。程序如果是第一次执行,那么ActionForm会是为空的。因为这里的ActionForm为空,所以就进入了if判断语句中,最后通过调用return createActionForm(config, servlet);创建ActionForm并且返回。

之后processActionForm就会把返回来的ActionForm放入request或者session中。具体实现就是:


if ("request".equals(mapping.getScope())){ 
 
      request.setAttribute(mapping.getAttribute(), instance); 
 
    } else { 
 
      HttpSession session =request.getSession(); 
 
      session.setAttribute(mapping.getAttribute(), instance); 
 
    }
로그인 후 복사

到此为止,ActionForm就创建完成,当ActionForm创建完成之后,就要用其他的方法来往ActionForm中赋值了

위 내용은 Struts1 ActionMapping 예제 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!