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.

Majid
  • 13,853
  • 15
  • 77
  • 113
Jake
  • 25,479
  • 31
  • 107
  • 168

3 Answers3

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) {
}
arahant
  • 2,203
  • 7
  • 38
  • 62
Affe
  • 47,174
  • 11
  • 83
  • 83
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");
}
Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62
  • 1
    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? – Jake Jul 29 '13 at 22:15
  • 12
    While this answer is technically correct, its not the recommended way to do it with Spring, @Affe's answer is more to the point. – Akshay Jul 30 '13 at 12:19
  • 1
    @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()` – Lukasz Wiktor Apr 20 '15 at 09:57
  • @LukaszWiktor I'm sorry I don't understand that comment. It does not seem related to any question or answer. – Akshay Apr 20 '15 at 11:58
  • 1
    @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. – Lukasz Wiktor Apr 20 '15 at 12:20
-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");
Robert
  • 1,286
  • 1
  • 17
  • 37
zrdegree
  • 1
  • 1