How are these params used in #RequestMapping - spring

I have inherited code which I am trying to figure out.
I have a Controller class for registering a user with the following method
#RequestMapping(method = POST, params = {USERNAME_PARAM, "!" + EMAIL_PARAM})
public ModelAndView usernameRegister(#Valid RegisterWithUsernameParameter usernameParameter, ModelMap model)
Where USERNAME_PARAM = "username" and EMAIL_PARAM = "email". I also have this method:
#RequestMapping(method = POST, params = {EMAIL_PARAM, "!" + USERNAME_PARAM})
public ModelAndView emailRegister(#Valid AuthenticateWithEmailParameter emailParameter, ModelMap model)
My question is, what is the purpose of the "params = " ? I have removed and tested and I can't see any difference, it still works. Also what does "!" mean in this context?
Thanks!

params = {} attribute specifies additional conditions under which a particular method will be called.
usernameRegister() method will only be called if USERNAME_PARAM is present and EMAIL_PARAM is NOT present in the request.
emailRegister() method will only be called if EMAIL_PARAM is present and USERNAME_PARAM is NOT present in the request.
Some useful links:
Javadoc for params, Example using params attribute

Using 'params' we can narrow the request. And '!' negate the expression. So first method (userNameRegister) is looking for reuqets with USERNAME_PARAM but not EMAIL_PARAM whereas second one (emailRegister) is lookign for EMAIL_PARAM but not an USERNAME_PARAM

Related

How to get Swagger UI to display similar Spring Boot REST endpoints?

I have a controller class with two endpoints
#RestController
#RequestMapping
public class TestController {
#RequestMapping(
value= "/test",
method = RequestMethod.GET)
#ResponseBody
public String getTest() {
return "test without params";
}
#RequestMapping(
value= "/test",
params = {"param"},
method = RequestMethod.GET)
#ResponseBody
public String getTest(#PathParam("param") int param) {
return "test with param";
}
}
One has a parameter, one doesn't, and the both work.
If I use curl or a web browser to hit the endpoints
http://localhost:8081/test
returns
test without params
and
http://localhost:8081/test?param=1
returns
test with param
but the swagger ui only shows the one without a parameter.
If I change the value in the request mapping for the request with a parameter to
#RequestMapping(
value= "/testbyparam",
params = {"param"},
method = RequestMethod.GET)
Swagger UI displays both endpoints correctly, but I'd rather not define my endpoints based on what swagger will or won't display.
Is there any way for me to get swagger ui to properly display endpoints with matching values, but different parameters?
Edit for Clarification:
The endpoints work perfectly fine; /test and /test?param=1 both work perfectly, the issue is that swagger-ui won't display them.
I would like for swagger ui to display the endpoints I have defined, but if it can't, then I'll just have to live with swagger-ui missing some of my endpoints.
Edit with reference:
The people answering here: Proper REST formatted URL with date ranges
explicitly say not to seperate the query string with a slash
They also said "There shouldn't be a slash before the query string."
The issue is in your Request Mapping, The second method declaration is overriding the first method. As Resource Mapping value is same.
Try changing the second method to below. As you want to give input in QueryParam rather than path variable, you should use #RequestParam not #PathParam.
Note that you have to give /test/, In order to tell Spring that your mapping is not ambiguous. Hope it helps.
#RequestMapping(
value= "/test/",
method = RequestMethod.GET)
#ResponseBody
public String getTest (#RequestParam("param") int param) {
return "test with param"+param;
}
Upon reading clarifications, the issue here is that swagger-ui is doing the correct thing.
You have two controller endpoints, but they are for the same RESOURCE /test that takes a set of optional query parameters.
Effectively, all mapped controller endpoints that have the same method (GET) and request mapping (/test) represent a single logical resource. GET operation on the test resource, and a set of optional parameters which may affect the results of invoking that operation.
The fact that you've implemented this as two separate controller endpoints is an implementation detail and does not change the fact that there is a single /test resource that can be operated upon.
What would be the benefit to consumers of your API by listing this as two separate endpoints in swagger UI vs a single endpoint with optional parameters? Perhaps it could constrain the set of allowed valid query parameters (if you set ?foo you MUST set &bar) but this can also be done in descriptive text, and is a much more standard approach. Personally, I am unfamiliar with any publicly documented api that distinguishes multiple operations for the same resource differentiated by query params.
As per Open API Specification 3
OpenAPI defines a unique operation as a combination of a path and an
HTTP method. This means that two GET or two POST methods for the same
path are not allowed – even if they have different parameters
(parameters have no effect on uniqueness).
Reference - https://swagger.io/docs/specification/paths-and-operations/
This was also raised as an issue but it was closed because OAS3 doesn't allow that -
https://github.com/springdoc/springdoc-openapi/issues/859
Try including the param in the path as below.
#GetMapping("/test/{param}")
public String getTest(#PathVariable final int param) {
return "test with param";
}
I'm unclear exactly what you're attempting to do, but I'll give two solutions:
If you want to have PATH parameters e.g. GET /test & GET /test/123 you can do:
#GetMapping("/test")
public String getTest() {
return "test without params";
}
#GetMapping("test/{param}")
public String getTest(#PathVariable("param") int param) {
return "test with param";
}
If you want query parameters (GET /test and GET /test?param=123) then you need a single endpoint that takes an optional parameter:
#GetMapping("test")
public String getTest(#RequestParam("param") Integer param) {
if(param == null) {
return "test without params";
} else {
return "test with param";
}
}

regexMatcher for URL with query parameters in Spring Security

How should I use parameters like this in regexMatcher in Spring Security? I have many URLs that start with /sUrl and have different parameters. This code doesn't work!
.regexMatchers("\\/sUrl\\?params=\\{url:\"reports\\/Manager\",subSystem:\"ABS\"\\}").access("hasRole('ROLE_ABS')")
Controller:
#RequestMapping(value = "sUrl", method = RequestMethod.GET)
public RedirectView sUrl(#RequestParam(name = "params") String params) {
RedirectView redirectView = new RedirectView();
.
.
.
return redirectView;
}
URL seen in network partition of browser inspector when I click on this link:
sUrl?params={url:%22reports/Manager%22,subSystem:%22ABS%22}
You have to use a regular expression with the URL-encoded query parameter, see RegexRequestMatcher:
Uses a regular expression to decide whether a supplied the URL of a supplied HttpServletRequest. Can also be configured to match a specific HTTP method. The match is performed against the servletPath + pathInfo + queryString of the request and is case-sensitive by default. Case-insensitive matching can be used by using the constructor which takes the caseInsensitive argument.
and HttpServletRequest:
Returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a query string. Same as the value of the CGI variable QUERY_STRING.
Returns:
a String containing the query string or null if the URL contains no query string. The value is not decoded by the container.
Your modfified code:
.regexMatchers("\\/sUrl\\?params=\\{url:%22reports\\/Manager\%22,subSystem:%22ABS%22\\}").access("hasRole('ROLE_ABS')")

Spring Rest Service GET with parentheses

I have a Spring Rest Service like this:
#RequestMapping(value = "/banks", method = RequestMethod.GET)
public List<String> getBanks( #RequestParam(value="name" , required=true) String name) {
...
}
The name must allows special character like parentheses, but the problem is that when i put parentheses on the param, y receive the ASCCI code like #040# on the "name" parameter.
I thought in use #RequestBody with a wrap filter like a posible solution, but the method must change to POST to support the wrap in the Request Body and the api design going to be bad.
So, someone have a solition for support parentheses on the param of a GET Rest Service?

Is it possible to return value from Spring AspectJ?

I'm returning value from my controller. Let it be ResponseEntity<String> type.
Controller returns:
new ResponseEntity<String>("{\"msg\":\"success\"}",HttpStatus.OK);
Following value goes to my spring aspect. I am receiving this object in following code:
#AfterReturning(pointcut = "somePointcut()",returning = "retVal")
public ResponseEntity<String> adviceTest3(Object retVal) {
//here i have access to controller's object
return new ResponseEntity<String>("{\"msg\":\"changed value within aspect\"}",HttpStatus.OK);
}
I'm aware that there is #AfterReturning. Is it any way manipulate data and achieve that?
With #AfterReturning, no. Quote from the documentation
An after returning advice has access to the return value (which it cannot modify), invoked method, methods arguments and target.
You could use #Around instead.

How to deal with error "Request method 'GET' not supported"

I would like to implement deletion of a entity from a list view. And I faced this problem. Can you explain me, what is the problem and how can I ovrcome it?
The controller method:
#RequestMapping(value = "/deleteComment/{commentId}", method = RequestMethod.POST)
public String deleteComment(#PathVariable int commentId, BindingResult result, Model model){
{
Comment deletedComment = commentService.findCommentByID(commentId);
if (deletedComment != null) {
commentService.deleteComment(deletedComment);
}
return "refresh:";
}
Do I need to specify 'Get' method, if I'm dealing with list-view (and I see the whole list). If I need, what code should I place there. I have no any ideas...
The problem is in button type attribute.
If You have HTML button type="submit" then Your service can be only RequestMethod.GET. When You change to RequestMethod.POST then You have "Request method 'GET' not supported".
SOLUTION: Change attribute in button tag to type="button".
By specifying method = RequestMethod.POST you are essentially saying that the deleteComment method should be called only for POST and for a path /deleteComment/{commentId}. If you want it to accept requests for GET also, you can just remove the method or accept GET also this way:
#RequestMapping(value = "/deleteComment/{commentId}", method = {RequestMethod.POST, RequestMethod.GET})
You may also want to explicitly specify the name of the variable to bind to the commentId path variable this way:
public String deleteComment(#PathVariable("commentId") int commentId, BindingResult result, Model model){

Resources