3

I have a tool (say mytool.com). When a user logs into the tool, I want to use information about the user (like what groups he is part of) to display some links.

For example, user A logs in and I know that user A will be able to to view item "abc" in category 111; so I will display a link on the page which will take the user to that item (something like mytool.com/items/111/abc).

My question is how do I generate these links in JSP. When a user logs in, I call a service to get a list of categories and items he can view (111 and "abc" in this case). How do I correctly translate that into links in JSP?

Additional information: I want to avoid having Java code in JSP. I am also using Spring mvc. Based on some comments it looks like I should generate the url in the controller and put it in the model and then have the JSP read it. Is that the correct way of going about it?

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
jay electricity
  • 299
  • 5
  • 15

1 Answers1

4

You can use JSTL to achieve this:

When calling your jsp:

  List<Product> products=getProductFromDB();
  request.setAttribute("products", products);//List of products

JSP:

<table>
 <c:foreach items="${products}" var="product">
     <tr>
         <td>
            <a href="${pageContext.request.contextPath}/items/${product.category}/${product.name}">${product.name}</a>
         <td>
     </tr>
 </c:foreach>
</table>

Spring Controller:

  @RequestMapping(value = "/items/{category}/{name}", method=RequestMethod.GET)
  public String getItem(@PathVariable("category") String category, @PathVariable("name") String name){
     String productname= name;
     String category=category;
     //Do your stuff
  }

Incase if you are not familiar with JSTL, take look at here.

Sas
  • 2,473
  • 6
  • 30
  • 47