Controller parameters (Parameter)


The WebMVC module not only makes writing controllers very simple, but also processing request parameters becomes easier! WebMVC will automatically convert the data type corresponding to the method parameter or class member according to the annotation configuration of the controller method parameter or class member. The binding of parameters involves the following annotations:

Basic parameter annotations
  • @RequestParam: bind the parameters in the request;

  • @RequestHeader: bind the parameter variables in the request header;

  • @CookieVariable: Bind parameter variables in Cookie;

The above three annotations have the same parameters:

value: parameter name, if not specified, the method parameter variable name is used by default;

prefix: parameter name prefix, the default is "";

defaultValue: the default value of the specified parameter, the default For "";

Sample code:

    @Controller
    @RequestMapping("/demo")
    public class DemoController {

        @RequestMapping("/param")
        public IView testParam(@RequestParam String name,
                          @RequestParam(defaultValue = "18") Integer age,
                          @RequestParam(value = "name", prefix = "user") String username,
                          @RequestHeader(defaultValue = "BASIC") String authType,
                          @CookieVariable(defaultValue = "false") Boolean isLogin) {

            System.out.println("AuthType: " + authType);
            System.out.println("IsLogin: " + isLogin);
            return View.textView("Hi, " + name + ", UserName: " + username + ", Age: " + age);
        }
    }

Access URL test through browser:

    http://localhost:8080/demo/param?name=webmvc&user.name=ymper

Execution result:

    控制台输出:
    AuthType: BASIC
    IsLogin: false

    浏览器输出:
    Hi, webmvc, UserName: ymper, Age: 18
Special parameter annotation
  • @ PathVariable: the path parameter variable in the binding request mapping;

    value: parameter name, if not specified, the method parameter variable name is used by default;

    Sample code:

    @Controller
    @RequestMapping("/demo")
    public class DemoController {
    
        @RequestMapping("/path/{name}/{age}")
        public IView testPath(@PathVariable String name,
                          @PathVariable(value = "age") Integer age,
                          @RequestParam(prefix = "user") String sex) {
    
            return View.textView("Hi, " + name + ", Age: " + age + ", Sex: " + sex);
        }
    }

    Access the URL test through the browser:

    http://localhost:8080/demo/path/webmvc/20?user.sex=F

    Execution result:

    Hi, webmvc, Age: 20, Sex: F

    Note: Path-based parameter variables must be continuous, such as:

    • Correct:/path/{name}/{age}

    • Incorrect:/path/{name}/age/{sex}

  • @ModelBind: value object parameter binding annotation;

    prefix: bound parameter name prefix, optional parameter, default is "";

    Sample code:

    public class DemoVO {
    
        @PathVariable
        private String name;
    
        @RequestParam
        private String sex;
    
        @RequestParam(prefix = "ext")
        private Integer age;
    
        // 省略Get和Set方法
    }
    
    @Controller
    @RequestMapping("/demo")
    public class DemoController {
    
        @RequestMapping("/bind/{demo.name}")
        public IView testBind(@ModelBind(prefix = "demo") DemoVO vo) {
            String _str = "Hi, " + vo.getName() + ", Age: " + vo.getAge() + ", Sex: " + vo.getSex();
            return View.textView(_str);
        }
    }

    Access URL test through browser:

    http://localhost:8080/demo/bind/webmvc?demo.sex=F&demo.ext.age=20

    Execution result:

    Hi, webmvc, Age: 20, Sex: F
  • @ParameterEscape: Controller method parameter escape annotation;

    You can configure parameters through the WebMVC module parameter_escape_orderThe setting is before the controller method parameters are verified. Or perform the parameter escaping action afterwards, the parameter value range is before or after, the default is after, that is, escape after parameter verification;

    scope: String parameter escape scope, the default is Type.EscapeScope.DEFAULT;

    • The value range includes: JAVA, JS, HTML, XML, SQL, CSV, DEFAULT;
    • The default value is DEFAULT, which completes the escaping of SQL and HTML;

    skiped: Notifies the parent annotation that the escaping operation of the current method or parameter will be ignored. Default Is false;

    processor: Custom string parameter escape processor;

    • Custom escape logic can be implemented through the IParameterEscapeProcessor interface;
    • Default implementation For DefaultParameterEscapeProcessor;

    Sample code one:

    @Controller
    @RequestMapping("/demo")
    @ParameterEscape
    public class DemoController {
    
        @RequestMapping("/escape")
        public IView testEscape(@RequestParam String content,
                                @ParameterEscape(skiped = true) @RequestParam String desc) {
    
            System.out.println("Content: " + content);
            System.out.println("Desc: " + desc);
            return View.nullView();
        }
    }
    
    // 或者:(两段代码执行结果相同)
    
    @Controller
    @RequestMapping("/demo")
    public class DemoController {
    
        @RequestMapping("/escape")
        @ParameterEscape
        public IView testEscape(@RequestParam String content,
                                @ParameterEscape(skiped = true) @RequestParam String desc) {
    
            System.out.println("Content: " + content);
            System.out.println("Desc: " + desc);
            return View.nullView();
        }
    }

    Access URL test through browser:

    http://localhost:8080/demo/escape?content=<p>content$<br><script>alert("hello");</script></p>&desc=<script>alert("hello");</script>

    Execution Result: (Console Output)

    Content: <p>content$<br><script>alert(&quot;hello&quot;);</script></p>
    Desc: <script>alert("hello");</script>

    Example 1 Description:

    • Since the controller class is declared with the @ParameterEscape annotation, it means that all request parameters in the entire controller class need to be escaped, so the content of the parameter content is successfully escaped;
    • Since the skipped value in the @ParameterEscape annotation declared by parameter desc is set to true, indicating that the upper-level settings are skipped, the parameter content is not escaped;

    Sample code two:

    @Controller
    @RequestMapping("/demo")
    @ParameterEscape
    public class DemoController {
    
        @RequestMapping("/escape2")
        @ParameterEscape(skiped = true)
        public IView testEscape2(@RequestParam String content,
                                @ParameterEscape @RequestParam String desc) {
    
            System.out.println("Content: " + content);
            System.out.println("Desc: " + desc);
            return View.nullView();
        }
    }

    Access the URL test through the browser:

    http://localhost:8080/demo/escape2?content=<p>content$<br><script>alert("hello");</script></p>&desc=<script>alert("hello");</script>

    Execution results: (Console output)

    Content: <p>content$<br><script>alert("hello");</script></p>
    Desc: <script>alert(&quot;hello&quot;);</script>

    Example 2 description:

    • Although the controller class is declared with the @ParameterEscape annotation, the controller method passes The skipped setting skips escaping, which means that the declared method parameter content is not escaped, so the content of the parameter content is not escaped;
    • Since the parameter desc declares the @ParameterEscape annotation, it means that the parameter needs Escape, so the parameter content is successfully escaped;

    Note: When both the controller class and the method declare the @ParameterEscape annotation, the annotation declared on the class will be treated as is invalid;

Special usage of non-single instance controller

The difference between singleton controller and non-single instance controller :

  • The singleton controller class has been instantiated when the WebMVC module is initialized;
  • The non-singleton controller class will create an instance every time a request is received. Object, the instance object is released after the request is completed;

Based on the above description, non-singleton controllers can receive request parameters through class members. The sample code is as follows:

@Controller(singleton = false)
@RequestMapping("/demo")
public class DemoController {

    @RequestParam
    private String content;

    @RequestMapping("/sayHi")
    public IView sayHi(@RequestParam String name) {
        return View.textView("Hi, " + name + ", Content: " + content);
    }
}

Access the URL test through the browser:

http://localhost:8080/demo/sayHi?name=YMPer&content=Welcome!

The execution result of this sample code:

Hi, YMPer, Content: Welcome!

Note: In singleton mode, the WebMVC module will ignore assigning values ​​to controller class members. It is also recommended not to use member variables as parameters in singleton mode. Unexpected problems may occur in a thread environment! !