0

i have two file abc.jsp & def.jsp. in abc.jsp, it contains this code:

<%
        String selectedCourse = request.getParameter("course");
        int count = 0;

        if(selectedCourse.equals("PHP")){
            count = count + 1;
        }

    %> 

i want this count value in def.jsp, so how can i pass this value?

Axon
  • 59
  • 1
  • 5
  • 2
    Check this one https://stackoverflow.com/questions/18763168/sending-variable-from-one-jsp-to-another-jsp – Sana Jul 15 '19 at 10:09
  • i want to pass integer, i can pass string, but can't pass integer! – Axon Jul 15 '19 at 10:28
  • Exactly the same way, just use `Integer` and not `int` (i.e. object, not the primitive type). – Jozef Chocholacek Jul 15 '19 at 10:53
  • i don't get it :/ can u explain with this code pls? – Axon Jul 15 '19 at 10:58
  • 1
    Everytime you come to `abc.jsp` page you intialize your count to `0` , So previous value it has in it will get lost .Try to store `count` in `session` and retreive count from `session` and then add it with `1` , also has `count` is already in session you can get that in any page i.e by writing `int count = session.getAttribute("count"); ` . – Swati Jul 15 '19 at 11:32

2 Answers2

1

abc.jsp

<%!
private synchronized void incrementCounter() {
  Integer count = session.getAttribute("count");
  if (count == null) {
    count = new Integer(0);
  }
  count++;
  session.setAttribute("count", new Integer(count));
}
%>

<%
String selectedCourse = request.getParameter("course");
if(selectedCourse.equals("PHP")){
  incrementCounter();
}
%> 

def.jsp

<%
int count = session.getAttribute("count"); 
%>

Anyway, such logic should not be in JSP, but belongs into a controller (servlet).

Jozef Chocholacek
  • 2,874
  • 2
  • 20
  • 25
0

Use Session Attributes

abc.jsp

<%
    String selectedCourse = request.getParameter("course");
    int count = 0;

    if(selectedCourse.equals("PHP")){
        count = count + 1;
    }
     session.setAttribute("count", count);
%> 

def.jsp

int count1 = Integer.parseInt(session.getAttribute("count").toString());

out.write("count:"+count1);
Sana
  • 360
  • 3
  • 13
  • not working, getting the initialize value of count 0 always! – Axon Jul 15 '19 at 11:15
  • int count1 = Integer.parseInt(session.getAttribute("count").toString()); out.write("count:"+count1); – Sana Jul 15 '19 at 11:37
  • int count1 = Integer.parseInt(session.getAttribute("count").toString()); is not working, it catches nullPointerException after running! – Axon Jul 15 '19 at 16:42