Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC : Common param in all requests

I have many controllers in my Spring MVC web application and there is a param mandatoryParam let's say which has to be present in all the requests to the web application.

Now I want to make that param-value available to all the methods in my web-layer and service-layer. How can I handle this scenario effectively?

Currently I am handling it in this way:

  • ... controllerMethod(@RequestParam String mandatoryParam, ...)
  • and, then passing this param to service layer by calling it's method
  • like image 487
    Yatendra Avatar asked Jul 15 '14 13:07

    Yatendra


    People also ask

    What is @requestparam in Spring MVC?

    In this quick tutorial, we’ll explore Spring's @RequestParam annotation and its attributes. Simply put, we can use @RequestParam to extract query parameters, form parameters, and even files from the request. In this article, we introduce different types of @RequestMapping shortcuts for quick web development using traditional Spring MVC framework.

    What are the different types of @requestparam?

    @RequestParam examples 1. Biding method parameter with web request parameter 2. Request parameter match method parameter name 3. Auto type conversion 4. @RequestParam with not mandatory parameters 5. @RequestParam with Default value 6. @RequestParam with List or array 7. @RequestParam with Map

    Can a single @requestparam have multiple values?

    Mapping a Multi-Value Parameter A single @RequestParam can have multiple values: 8. Conclusion In this article, we learned how to use @RequestParam. The full source code for the examples can be found in the GitHub project. with Spring?

    Do you need to specify parameter name in @requestparam?

    Request parameter match method parameter name If both variable and request parameter name matches we don’t need to specify the parameter name in the @RequestParam annotation. In the example above, since** **both variable and request parameter name is ‘category’, binding is performed automatically. 3. Auto type conversion


    1 Answers

    @ControllerAdvice("net.myproject.mypackage")
    public class MyControllerAdvice {
    
        @ModelAttribute
        public void myMethod(@RequestParam String mandatoryParam) {
    
            // Use your mandatoryParam
        }
    }
    

    myMethod() will be called for every request to any controller in the net.myproject.mypackage package. (Before Spring 4.0, you could not define a package. @ControllerAdvice applied to all controllers).

    See the Spring Reference for more details on @ModelAttribute methods.

    like image 180
    Alexey Avatar answered Sep 28 '22 04:09

    Alexey