我可以在组件.jsp中使用方法吗?

时间:2013-11-14 16:03:18

标签: jsp cq5

我正在尝试根据Adobe网站上的一篇文章编写一个简单的服务层接口(链接显示在代码头中以供参考)。当我尝试基于模板/组件加载页面时,我收到一个错误:方法[methodname]未定义类型[componentname] _jsp。我尝试使用更简单的单行方法,使用public和no访问修饰符,不同的签名和返回类型,将方法移动到调用代码上方,并始终获得相同的结果。如果我注释掉方法名称并将代码作为大括号括起来的块包含,那么它编译好了。这在CQ / AEM v5.6.1中是不可能的,还是我做错了什么?

下面显示了整个代码和异常(为了简单起见,省略了各种实验版本的注释和原始的getPath(...)方法)。提前感谢您的时间。

<%--

    apipage component: implements service layer pages
    see: http://blogs.adobe.com/contentmanagement/2012/08/19/how-to-integrate-with-other-web-services-without-creating-osgi-packages/

--%><%
%><%@include file="/libs/foundation/global.jsp"%>
  <%@page import="org.apache.commons.httpclient.HttpClient,
                  org.apache.commons.httpclient.params.HttpClientParams,
                  org.apache.commons.httpclient.DefaultHttpMethodRetryHandler,
                  org.apache.commons.httpclient.methods.PostMethod,
                  org.json.JSONObject"
%><%@page session="false" %><%
%><%
    if (request.getParameter("action") != null) {
        if (request.getParameter("action").equals("getFields") &&
                request.getParameter("param1") != null &&
                    request.getParameter("param2") != null) {
            //response.setContentType("application/json");
            //          out.write(getPath((String)request.getParameter("param1"), (String)request.getParameter("param2"));
            String str1 = "param1";
            String str2 = "param2";
            //out.write(getPath(str1, str2));
            int i = doNothing();
        }
    } else {
        response.setContentType("application/json");
        out.write("{\"error\":\"error\"}");
    }

    /*public*/ int doNothing() {
        return 1;
    }
%>

Error during include of component '/apps/trp/components/layouts/apipage'
Error Message:

org.apache.sling.api.scripting.ScriptEvaluationException: org.apache.sling.scripting.jsp.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 24 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp
The method doNothing() is undefined for the type apipage_jsp
21:             String str1 = "param1";
22:             String str2 = "param2";
23:             //out.write(getPath(str1, str2));
24:             int i = doNothing();
25:         }
26:     } else {
27:         response.setContentType("application/json");


An error occurred at line: 31 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp
Syntax error on token "int", new expected
28:         out.write("{\"error\":\"error\"}");
29:     }
30: 
31: /*public*/ int doNothing() {
32:         return 1;
33:     }
34: 


An error occurred at line: 31 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp
doNothing cannot be resolved to a type
28:         out.write("{\"error\":\"error\"}");
29:     }
30: 
31: /*public*/ int doNothing() {
32:         return 1;
33:     }
34: 


An error occurred at line: 31 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp
Syntax error, insert ";" to complete Statement
28:         out.write("{\"error\":\"error\"}");
29:     }
30: 
31: /*public*/ int doNothing() {
32:         return 1;
33:     }
34: 


An error occurred at line: 32 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp
Void methods cannot return a value
29:     }
30: 
31: /*public*/ int doNothing() {
32:         return 1;
33:     }
34: 
35: /*

Processing Info:
Page    =   /content/trp/en/AfrescoAPI  
Resource Path   =   /content/trp/en/AfrescoAPI/jcr:content  
Cell    =   apipage 
Cell Search Path    =   apipage 
Component Path  =   /apps/trp/components/layouts/apipage    
Sling Request Progress:

      0 (2013-11-14 10:41:01) TIMER_START{Request Processing}
      0 (2013-11-14 10:41:01) COMMENT timer_end format is {<elapsed msec>,<timer name>} <optional message>
      0 (2013-11-14 10:41:01) LOG Method=GET, PathInfo=/content/trp/en/AfrescoAPI.html
      0 (2013-11-14 10:41:01) TIMER_START{ResourceResolution}
      0 (2013-11-14 10:41:01) TIMER_END{0,ResourceResolution} URI=/content/trp/en/AfrescoAPI.html resolves to Resource=JcrNodeResource, type=cq:Page, superType=null, path=/content/trp/en/AfrescoAPI
      0 (2013-11-14 10:41:01) LOG Resource Path Info: SlingRequestPathInfo: path='/content/trp/en/AfrescoAPI', selectorString='null', extension='html', suffix='null'
      0 (2013-11-14 10:41:01) TIMER_START{ServletResolution}
      0 (2013-11-14 10:41:01) TIMER_START{resolveServlet(JcrNodeResource, type=cq:Page, superType=null, path=/content/trp/en/AfrescoAPI)}
      0 (2013-11-14 10:41:01) TIMER_END{0,resolveServlet(JcrNodeResource, type=cq:Page, superType=null, path=/content/trp/en/AfrescoAPI)} Using servlet /libs/foundation/components/primary/cq/Page/Page.jsp
      0 (2013-11-14 10:41:01) TIMER_END{0,ServletResolution} URI=/content/trp/en/AfrescoAPI.html handled by Servlet=/libs/foundation/components/primary/cq/Page/Page.jsp
      0 (2013-11-14 10:41:01) LOG Applying Requestfilters
      0 (2013-11-14 10:41:01) LOG Calling filter: org.apache.sling.bgservlets.impl.BackgroundServletStarterFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: org.apache.sling.i18n.impl.I18NFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: org.apache.sling.rewriter.impl.RewriterFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.designimporter.CanvasPageDeleteRequestFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.adobe.cq.history.impl.HistoryRequestFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.core.impl.WCMRequestFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.adobe.granite.optout.impl.OptOutFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.theme.impl.ThemeResolverFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.foundation.forms.impl.FormsHandlingServlet
      0 (2013-11-14 10:41:01) LOG Calling filter: org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.mobile.core.impl.redirect.RedirectFilter
      0 (2013-11-14 10:41:01) LOG RedirectFilter did not redirect (MobileUtil.isMobileResource() returns false)
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.core.impl.warp.TimeWarpFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.core.impl.AuthoringUIModeServiceImpl
      0 (2013-11-14 10:41:01) LOG Applying Componentfilters
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.personalization.impl.TargetComponentFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.core.impl.WCMComponentFilter
      0 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.core.impl.WCMDebugFilter
      0 (2013-11-14 10:41:01) TIMER_START{/libs/foundation/components/primary/cq/Page/Page.jsp#0}
      0 (2013-11-14 10:41:01) LOG Including resource JcrNodeResource, type=trp/components/layouts/apipage, superType=null, path=/content/trp/en/AfrescoAPI/jcr:content (SlingRequestPathInfo: path='/content/trp/en/AfrescoAPI/jcr:content', selectorString='null', extension='html', suffix='null')
      0 (2013-11-14 10:41:01) TIMER_START{resolveServlet(JcrNodeResource, type=trp/components/layouts/apipage, superType=null, path=/content/trp/en/AfrescoAPI/jcr:content)}
     16 (2013-11-14 10:41:01) TIMER_END{16,resolveServlet(JcrNodeResource, type=trp/components/layouts/apipage, superType=null, path=/content/trp/en/AfrescoAPI/jcr:content)} Using servlet /apps/trp/components/layouts/apipage/apipage.jsp
     16 (2013-11-14 10:41:01) LOG Applying Includefilters
     16 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.personalization.impl.TargetComponentFilter
     16 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.core.impl.WCMComponentFilter
     16 (2013-11-14 10:41:01) LOG Calling filter: com.day.cq.wcm.core.impl.WCMDebugFilter
     16 (2013-11-14 10:41:01) TIMER_START{/apps/trp/components/layouts/apipage/apipage.jsp#1}
    156 (2013-11-14 10:41:01) LOG SCRIPT ERROR: org.apache.sling.scripting.jsp.jasper.JasperException: Unable to compile class for JSP: //An error occurred at line: 24 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp/The method doNothing() is undefined for the type apipage_jsp/21:             String str1 = "param1";/22:             String str2 = "param2";/23:             //out.write(getPath(str1, str2));/24:             int i = doNothing();/25:         }/26:     } else {/27:         response.setContentType("application/json");///An error occurred at line: 31 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp/Syntax error on token "int", new expected/28:         out.write("{\"error\":\"error\"}");/29:     }/30: /31: /*public*/ int doNothing() {/32:       return 1;/33:   }/34: ///An error occurred at line: 31 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp/doNothing cannot be resolved to a type/28:         out.write("{\"error\":\"error\"}");/29:     }/30: /31: /*public*/ int doNothing() {/32:         return 1;/33:   }/34: ///An error occurred at line: 31 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp/Syntax error, insert ";" to complete Statement/28:         out.write("{\"error\":\"error\"}");/29:     }/30: /31: /*public*/ int doNothing() {/32:         return 1;/33:   }/34: ///An error occurred at line: 32 in the jsp file: /apps/trp/components/layouts/apipage/apipage.jsp/Void methods cannot return a value/29:     }/30: /31: /*public*/ int doNothing() {/32:         return 1;/33:   }/34: /35: /*/
    156 (2013-11-14 10:41:01) TIMER_END{140,/apps/trp/components/layouts/apipage/apipage.jsp#1}
    172 (2013-11-14 10:41:01) LOG Found processor for post processing ProcessorConfiguration: {contentTypes=[text/html],order=-1, active=true, valid=true, processErrorResponse=true, pipeline=(generator=Config(type=htmlparser, config={}), transformers=(Config(type=linkchecker, config={}), Config(type=mobile, config=JcrPropertyMap [node=node /libs/cq/config/rewriter/default/transformer-mobile, values={component-optional=true, jcr:primaryType=nt:unstructured}]), Config(type=mobiledebug, config=JcrPropertyMap [node=node /libs/cq/config/rewriter/default/transformer-mobiledebug, values={component-optional=true, jcr:primaryType=nt:unstructured}]), Config(type=contentsync, config=JcrPropertyMap [node=node /libs/cq/config/rewriter/default/transformer-contentsync, values={component-optional=true, jcr:primaryType=nt:unstructured}]), serializer=Config(type=htmlwriter, config={}))}
    172 (2013-11-14 10:41:01) TIMER_END{172,Request Processing} Dumping SlingRequestProgressTracker Entries

2 个答案:

答案 0 :(得分:3)

Scriptlets是魔鬼。你永远不应该使用scriptlet。忘记它们甚至存在。学习JSP EL和JSTL。使用MVC框架。

那就是说,这就是为什么你的代码不起作用的原因。 <%%>内的所有内容都是为JSP生成的servlet的服务方法内部的代码。那么,以下JSP:

<html>
    <% System.out.println("hello"); %>
</html>
容器在容器中转换

,如下所示:

public class YourJsp extends JspServlet {

    public void jspService(HttpServletRequest request, HttpServletResponse response) {
        JspWriter out = createJspWriter(response);
        out.println("<html>");
        System.out.println("hello");
        out.println("</html>");
    }
}

您可以推断出上述示例,您的代码将被翻译为类似

的内容
    public void jspService(HttpServletRequest request, HttpServletResponse response) {
        ...

        int doNothing() {
           return 1;
        }
    }

因此会在另一个方法中声明一个方法。这将是无效的Java代码,这就是您的JSP无效的原因。

要在JSP中声明方法,需要以下语法(请注意感叹号,这意味着“声明”):

<%!
    int doNothing() {
        return 1;
    }
%>

上面的代码将是生成的servlet类的一部分,而不是其jspService()方法的一部分。

那说:你不应该在JSP中有scriptlet。更少的方法。这应该是Java源文件。 Scriptlet已经淘汰了10多年。 JSP是视图组件,其唯一的责任应该是从用Java编写的控制器准备的数据生成HTML标记。

答案 1 :(得分:2)

您需要使用声明语法(&lt;%!...%&gt;):

<%! 
   public  int doNothing() { 
      return 1;
   } 
%>
<%
   int test = doNothing(); 
%>