-1

The below jsp code is not giving output as expected

<%@page contentType="text/html" pageEncoding="UTF-8" buffer="none" autoFlush="true"%>
<%@page import="java.util.logging.Logger" %>


<%!  
    String test = "Hei you!!!"; 
    String test2="ok done"; 
%>  <%= test = (test + test2)%>

out put: (on sbusequent page refresh)

Hei you!!! ok done
Hei you!!! ok done
Hei you!!! ok done

expecting:(only on each request)

Hei you!!! ok done

I am not sure if the variable 'test' is stored in cache in jsp server or any binding occurs or variable in this case is stored in application/session scope. Any help is appreciable.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Manojak
  • 149
  • 2
  • 3
  • 10

2 Answers2

3

<%! %> is declaration section which means

String test = "Hei you!!!"; 
String test2="ok done"; 

will be fields in generated from jsp servlet, not local variables in jspService() method so each time you do

<%= test = (test + test2)%>

text field will be concatenated with value from test2.


In other words your code will generate code similar to

public class Problem extends SomeSpecialJSPHttpServlet {

    String test = "Hei you!!!"; 
    String test2 = "ok done"; 

    protected void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print(test = (test + test2));
    }
}

To print only test + test2 don't reassign this result to test so maybe just use

<%= test + test2 %>
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

try like this:

<%=(test + test2)%>
Ashish Ratan
  • 2,838
  • 1
  • 24
  • 50