컨트롤러 매개변수(Parameter)


WebMVC 모듈을 사용하면 컨트롤러 작성이 매우 간단해질 뿐만 아니라 요청 매개변수 처리도 더 쉬워집니다! WebMVC는 컨트롤러 메서드 매개 변수 또는 클래스 멤버의 주석 구성을 기반으로 메서드 매개 변수 또는 클래스 멤버에 해당하는 데이터 형식을 자동으로 변환합니다. 매개 변수 바인딩에는 다음 주석이 포함됩니다.

기본 매개 변수 주석
  • @RequestParam : 요청에 매개변수를 바인딩합니다.

  • @RequestHeader: 요청 헤더에 매개변수 변수를 바인딩합니다.

  • @CookieVariable: 쿠키에 매개변수 변수를 바인딩합니다.

위의 세 가지 주석은 동일합니다. 매개변수:

value: 매개변수 이름, 지정하지 않으면 기본적으로 메소드 매개변수 변수 이름이 사용됩니다.

prefix: 매개변수 이름 접두사, 기본값은 ""입니다.

defaultValue: 지정된 매개변수의 기본값입니다. , 기본값은 ""입니다.

샘플 코드:

    @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);
        }
    }

브라우저를 통한 액세스 URL 테스트:

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

실행 결과:

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

    浏览器输出:
    Hi, webmvc, UserName: ymper, Age: 18
Special 매개변수 주석
  • @P athVariable: 바인딩 요청 매핑 경로 매개변수 변수

    값: 매개변수 이름, 지정하지 않으면 기본적으로 메서드 매개변수 변수 이름이 사용됩니다.

    @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);
        }
    }

    액세스 URL 테스트 브라우저를 통해:

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

    실행 결과:

    Hi, webmvc, Age: 20, Sex: F

    Note
    : 경로 기반 매개변수 변수는 연속적이어야 합니다. 예:

    올바른: /path/{name}/ {age}
    • Error :/path/{name}/age/{sex}
    @ModelBind: 값 개체 매개변수 바인딩 주석
  • prefix: 바인딩된 매개변수 이름 접두사, 선택적 매개변수, 기본값은 "" ;

    샘플 코드:

    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);
        }
    }

    브라우저를 통한 액세스 URL 테스트:

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

    실행 결과:

    Hi, webmvc, Age: 20, Sex: F

  • @ParameterEscape: 컨트롤러 메서드 매개 변수 이스케이프 주석;

    WebMVC 모듈을 통해 매개 변수를 구성할 수 있습니다. parameter_escape_order设定是在控制器方法参数执行验证之前还是之后执行参数转义动作,参数取值范围为beforeafter,默认为after즉, 매개 변수 확인 후 이스케이프됩니다.

    scope: 문자열 매개 변수 이스케이프 범위, 기본값은 Type.EscapeScope.DEFAULT입니다.

    • 값 범위에는 JAVA, JS, HTML, XML, SQL, CSV, DEFAULT가 포함됩니다.
    • 기본값 DEFAULT는 SQL 및 HTML의 이스케이프를 완료합니다.

    skiped: 상위 주석에 알립니다. 현재 메소드 또는 매개변수는 무시되며 기본값은 false입니다.

    processor: 사용자 정의된 이스케이프 로직은 IParameterEscapeProcessor 인터페이스를 통해 구현될 수 있습니다.

    • 샘플 코드 1:
    @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();
        }
    }

    브라우저를 통한 액세스 URL 테스트:
    http://localhost:8080/demo/escape?content=<p>content$<br><script>alert("hello");</script></p>&desc=<script>alert("hello");</script>

    실행 결과: (콘솔 출력)
    Content: <p>content$<br><script>alert(&quot;hello&quot;);</script></p>
    Desc: <script>alert("hello");</script>

    예제 1 설명:
    컨트롤러 클래스이기 때문에 @ParameterEscape 주석으로 선언되면 전체 컨트롤러 클래스의 모든 요청 매개변수를 이스케이프해야 하므로 매개변수 내용의 내용이 성공적으로 이스케이프됩니다.

    매개변수 desc가 @ParameterEscape를 선언하기 때문에 주석에서 건너뛴 값입니다. true로 설정됩니다. 즉, 상위 수준 설정을 건너뛰므로 매개변수 내용이 이스케이프되지 않습니다.

    • 샘플 코드 2:
    @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();
        }
    }

    브라우저를 통해 URL 테스트에 액세스:
    http://localhost:8080/demo/escape2?content=<p>content$<br><script>alert("hello");</script></p>&desc=<script>alert("hello");</script>

    실행 결과: (콘솔 출력)
    Content: <p>content$<br><script>alert("hello");</script></p>
    Desc: <script>alert(&quot;hello&quot;);</script>

    예제 2 설명:
    컨트롤러 클래스가 @ParameterEscape 주석으로 선언되었지만 컨트롤러 메서드는 건너뛴 설정을 통한 이스케이프를 건너뜁니다. 선언된 메소드 매개변수 내용이 이스케이프되지 않으므로 매개변수 내용이 이스케이프되지 않습니다.

    매개변수 desc가 매개변수를 이스케이프해야 함을 나타내는 @ParameterEscape 주석을 선언하므로 매개변수 내용이 성공적으로 이스케이프됩니다.

      Note
    • : 컨트롤러 클래스와 메서드가 모두 @ParameterEscape 주석을 선언하면 클래스에 선언된 주석은 유효하지 않은 것으로 간주됩니다.

    싱글톤이 아닌 컨트롤러의 특수 사용법

    싱글톤 컨트롤의 차이점 컨트롤러 및 비싱글턴 컨트롤러:
싱글턴 컨트롤러 클래스는 WebMVC 모듈이 초기화될 때 인스턴스화되었습니다. 비싱글턴 컨트롤러 클래스는 요청이 수신될 때마다 인스턴스 개체를 생성합니다. 요청이 완료된 후

위 설명을 기반으로 싱글톤 컨트롤러가 아닌 경우 클래스 멤버를 통해 요청 매개변수를 받을 수 있습니다. 샘플 코드는 다음과 같습니다.
  • @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);
        }
    }
브라우저를 통한 액세스 URL 테스트:

http://localhost:8080/demo/sayHi?name=YMPer&content=Welcome!
이 샘플 코드의 실행 결과:

Hi, YMPer, Content: Welcome!

Note: 싱글톤 모드에서 WebMVC 모듈은 컨트롤러 클래스 멤버에 대한 값 할당을 무시합니다. 또한 싱글톤 모드에서는 멤버 변수를 매개 변수로 사용하지 않는 것이 좋습니다. 동시 다중 스레드 환경에서는 예기치 않은 결과가 발생할 수 있습니다. . 질문! !