Super Hornet
Super Hornet

Reputation: 2907

How to redirect to current url in java?

I'm using

<%=request.getRequestURL()%>

to redirect to current page but it has problem with addresses with some parameters like this:

http://xxx.com/yyy/x/search?mesg=welcome&initial=true&app= 

and redirects to address without parameter which causes problems.

is there any solution to get whole of address?

Upvotes: 2

Views: 2046

Answers (3)

Super Hornet
Super Hornet

Reputation: 2907

I just modified the previous answers and wrote this:

<c:set var="parameter" value="<%=request.getQueryString()%>"/>
<c:if test="${not empty parameter}">
    <c:set var="parameter" value="?${parameter}"/>
</c:if>

thanks everbody

Upvotes: 1

Alpesh Gediya
Alpesh Gediya

Reputation: 3794

You can redirect url using below two methods.

Using core jsp taglib.( I prefers this one)

<c:redirect url="your url">   
     <c:param name="mesg" value ="${mesg}" />   
     <c:param name="initial" value ="${initial}" /> 
     <c:param name="app" value="${app}" />
<c:redirect> 

Using scriptlet

<%
  String queryString =  request.getQueryString();
  if(queryString != null) {
    response.sendRedirect("http://xxx.com/yyy/x/search?" + queryString); 
  }
  else {
    response.sendRedirect("http://xxx.com/yyy/x/search"); 
  }
%>

getQueryString(), returns query string of the request ,but if no request parameters are supplied/availible then it returns null so you need to handle that null.

Upvotes: 2

NilsH
NilsH

Reputation: 13821

As the documentation for HttpServletRequest.getRequestURL() states, it does not include the query string. I can't see any methods on HttpServletRequest that does include this "directly", so you might have to construct this yourself, which shouldn't be too difficult. You can use the getParameterMap() method to get a map of all query parameters.

Edit

HttpServletRequest.getQueryString() was the method I was looking for. Thanks @AlpeshGediya. So by combining it with getRequestURL, you have what you want.

Upvotes: 2

Related Questions