简体   繁体   English

是否可以在JSP中定义方法并从servlet调用它

[英]Is it possible define a method in JSP and invoke it from a servlet

suppose the following JSP tag 假设以下JSP标签

<%! public void test(){} %>

Is it possible to define a method (eg the above test() method) in a jsp page and then call it from a servlet class? 是否可以在jsp页面中定义一个方法(例如上述test()方法),然后从servlet类调用它?
if the answer is yes, then how it can be done? 如果答案是肯定的,那该怎么办呢? if the answer is no, then why? 如果答案是否定的,那为什么呢?

(I know that before running a JSP page the web server complies it into a servlet class) (我知道在运行JSP页面之前,Web服务器会将其编译为Servlet类)

What normally happens is you map the request to the servlet, and the servlet forwards to the JSP. 通常发生的情况是将请求映射到servlet,然后servlet转发到JSP。

String nextJSP = "/searchResults.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);

You can't invoke a method on your JSP, because the servlet does not have access to the compiled JSP directly, it only has access to the dispatcher. 您不能在JSP上调用方法,因为Servlet无法直接访问已编译的JSP,而只能访问调度程序。

But what usually is done, is setting of request attributes in the servlet and then the JSP can pick these up. 但是通常要做的是在servlet中设置请求属性,然后JSP可以选择这些属性。

So in the top of the JSP, you could do something like 因此,在JSP的顶部,您可以执行以下操作

<% if(request.getAttribute("doTest")) then test(); %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM