How to bind 2 GET methods in Spring MVC and distinguish using #RequestMapping? - spring

I have 2 different method, both have same url, but different set of incoming params, can I properly map them using #RequestMapping?
#RequestMapping(value = "/someurl", method = RequestMethod.GET)
public ModelAndView methodA (
#RequestParam(value = "param1", required = false) String param1,
#RequestParam(value = "param2", required = false) String param2) {
return null;
}
#RequestMapping(value = "/someurl", method = RequestMethod.GET)
public ModelAndView methodB (
#RequestParam(value = "array", required = false) String[] array) {
return null;
}

You can narrow a mapped request based on the existance or non-existance of the request parameters, e.g.
#RequestMapping(value = "/someurl", method = RequestMethod.GET, params={"!param1", "!param2"})
public ModelAndView methodB (
#RequestParam(value = "array", required = false) String[] array) {
return null;
}
will mapp to the methodB only when there is no param1 or param2 in the request and will give an info to the framework how to distinguish between the two mappings, so you won't get any errors at startup

Related

Spring: How can I get value from uri?

How can the callbackFacebook function get the value of code from the uri?
uri = http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code) {
System.out.println(code);
return "login";
}
Try this. code is a query parameter judging by your URL, not a path variable. Path variables are a part of the path itself (i.e. if your URL was something like /{code}/callback, then code is a PathVariable).
#RequestMapping(value = "/callback", method = RequestMethod.GET)
public String callbackFacebook(Model model, #RequestParam(value = "code") String code) {
System.out.println(code);
return "login";
}
If your URL is http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo then it is case of request parameters so the method will be like below.
#RequestMapping(value = "/callback", method = RequestMethod.GET)
public String callbackFacebook(Model model, #RequestParam(value = "code") String code) {
return "login";
}
If your URL is http://localhost:8081/callback/AQDNm6hezKdTsId5k4oXKNo then then it is case of path variables method will be like below.
#RequestMapping(value = "/callback/{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(value = "code") String code) {
return "login";
}
Refer requestparam-vs-pathvariable for better clarity.
I will explain 2 ways.
1-If it is added in the session in somewhere in the project as attribute,You can get it like this :
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code,HttpServletRequest request) {
String code1 = request.getSession().getAttribute("code").toString();
return "login";
}
example output : AQDNm6hezKdTsId5k4oXKNo
2-You can directly get URL.But then you need to parse URL.Because all URL is coming.
#RequestMapping(value = "/callback?{code}", method = RequestMethod.GET)
public String callbackFacebook(Model model, #PathVariable(name = "code") String code,HttpServletRequest request) {
StringBuffer requestURL = request.getRequestURL();
return "login";
}
example output : http://localhost:8081/callback?code=AQDNm6hezKdTsId5k4oXKNo

How to provide default values for array parameters in spring MVC url mapping?

#RequestMapping(value = "/getUserScoreCardDetails", method = RequestMethod.GET)
public #ResponseBody List<ScoreDetails> getUserScoreCardDetails(
#RequestParam(value = "playerIds", required = false) int[] playerIds) {
}
I need to provide default values [1,2,3] for playerIds if playerIds is not available in request?
You can set comma separated values inside defaultValue property in #RequestParam
#RequestMapping(value = "/getUserScoreCardDetails", method = RequestMethod.GET)
public #ResponseBody List<ScoreDetails> getUserScoreCardDetails(
#RequestParam(value = "playerIds", required = false, defaultValue="1,2,3") int[] playerIds) {
}
Inside your method, just check, if playerIds is null and if it is null then specify the default values there like this
#RequestMapping(value = "/getUserScoreCardDetails", method =
RequestMethod.GET)
public #ResponseBody List<ScoreDetails> getUserScoreCardDetails(
#RequestParam(value = "playerIds", required = false) int[] playerIds) {
if(playerIds==null){
playerIds = {1,2,3};
}
}

How to redirect to a new url on the basis of a parameter in Spring

My RequestMapping & ResponseBody is like this:
#RequestMapping(value = "/someURL", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public ModelAndView getDetails(
#RequestParam(value = "param1", required = false) String param1,
#RequestParam(value = "param2", required = false) String param2,
{
Now on the basis of param1, I want to redirect to a particular URL.
Eg. Right now after processing, my page is going to
http://parent-domain/someURL?param1=...param2=...
But what I want is to completely change the parent domain like this
http://some-other-domain/someURL?param1=...param2=...
Do something like this:
#RequestMapping(value = "/someURL", method = RequestMethod.GET, produces = "application/json")
public ModelAndView getDetails(#RequestParam(value = "param1", required = false) String param1,
#RequestParam(value = "param2", required = false) String param2) {
if (param1.equals("a"))
return new ModelAndView("redirect:somotherurl");
else
return new ModelAndView("redirect:http://google.com");
}
if param1 is a then it will go to someotherurl in parent else it will redirect to google.com

how to check if a request param/query param is passed in the request in Spring MVC app?

I have two different requests to handle
localhost:8080/myapp/status
localhost:8080/myapp/status?v
Please note that in the second request, just a request param is passed. No value is required to be set for it. That is the requirement.
How will I handle this in my controller?
#RequestMapping(value = "/status", method = RequestMethod.GET)
#ResponseBody
public void status(
#RequestParam(value = "v", required = "false") final String verbose) {
//check if v is in query params
...logic
//else
..logic
}
You could use HttpServlerRequest.getParameterMap() like this:
#RequestMapping(value = "/status", method = RequestMethod.GET)
#ResponseBody
public void status(HttpServletRequest request) {
boolean verbose = request.getParameterMap().containsKey("v");
if (verbose) {
...
} else {
...
}
}

Expecting a request param with a "XOR" validation

I have a simple request call in a spring mvc controller
#ResponseBody
#RequestMapping(value = "/url", method = RequestMethod.GET)
public SomeDTO getSth(#RequestParam("paramA") Integer paramA, #RequestParam("paramB") Integer paramB) {
// ...
}
and I want to have either the paramA or the paramB otherwise a normal http response as it currently happens if I do not provide both parameters.
I know there is a required parameter available, but I do not see a way to connect both. Any idea?
I can't think of a very good solution, but the straightforward one seems to be normal, isn't it?
#ResponseBody
#RequestMapping(value = "/url", method = RequestMethod.GET)
public String getSth(#RequestParam(value = "paramA", required = false) Integer paramA,
#RequestParam(value = "paramB", required = false) Integer paramB) {
if (paramA == null ^ paramB == null) {
return "body";
} else {
throw new BadRequestException();
}
}
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public static class BadRequestException extends RuntimeException {
private static final long serialVersionUID = 1L;
}

Resources