2
2

More than 3 years have passed since last update.

ルーティング

Posted at

ルーティング

コントローラ、メソッドそれぞれに
@RequestMapping
を付与することでルーティングを設定できます。
コントローラの@RequestMappingに「routing」、
メソッドの@RequestMappingに「index」を指定した場合、
URLは「http://localhost:8080/routing/index」となります。
HTTPメソッドによりメソッドを分ける場合は「method = RequestMethod.GET」の要領で指定することができます。

URL中のクエリストリング取得

メソッドに
@RequestParam Integer id
の要領で指定することができます。

POST値の取得

メソッドに
@ModelAttribute IndexForm form
の要領で指定することができます。
なお、POST値を保持するクラスにSetterがない場合は値が設定されないのでご注意ください。

サンプルプログラム(ルーティング、GET、POST値取得)

demo\src\main\java\com\example\demo\RoutingController.java
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("routing")
public class RoutingController {

    // routing/index の処理(GET)
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public Model indexGet(Model model, @RequestParam(required=false) Integer id) {
        System.out.println("ID=" + id);

        return model;
    }

    // routing/index の処理(POST)
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public Model indexPost(Model model, @ModelAttribute IndexForm form) {
        System.out.println("form.name=" + form.name);

        return model;
    }

    /**
     * POST値保持用のフォームクラス
     */
    public class IndexForm {
        public String name ;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }
}
2
2
0

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
  3. You can use dark theme
What you can do with signing up
2
2