Composing a URL in JSP

Lets say that my current URL is /app.jsp?filter=10&sort=name .

I have a pagination component in JSP that should contain links like:
/app.jsp?filter=10&sort=name&page=xxx .

How to create valid URLs in JSP by adding new parameters to current url? I do not want to use Java code in the JSP, and I am not getting URLs such as:
/app.jsp?filter=10&sort=name&?&page=xxx , or /app.jsp?&page=xxx , etc.

+6
source share
3 answers

Ok, I found the answer. The first problem is that I have to save all current parameters in the url and change only the page parameter. To do this, I need to iterate over all the current parameters and add those that I do not want to change to the URL. Then I added the options that I want to change or add. So, I ended up with this solution:

 <c:url var="nextUrl" value=""> <c:forEach items="${param}" var="entry"> <c:if test="${entry.key != 'page'}"> <c:param name="${entry.key}" value="${entry.value}" /> </c:if> </c:forEach> <c:param name="page" value="${some calculation}" /> </c:url> 

This will create a nice and clean URL that is independent of the page parameter in the request. The bonus to this approach is that the URL can be just that.

+9
source
 <c:url var="myURL" value="/app.jsp"> <c:param name="filter" value="10"/> <c:param name="sort" value="name"/> </c:url> 

To show the url you can do something like this

 <a href="${myURL}">Your URL Text</a> 
+8
source

To create a new URL based on the current URL, you first need to get the current URL from the request object . To access the request object in the JSP, use the pageContext implicit object defined by the JSP expression language:

 ${pageContext.request.requestURL} 

Here is a simple example of building a URL on a JSP page:

test.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <title>Test Page</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <h1>Testing URL construction</h1> <c:choose> <c:when test="${pageContext.request.queryString != null}"> <a href="${pageContext.request.requestURL}?${pageContext.request.queryString}&page=xxx">Go to page xxx</a> </c:when> <c:otherwise> <a href="${pageContext.request.requestURL}?page=xxx">Go to page xxx</a> </c:otherwise> </c:choose> </body> </html> 


This solution allows you to create URLs depending on whether the current URL contains any query string or not . So you add accordingly

?${pageContext.request.queryString}&page=xxx

or simply

?page=xxx

to the current URL.

JSTL and Expression Language were used to implement query string validation. And we used the getRequestURL() method to get the current URL.

+2
source

All Articles