How to dynamically create URLs in JSP?

I have a tool (say mytool.com). When a user logs into a tool, I want to use the user's information (like which groups they are part of) to display some links.

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

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

More info: I want to avoid using Java code in JSP. I am also using Spring mvc. Based on some of the comments, it looks like I should generate the url in the controller and put it in the model, then read the JSP. Is this the correct way to get around this?

+3


source to share


1 answer


You can use JSTL for this:

When calling 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
  }

      

If you are not familiar with JSTL take a look here .

+4


source







All Articles