How to redirect to a new url on the basis of a parameter in Spring - 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

Related

#PathVariable with slashes in middle of RequestMapping URL

I have a Spring controller mapping like following:
#RequestMapping(value = "api/{pathVar1}/receipt", method = RequestMethod.POST)
#ResponseBody
public String generateReceipt(HttpServletRequest request, #PathVariable String pathVar1) {
....
}
In this case what if the pathVar1 has slash('/').
Example request:
'api/CODE/1/receipt'
pathVar1 is supplied with
'CODE/1'
.
I guess it's not the cleanest solution, but it seems to be working:
Replace #PathVariable in API path with ** to accept anything between "api/" and "/receipt", and then extract the needed part of path.
#RequestMapping(value = "api/**/receipt", method = RequestMethod.POST)
#ResponseBody
public String generateReceipt(HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
String apiPath = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
String neededPathVariableValue = apiPath.substring(0, apiPath.length() - "/receipt".length());
//...
}

Spring get MediaType of received body

Following this answer I've set my method in controller this way:
#PostMapping(path = PathConstants.START_ACTION, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<BaseResponse<ProcessInstance>> start(#PathVariable String processDefinitionId,
#RequestBody(required = false) String params)
Now I need to behave differently according to my #RequestBody being of one MediaType or the other, so I need to know whether my params body is json o urlencoded. Is there a way to do this?
You can simply inject Content-Type header.
#PostMapping(path = "/{processDefinitionId}", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> start(#PathVariable String processDefinitionId,
#RequestBody(required = false) String params,
#RequestHeader("Content-Type") String contentType) {
if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
System.out.println("json");
} else {
// ...
}
return ResponseEntity.ok(params);
}
But I would suggest to split this method on two methods with different consumes values:
#PostMapping(path = "/v2/{processDefinitionId}", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> startV2Json(#PathVariable String processDefinitionId,
#RequestBody(required = false) String params) {
return ResponseEntity.ok(params);
}
#PostMapping(path = "/v2/{processDefinitionId}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> startV2UrlEncoded(#PathVariable String processDefinitionId,
#RequestBody(required = false) String params) {
return ResponseEntity.ok(params);
}

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 bind 2 GET methods in Spring MVC and distinguish using #RequestMapping?

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

Resources