简体   繁体   中英

How to use declaration tag in JSP?

I have one method and i took one variable int b=10 & i want to print this value in display method. How can i do it ?

<%!
int b=10;
public void display()
{
    out.print(b);
}
%>

But it is giving error like, "Out cannot be resolved".

Scriptlets are executed inside service method and each time this method is invoked to handle some request it needs to create its own set of local variables to not collide with other invocations of service method which will handle different request. One of this local variables is out .

Since <%! ... %> <%! ... %> is responsible for declaring code at class-level it doesn't have access to local variables of service method.

If you really need to have access to out you can pass it to display method as argument like

public void display(JspWriter out) //javax.servlet.jsp.JspWriter 
{
    out.print(b);
}

You could also create other method, which instead of being responsible for displaying, will return content to display like

public int getB()
{
    return b;
}

You can use it in scriptlet with out like <% out.print(getB()); %> <% out.print(getB()); %> or <%=getB()%>

But you should avoid scriptlets .

A scriptlet is introduced with <%, not <%!. Additionally, there is a bit of information missing. Is this running within a JSP file within a server like, for example, Tomcat?

The "out" variable should be defined as it is a standard predefined variable in a JSP.

Whatever placed inside a declaration tags gets initialized during JSP initialization phase. So the implicit object "out" is not yet available here.

If you really need to output something within your own method (in the jsp class) you can do like that:

<%!
int b=10;
public void display(HttpServletResponse res) {
    try {
        res.getWriter().write(b) ;
    } catch (IOException e) {
        //
    }
}
%>

and later in the jsp:

<%= display(response) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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