찾다
Javajava지도 시간Struts1의 ActionMapping 예제에 대한 자세한 설명

이 기사는 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Java 플랫폼 독립성 : 다른 OS와의 호환성Java 플랫폼 독립성 : 다른 OS와의 호환성May 13, 2025 am 12:11 AM

javaachievesplatformincendenceThoughthehoughthejavavirtualmachine (JVM), hittoutModification.thejvmcompileSjavacodeIntOplatform-independentByTecode, whatitTengretsAndexeSontheSpecoS, toplacetSonthecificos, toacketSecificos

Java가 여전히 강력하게 만드는 기능Java가 여전히 강력하게 만드는 기능May 13, 2025 am 12:05 AM

javaispowerfuldueToitsplatformincendence, 객체 지향적, RichandardLibrary, PerformanceCapabilities 및 StrongSecurityFeatures.1) Platform IndependenceAllowsApplicationStorunannyDevicesUpportingjava.2) 대상 지향적 프로그래밍 프로모션 Modulara

최고 Java 기능 : 개발자를위한 포괄적 인 가이드최고 Java 기능 : 개발자를위한 포괄적 인 가이드May 13, 2025 am 12:04 AM

최고 Java 기능에는 다음이 포함됩니다. 1) 객체 지향 프로그래밍, 다형성 지원, 코드 유연성 및 유지 관리 가능성 향상; 2) 예외 처리 메커니즘, 시도 캐치-패치 블록을 통한 코드 견고성 향상; 3) 쓰레기 수집, 메모리 관리 단순화; 4) 제네릭, 유형 안전 강화; 5) 코드를보다 간결하고 표현력있게 만들기위한 AMBDA 표현 및 기능 프로그래밍; 6) 최적화 된 데이터 구조 및 알고리즘을 제공하는 풍부한 표준 라이브러리.

Java는 진정으로 플랫폼이 독립적입니까? '한 번 쓰기, 어디서나 달리는'방법이 작동하는 방법Java는 진정으로 플랫폼이 독립적입니까? '한 번 쓰기, 어디서나 달리는'방법이 작동하는 방법May 13, 2025 am 12:03 AM

javaisnotentirelyplatformindent의 의존적 duetojvmvariationsandnativecodeintegration

JVM을 탈취 : Java 실행을 이해하는 열쇠JVM을 탈취 : Java 실행을 이해하는 열쇠May 13, 2025 am 12:02 AM

TheJavavirtualMachine (JVM) isanabstractcomputingmachinecrucialforjavaexecutionasitsjavabytecode, "writeonce, runanywhere"기능을 가능하게합니다

Java는 여전히 새로운 기능을 기반으로 좋은 언어입니까?Java는 여전히 새로운 기능을 기반으로 좋은 언어입니까?May 12, 2025 am 12:12 AM

javaremainsagoodlugageedueToitscontinuousevolutionandrobustecosystem.1) lambdaexpressionsenhancececeadeabilitys.2) Streamsallowforefficileddataprocessing, 특히 플레어로드 라트 웨이션

Java가 위대하게 만드는 이유는 무엇입니까? 주요 기능과 이점Java가 위대하게 만드는 이유는 무엇입니까? 주요 기능과 이점May 12, 2025 am 12:11 AM

javaisgreatduetoitsplatform incendence, robustoopsupport, extensibraries 및 strongcommunity.1) platforminceptenceviajvmallowscodetorunonvariousplatforms.2) oopeatures inncapsulation, Nheritance, and Polymorphismenblularandscode.3)

상위 5 개의 Java 기능 : 예와 설명상위 5 개의 Java 기능 : 예와 설명May 12, 2025 am 12:09 AM

Java의 5 가지 주요 특징은 다형성, Lambda Expressions, Streamsapi, 제네릭 및 예외 처리입니다. 1. 다형성을 사용하면 다른 클래스의 물체가 공통 기본 클래스의 물체로 사용될 수 있습니다. 2. Lambda 표현식은 코드를보다 간결하게 만듭니다. 특히 컬렉션 및 스트림을 처리하는 데 적합합니다. 3.StreamSapi는 대규모 데이터 세트를 효율적으로 처리하고 선언적 작업을 지원합니다. 4. 제네릭은 유형 안전 및 재사용 성을 제공하며 편집 중에 유형 오류가 잡히립니다. 5. 예외 처리는 오류를 우아하게 처리하고 신뢰할 수있는 소프트웨어를 작성하는 데 도움이됩니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.