26

I have a referrer URL like this:

http://myUrl.com?page=thisPage&gotoUrl=https://yahoo.com?gotoPage

How do I get the Values of "page" and "gotoUrl" in my Spring Controller?

I want to store these values as variables, so I can reuse them later.

3
  • 1
    Take a look at the @RequestParam annotation. Commented Jul 29, 2013 at 22:11
  • 1
    Did you really mean to say "referer"? If so the accepted answer is wrong. Commented Jul 30, 2013 at 19:55
  • You should probably URL-encode the value of gotoUrl (although I'm not sure it would functionally matter in this particular example). Commented Mar 10, 2015 at 20:58

3 Answers 3

105

In SpringMVC you can specify values from the query string be parsed and passed in as method parameters with the @RequestParam annotation.

public ModelAndView getPage(
    @RequestParam(value="page", required=false) String page, 
    @RequestParam(value="gotoUrl", required = false) String gotoUrl) {
}
Sign up to request clarification or add additional context in comments.

Comments

14

You can use the getParameter() method from the HttpServletRequest interface.

For example;

  public void getMeThoseParams(HttpServletRequest request){
    String page = request.getParameter("page");
    String goToURL = request.getParameter("gotoUrl");
}

5 Comments

This makes sense, if I want to pass the request as an argument. But is there a way to retrieve parameters, if I don't want to pass HttpServletRequest as an Argument to my controller action?
While this answer is technically correct, its not the recommended way to do it with Spring, @Affe's answer is more to the point.
@AkshaySinghal unless you don't know the parameters in advance but you need a way to handle them - then you can use request.getParameterNames() or request.getParameterMap()
@LukaszWiktor I'm sorry I don't understand that comment. It does not seem related to any question or answer.
@AkshaySinghal I wanted to say that Raunak's answer was helpful. In my case I don't know exact names of the parameters. I need to create an endpoint that can read any parameter. When I noticed this answer I discovered also the 2 methods mentioned in my previous comment.
-7

Get the QueryString in Spring MVC Controller

This is Liferay portal specific solution, and it works.

Query String Example: ?reportTypeId=1&reportSeqNo=391

In order to get the value of reportSeqNo in Liferay Portal, we need to get the Original Servlet Request.

String reportSeq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest)).getParameter("reportSeqNo");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.