Question

What's the proper way to create a hyperlink in Spring+JSP? There must be a better way than just coding in the <a href="..."> tag. Take for example a page that displays people. The URL is people.htm. The corresponding controller gets people from the database and performs optional column sorting. The JSP might look like:

<table>
<tr>
  <td><a href="people.htm?sort=name">Name</a></td>
  <td><a href="people.htm?sort=age">Age</a></td>
  <td><a href="people.htm?sort=address">Address</a></td>
</tr>
...

This seems bad as the URL people.htm is hardcoded in the JSP. There should be a way to have Spring automatically build the <a> tag using the URL defined in servlet.xml.

Edit: Maybe I should be using a Spring form.

Was it helpful?

Solution

The only thing that comes to mind is the JSTL standard tag <c:url>. For example:

<c:url var="thisURL" value="homer.jsp">
  <c:param name="iq" value="${homer.iq}"/>
  <c:param name="checkAgainst" value="marge simpson"/>
</c:url>
<a href="<c:out value="${thisURL}"/>">Next</a>

Now this won't get you servlet mapping or the like but nothing will. It's not something you could really do programmatically (after all, a servlet can and usually does map to a range of URLs). But this will take care of escaping for you.

OTHER TIPS

I haven't seen this kind of functionality in pure spring (although grails offers things like that).

For your specific case you might consider removing the file part and only using the query string as the href attribute:

<td><a href="?sort=name">Name</a></td>
<td><a href="?sort=age">Age</a></td>
<td><a href="?sort=address">Address</a></td>

These links append the query string to the path component of the current url.

Better way to create link is:

<a href="<%=request.getContextPath() %>/people">Name</a>

<%=request.getContextPath() %> makes sure that correct URI will be taken into account.

"sort" parameter you can get over with hidden field and change a value with a little bit of javascript:

<input type="hidden" name="sort" id="sort" value="name">

And controller method should look like this:

@RequestMapping("/people")
public String createUser(String sort) {

   ...

}

In Spring MVC in jsp:

You can use:

General Hyperlink:

<a href="/Portfolio/login">Click Here</a>

If passing from controller:

<a href="/Portfolio/${page}">Click Here</a>

Jsp tags

<c:url var="URL" value="login">
<c:param name="param" value="${parameter}"/>
</c:url>
<a href="<c:out value="${URL}"/>">Click Here</a>

Hope it Helps.. :)

Import this package in your jsp file

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

when you want to redirect new page or url then use for eg.

<a href='<c:url value="url of next page" />'>Home</a>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top