2013-10-07 4 views
1

의도 한대로 작동하도록 일부 속성 (런타임 중에 사용자가 설정 함)이 필요한 구성 요소로 작업하고 있습니다.Java 클래스에서 구성 요소 속성에 액세스하는 방법

초기에는 properties.get('foo')을 사용하여 구성 요소에서 필요한 속성을 가져 왔지만 구성 요소 JSP 파일에서 스크립트 추적 코드의 모든 흔적을 제거하려고합니다.

Java 코드 내에서 'foo'(런타임에 구성 요소에 설정 됨) 속성을 가져 오는 방법은 무엇입니까? 나는 valueMap과를 사용하는 것이 가장 좋은 방법이라고 어딘가에서 읽은 기억, 그래서 나는 이것을 사용하여 시도 : -

public static Map<String, Object> getResourceProperties(String path, 
      SlingHttpServletRequest request) { 
     ResourceResolver resourceResolver = request.getResourceResolver(); 
     Map<String, Object> props= new HashMap<String, Object>(); 
     Resource resource = resourceResolver.getResource(path); 
     if (null != resource) { 
      props.putAll(resource.adaptTo(ValueMap.class)); 
     } 
     return props; 
    } 

이 내 JSP에서 : - <c:set var="refProperties" value="${xyz:getResourceProperties(properties.path,slingRequest)}" />

을하지만 이것은 내가 원하는 값을 반환하지 않습니다.

답변

5

이 작업을 수행하는 가장 간단한 방법은 /libs/foundation/global.jsp을 포함하고 properties 개체를 이미 범위 ${properties.foo}에 사용하는 것입니다. 그것은 기본적으로 슬링 (슬링), CQ (CQ)와 JSTL를 등록 나타내는 파일의 주석으로

<%@include file="/libs/foundation/global.jsp"%> 

:

는 너무 같은 구성 요소 JSP의 상단에 global.jsp 포함 (c, fmt, fn) taglib 네임 스페이스를 JSP에서 사용합니다.

그런 다음 cq:defineObjects taglib의 도움을 받아 많은 유용한 객체를 범위로 가져옵니다. defineObjects 이미 JSP 표현 언어 (EL)을 통해 등록 된 valueMap에 액세스 할 수있는 태그 라이브러리 :

@param slingRequest SlingHttpServletRequest 
@param slingResponse SlingHttpServletResponse 
@param resource the current resource 
@param currentNode the current node 
@param log default logger 
@param sling sling script helper 

@param componentContext component context of this request 
@param editContext edit context of this request 
@param properties properties of the addressed resource (aka "localstruct") 
@param pageManager page manager 
@param currentPage containing page addressed by the request (aka "actpage") 
@param resourcePage containing page of the addressed resource (aka "myPage") 
@param pageProperties properties of the containing page 
@param component current CQ5 component 
@param designer designer 
@param currentDesign design of the addressed resource (aka "actdesign") 
@param resourceDesign design of the addressed resource (aka "myDesign") 
@param currentStyle style of the addressed resource (aka "actstyle") 

이 단순히 CQ를 사용하여 의미합니다 : 여기

<cq:defineObjects /> 

은 목록입니다. JSP 내의 등록 정보에 액세스하기 위해 추가 변환이 필요하지 않습니다.

<c:out value="${properties.foo}" /> 

자신의 Java taglib 또는 bean의 속성에 액세스하려면 표준 JSTL 태그를 사용하여 코드에 적절한 객체를 전달하면됩니다. 전체 요청, 현재 자원 또는 속성 만 전달할 수 있습니다. 전체 요청을 전달하면 Java 코드가 현재 리소스 및 ValueMap 속성을 포함하여 cq : defineObjects taglib에 의해 생성 된 모든 객체에 액세스 할 수 있습니다. JSP에서

:

<jsp:useBean id="mybean" scope="request" class="com.my.impl.TheBean"> 
    <jsp:setProperty name="mybean" property="slingRequest" value="${slingRequest}"/> 
    <jsp:setProperty name="mybean" property="resource" value="${resource}"/> 
    <jsp:setProperty name="mybean" property="properties" value="${properties}"/> 
</jsp:useBean> 

콩에서 :

public void setSlingRequest(final SlingHttpServletRequest slingRequest) { 
    this.slingRequest = slingRequest; 
    // Use the one created by cq:defineObjects 
    this.properties = (ValueMap)this.slingRequest.getAttribute("properties"); 
    // OR adapt the resource 
    this.properties = this.slingRequest.getResource().adaptTo(ValueMap.class); 
} 

public void setResource(final Resource resource) { 
    this.resource = resource; 
    this.properties = this.resource.adaptTo(ValueMap.class); 
} 

public void setProperties(final ValueMap properties) { 
    this.properties = properties; 
} 
+1

동의 ... 이것은 가장 간단한 방법입니다. 왜 내가 이것을 사용하지 않았는지 모르겠다. 왜 더 나쁜가는 내가 글로벌하게 들여다 보았다.jsp 그리고 이것이 내가'resource'를 사용하여 속성에 접근하는 방법을 발견 한 곳입니다. – bongman1612

0

Java 파일에서 JCR 세션을 가져온 다음 노드 (content/your_site_name/node/some_parsys)을 반복합니다. 그런 다음 런타임에 작성자가 설정 한 값을 가져올 수 있습니다.

if(node.hasProperty("title")){ 
    String title=node.getProperty().getValue().getString(); 
} 
1

이 경우, 모든 리소스 속성이 포함 된 Map<String, Object>을 만들려고합니다. 이지도는 properties 개체와 같을 것이며 (따라서 Map이기도합니다.) 따라서 전체 메서드가 중복되는 것 같아요. 그리고 쓸 때 - 작동하지 않습니다. properties 개체에는 path 메서드가 포함되어 있지 않으므로 아마도 작동하지 않습니다.

request.getResource() (경로별로 해결 자 및 리소스를받는 대신) request.getResource()을 사용했을 수 있습니다. 또한 resourceValueMap으로 변경하는 대신 JSP에서 간단한 패스 properties을 가질 수 있습니다.

더 일반적으로 JSP에서 Java 클래스로 로직을 추출하려면 model 클래스를 생성하고 slingRequest을 생성자에 전달한 다음 JSP에서 해당 메소드를 호출하는 것이 좋습니다. 예 :

GET.jsp

<c:set var="model" value="<%= new MyModel(slingRequest) %>" /> 
Result of the first method: ${model.firstValue}<br/> 
Result of the second method: ${model.secondValue} 

MyModel.java

public class MyModel { 
    private final SlingHttpServletRequest request; 

    private final Resource resource; 

    private final ValueMap properties; 

    public MyModel(SlingHttpServletRequest request) { 
     this.request = request; 
     this.resource = request.getResource(); 
     this.properties = resource.adaptTo(ValueMap.class); 
    } 

    public String getFirstMethod() { 
     // do some clever things 
     return ""; 
    } 

    public String getSecondMethod() { 
     // do more clever things 
     return ""; 
    } 
} 

당신이 ${model.firstMethod}를 호출 할 경우 메소드 이름에 get 접두사를 추가 (getFirstMethod())가 필요 통지하십시오 .

<jsp:useBean id="mycomponent" scope="request" class="com.company.components.SomeComponent"> 
    <jsp:setProperty name="mycomponent" property="request" value="<%= slingRequest %>"/> 
</jsp:useBean> 

가 그럼 그냥 클래스에서 세터를 만들 :

+0

내가 같은 오류가 점점 계속 그렇게 : -'정적 context'이를 사용할 수 없습니다. 왜 이것이 사실인지 아십니까? 'request.getResource()'를 사용하는 이유는 내 페이지에 동일한 구성 요소의 인스턴스가 6 개 있기 때문입니다. 작성자가 전달하는 매개 변수는 모든 인스턴스마다 다를 수 있습니다. 즉, 경로가 1 개인 리소스를 만드는 것이 실제로 도움이되지는 않습니다. – bongman1612

+0

이 오류는'this' 키워드를 사용하려고 시도하는'static' 메쏘드 (예제의 생성자 라기보다는)가 있음을 암시합니다. –

1

나는 당신이 필요로하는 어떤 정보를 줄 수있는 클래스의 인스턴스를 생성하기 위해 useBean에서 태그를 사용합니다. 그런 다음 JSP에서

public void setRequest(final SlingHttpServletRequest request) { 
    this.request = request; 
    //or more likely an init() method that inits all your props 
    //you could even use reflection to look for props that match all the field names 
    //to init them automatically 
    ValueMap props=request.getResource().adaptTo(ValueMap.class) 
    this.interestingProp= props.get("interestingProp"); 
} 

public String getInterestingProp(){ 
    return this.interestingProp; 
} 

:

<c:out value="${mycomponent.interestingProp}"/> 
0

그럼 난 내 자신의 질문에 대답 관리 않았다. 내가 한 모든 일은 내 JSP에 resource.path을 사용하는 것이 었습니다.

자원 여기에 문제의 구성 요소를 의미하고, 그래서 내가 제대로 내 valueMap과을 만들 수 있었던 경로를 사용하여. 다음과 같이

그래서, 내 JSP 파일의 코드는 다음과 같습니다 -

<c:set var="refProperties" value="${xyz:getResourceProperties(resource.path,slingRequest)}"\> 

, 나는 지금 내가 원하는 구성 요소의 모든 속성을 참조 할 수 있습니다이 사용 : -

${refProperties.foo} 

resource.path을 사용하려면 global.jsp도 포함해야합니다. 그렇지 않으면 인식되지 않습니다.

관련 문제