Spring MVC referencing params variable from RequestMapping - java

I have the method below:
#RequestMapping(value = "/path/to/{iconId}", params="size={iconSize}", method = RequestMethod.GET)
public void webletIconData(#PathVariable String iconId, #PathVariable String iconSize, HttpServletResponse response) throws IOException {
// Implementation here
}
I know how to pass the variable "webletId" from the RequestMapping using the #PathVariable, but how do I reference the variable "iconSize" from params?
Thanks a lot.

Use #RequestParam:
#RequestMapping(value = "/path/to/{iconId}", method = RequestMethod.GET)
public void webletIconData(#PathVariable String iconId,
#RequestParam("size") String iconSize,
HttpServletResponse response) throws IOException { ... }
See also:
15.3.2.3 Supported handler method arguments and return types

axtavt is right
I only want to explain what your mistake is:
The #RequestMapping params parameter is a filter to make sure that the annotated handler method is only invoked if there is a parameter with the requested value.
So a handler method annotated with #RequestMapping(params="action=doSomething") will be only invoked if there is an request parameter actionwith the content doSomething.

Related

Spring Boot not recognize controller with send request parameters

The spring boot do not recognize my controllers only if i send more parameters on request. For example:
If i send normal GET request the spring boot recognize my controller:
http://localhost/idp/oauth/123/authorize
If i send GET request with extras parameters the spring boot do not recognize my controller:
http://localhost/idp/oauth/123/authorize?scope=public_profile
I need receive the request exactly for second example (with parameter scope), but the spring boot do not recognize the controller and redirect to /error.
code:
#Controller
#RequestMapping("/idp/oauth")
public class OAuthController {
#RequestMapping(value = "/{clientId}/authorize", method = RequestMethod.GET)
public String authorizeGet(
HttpServletRequest request,
HttpServletResponse response,
#PathVariable String clientId,
Model model) {
// ...
}
#RequestMapping(value = "/{clientId}/authorize", method = RequestMethod.POST)
public String authorizePost(
HttpServletRequest request,
HttpServletResponse response,
#PathVariable String clientId,
Model model) {
// ...
}
}
Since you are passing extra param with name "scope" Spring will search for #RequestParam in methods
It can't find any, thus the error
You need to modify your method to add all #RequestParam
You can also add optional fields if they are not mandatory with required = false
#RequestMapping(value = "/{clientId}/authorize", method = RequestMethod.GET)
public String authorizeGet(
HttpServletRequest request,
HttpServletResponse response,
#PathVariable String clientId,
#RequestParam(value = "scope") String scope,
#RequestParam(required = false, value = "optionalParam") String optionalParam,
Model model) {
// ...
}
You missed #RequestParam in the controller method definition.
More on #RequestParam

Get original mapping value inside Spring controller method

Since I'm using the CQRS pattern, I'm trying to create a single controller method that accepts every POST call with a command in its request body and send it.
I'm almost there, but I can't get the path variables.
I created a custom HandlerMapping
#Bean
public HandlerMapping requestMappingHandlerMapping() throws NoSuchMethodException {
for (final UrlEnum urlEnumItem : UrlEnum.values()) {
requestMappingHandlerMapping.registerMapping(new RequestMappingInfo(urlEnumItem.getCommandName(),
new PatternsRequestCondition(urlEnumItem.getUrl()),
null,
null,
null,
null,
null,
null),
commandController,
commandController.getClass().getDeclaredMethod("commandHandler", HttpServletRequest.class)
);
}
return requestMappingHandlerMapping;
}
and this is my controller method signature
#RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> commandHandler(final HttpServletRequest request) throws Exception {
// controller code here
}
If the url path is something like /api/test it works, but with something like /api/test/{idEntity} I don't have any PathVariable available in the request.
I tried everything like
String originalUrl = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
which returns the valued url (i.e. /api/test/1234), not the template, or adding
#PathVariable Map<String, Object> parameters
as a parameter in the method, which is empty.
Debugging the request object it seems there isn't anything useful to identify the path variables.
Maybe I should interrogate the HandlerMapping, but I can't have access to it in the controller method.
Is there a way to extract the pathVariables in the controller method?
It was an error in the configuration. I shouldn't have added the RequestMapping annotation to the controller method because it overrode my configuration.
Now I have
#RestController
public class CommandController extends AbstractController {
private final MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
#Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
// controller code here
return new ModelAndView(mappingJackson2JsonView);
}
}

How to handle that can not get form data by using RequestMapping

I implement a controller as the following:
#RequestMapping(value = "/export", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<Object> Export(HttpServletRequest req, HttpServletResponse response, String type,String text) {
........
}
When posting the text(form param) which the length is small(about 20k) from client, the controller works ok and can get form params(data and type).
But 'type' and 'text' are null in service side, when text(form param) is very long(more than 200k) from client.
Who know how to handle it.
Form params can be read from request as req.getParameter("type").
change your method as below since you are already using req and resp in the method signature
public #ResponseBody ResponseEntity<Object> Export(HttpServletRequest req, HttpServletResponse response){
String type = req.getParameter("type");
String text = req.getParameter("text");
}
You could use the Spring MVC annotation as follows.
public #ResponseBody void export(#PathVariable final String whatEver,
#RequestParam("type") final String type, #RequestParam("text") final String text,
final HttpServletRequest request)

How to get method's request in springmvc

I have the next method:
#RequestMapping(value="/busqueda/basica", method = {RequestMethod.POST,RequestMethod.GET})
public String busquedaBasica(HttpServletRequest request,
HttpServletResponse response,
ModelMap modelMap,
#RequestParam("nombreBasica") String nombre){
...
}
Is there any way to get the method's request, POST or GET?
Yes, the HttpServletRequest has a getMethod() that returns a String value representing the HTTP method.

add custom parameters to spring mvc controller

I have a custom dispatcher servlet which extends the default DispatcherServlet to do some validation for all requests.
Since I will get all the parameters from a request(getInputStream()->Map) to do some validation, I want to pass the params to controller or add the params to the context where I can get them again from the cotroller.
Now I just put all the params to a global Map, but I wonder if there are some simple ways.
public class CustomDispatcherServlet extends DispatcherServlet {
private static final long serialVersionUID = 7250693017796274410L;
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
doFilter(request, response);
super.doDispatch(request, response);
}
...
private void doFilter(HttpServletRequest request, HttpServletResponse response) {
WLNResponse<String> error = null;
try {
boolean isSignValid = checkSignValidity(request);
...
private boolean checkSignValidity(HttpServletRequest request) throws IOException {
// pass this params to controller or somewhere I can get from controller
Map<String, Object> params = WebUtils.readParams(request);
...
The way I would go at validating params in the controller itself. for instance
#Controller
public ControllerClass
{
#RequestMapping(value = "/someurl", method = RequestMethod.GET, params = {
"requestParam"})
public void someMethod(#RequestParam(value = "requestParam") String requestParam)
{
System.out.println("This is the value of the RequestParam requestParam " + requestParam);
}
}
This way you can do your validation within the controller.
The only thing this doesn't solve for is if the request being made is not resolved to a valid controller. For that I would use the annotation #controllerAdvice.
Currently, I simply use the request.setAttribute() to put params to the attributes and get it from the controller.....

Categories

Resources