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".
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()); %>
or <%=getB()%>
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) %>