Pavel
Pavel

Reputation: 138

How to set a session attribute after clicking a link?

I have a jsp page with multiple links created inside a loop. All the links go to exactly one another jsp page. In the second jsp page I need to find out which link was clicked in the first jsp page. How can I do that ? Is there any way after clicking a link in the first jsp page I can set an attribute instantly, so that in the second page I can get that attribute to determine which link was clicked ?

Here is my code of the loop with the links -- http://pastebin.com/J3JGu5jD

<%  
    System.out.println("Going inside loop");
    for(int i = 0; i < n_row ; i++)
    {
        course_name = dbManager.get_course_name(teachers_course_id_list[i]);
        course_id = teachers_course_id_list[i];
%>
        table = '<tr><td> <a href="MarkDistribution1.jsp?course_id_QSparam             
        ='+"<%=course_id%>"+'">'+ "<%=course_id%>" + ': ' + "<%=course_name%>"+'</td>  
        </a></tr>'
        document.write(table);
<%
    }
%>

PS: Another question. I have a string variable link. is this the proper way to assign it to the javascript variable --- javascript_variable = <%=link%> ?

Upvotes: 0

Views: 6400

Answers (3)

Pavel
Pavel

Reputation: 138

This is weird. I solved the problem by changing the code like this,

<%  
    String link;
    System.out.println("Going inside loop");
    for(int i = 0; i < n_row ; i++)
    {
    course_name = dbManager.get_course_name(teachers_course_id_list[i]);
    course_id = teachers_course_id_list[i];
    link = "<tr><td> <a 
    href=\"MarkDistribution1.jsp?course_id_QSParam="+course_id+"\">"+course_id+":
    "+course_name+"</td></a></tr>";
%>
    table = '<%=link%>'
    document.write(table);
<%
    }   
%>

Assigned java variable link inside the java script variable table using single quote. Thanks anyway guys.

Upvotes: 0

Vinoth Krishnan
Vinoth Krishnan

Reputation: 2949

Correct way of your code is

<tr>
    <td> 
        <a href="MarkDistribution1.jsp?course_id_QSparam="+<%=course_id%>'></a>
    </td>  
</tr>

The mistake you did was closed the <td> before <a> tag. You can add the remaining parameters like this.

Upvotes: 0

Ker p pag
Ker p pag

Reputation: 1588

don't use scriptlet please. you could use JSTL foreach tag

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

then use the loop in your jsp, you can use GET method to know which link is clicked

<c:foreach items="${yourarray}" var="link">

     <a href="myController?link=1"><c:out value="${link}"/></a>

</c:foreach>

and in you controller catch the parameter

doGet(HttpServletRequest request,HttpServletResponse response){


   String theLink="";
   if(request.getParameter("link")!=null){
      theLink= request.getParameter("link");
      request.getSession(true).setAttribute("clickedLink",theLink);
    }
  }

Upvotes: 1

Related Questions