LoginSignup
4

More than 3 years have passed since last update.

posted at

Spring boot コントローラメソッド メモ

Spring MVCのコントローラメソッドは、画面で入力されたパラメータ以外に、様々な情報を引数として受け取ることができる。

@Secured

@Secured アノテーションを付けることで、URLに関する権限を指定する事が出来る。


@Controller
@RequestMapping("/sbadmin2/")
@Secured("IS_AUTHENTICATED_FULLY")
public class SbAdmin2Controller {

    @RequestMapping("/index.html")
    public ModelAndView index() {
        return new ModelAndView("SbAdmin2Controller/index");
    }

    @Secured("ROLE_STAFF")
    @RequestMapping("/forms.html")
    public ModelAndView forms() {
        return new ModelAndView("SbAdmin2Controller/forms");
    }
}
// /sbadmin2/index.html はログインしていればアクセス可能
// /sbadmin2/forms.html はログインして ROLE_STAFFの権限を割り当てられていればアクセス可能

@RequestParam

@RequestParam アノテーションを指定すると、URLに含まれるクエリパラメータや、メッセージボディーに含まれるポストパラメータを受け取ることができる。


@GetMapping("/hello")
public String hello(@RequestParam("name") String name) {}
// /hello?name=string

@RequestPart

@RequestParam アノテーションを指定すると、画像・動画ファイルやJSONを受け取ることができる。


@GetMapping("/hello")
public String hello(@RequestPart("data") String data) {}
const data = new FormData()
data.append('file', file)
data.append('jsonValue', new Blob([JSON.stringify(sampleObject)], {type : 'application/json'}))

axios.get('/hello', data)

@PathVariable

@PathVariable アノテーションを指定すると、URLに含まれる動的なパラメータを受け取ることができる。


@GetMapping("/hello/{userId}")
public String hello(@PathVariable("userId") Integer userId) {

@RequestHeader

@RequestHeader アノテーションを指定すると、リクエストヘッダに含まれている各項目を受け取ることができる。


@GetMapping("/hello")
public String hello(@RequestHeader("User-Agent") String userAgent) {
RequestHeader
GET /hello?userId=10 HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json
X-XSRF-TOKEN: 00000-000-0000-0000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
Referer: http://localhost:8080/hello?userId=10
Accept-Encoding: gzip, deflate, br
Accept-Language: ja,en-US;q=0.9,en;q=0.8
Cookie: mailaddress=hoge@hoge.com;
JSESSIONID=sfdgfhgjh;
XSRF-TOKEN=00000-000-0000-0000

@RequestBody

@RequestBody アノテーションを指定すると、リクエストボディーの内容をそのまま取得することができる。

@PostMapping("/hello")
public String hello(@RequestBody String body) {
POST /hello HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 22
Cache-Control: max-age=0
Origin: http://localhost:8080
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://localhost:8080/hello
Accept-Encoding: gzip, deflate, br
Accept-Language: ja,en-US;q=0.8,en;q=0.6

user=scott&password=tiger

※リクエストヘッダの後に一行、空行が入り、その後POSTで送信したクエリが、リクエストボディとしてクライアントからサーバへと送信されてくる
※仕様上、get時の body は null に設定される

@DateTimeFormat

@DateTimeFormat アノテーションを指定して、受け取る日時の文字列表現の形式を指定する。

@GetMapping("/hello/{date}")
public String hello(@PathVariable("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) java.util.Date date) {}

@Autowired

付与されたフィールドの型と合うBeanを自動的にInjectionしてくれる。
型と会うBeanが複数ある場合は、@Qualifierアノテーションを使用することで一意に識別できる。

参考: @Autowired、@Inject、@Resourceの違いについての検証

@Validated

@Validated アノテーションを指定して、バリデーションを有効化する。

 @PostMapping("/hello")
    public String hello(@RequestBody @Validated String name)

@AuthenticationPrincipal

@AuthenticationPrincipal アノテーションを指定して、その引数に認証したユーザ情報が自動的に渡されるようにする。

@RequestMapping("/hello")
    public String hello(@AuthenticationPrincipal AppUserDetail userDetail) {
        log.info("debug: {}", userDetail);

        return "user";
    }

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
4