前一篇咱們探討了關於springboot的配置文件和Controller的使用,本篇咱們來一塊兒探討一下關於springboot如何傳遞參數的知識。html
參數傳遞咱們最多見的就是在url後經過?/&兩個符號來將參數傳遞到後臺,固然springboot也是也同樣,咱們能夠經過這種方式將參數傳遞到後臺,那麼後臺如何接收這些參數呢?下面咱們一塊兒學習一下:spring
這裏咱們將用到@RequestParam註解,這個註解有三個參數分別是:value、required、defaultValue,具體的用法,下面一一爲你們介紹。瀏覽器
@RequestMapping(value = "/par1", method = RequestMethod.GET) public String reqPar1(@RequestParam("name") String name){ return name; }
經過@RequestParam註解聲明接收用戶傳入的參數,這樣當咱們在瀏覽器輸入http://localhost:8080/par1?name=123springboot
@RequestMapping(value = "/par2", method = RequestMethod.GET) public String reqPar2(@RequestParam(value = "name", required = false) String name){ if(null != name){ return name; }else{ return "未傳入參數"; } }
咱們看到第一個接口咱們並無寫value和required,其實第一個接口是簡寫,等同於app
@RequestParam(value = "name", required = true)
required=true:該參數不能爲空;相反required=false:該參數能爲空ide
@RequestMapping(value = "/par3", method = RequestMethod.GET) public String reqPar3(@RequestParam(value = "name", defaultValue = "null") String name){ return name; }
最後說一下defaultValue看字面意思,估計你已經想到它的做用了,是的當咱們未穿入該參數時的默認值。學習
下面咱們先看一下博客園中博客地址的連接:http://www.cnblogs.com/AndroidJotting/p/8232686.html,請你們注意紅色位置,這樣的參數傳遞是否是頗有趣,咱們並不用設置參數的key,那麼這是怎麼實現的呢?請接着看。ui
@RequestMapping(value = "/par4/{id}", method = RequestMethod.GET) public Integer reqPar4(@PathVariable("id") Integer id){ return id; }
這樣是否是和博客園的訪問很像,這樣咱們即可以直接將傳遞參數加在url後面。最後再來活學活用一下:url
@RequestMapping(value = "/{id}/par5", method = RequestMethod.GET) public Integer reqPar5(@PathVariable("id") Integer id){ return id; }
OK到這裏關於參數傳遞的內容就和你們分享完畢,最後再給你們補充一個小知識:spa
resources資源springboot默認只映射static、templates兩個文件夾下的文件,那麼如何進行拓展呢?很簡單,好比咱們在resources下新建一個image資源,這是咱們須要打開項目的主類:xxApplication
@SpringBootApplication public class Springboot1Application extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(Springboot1Application.class, args); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); //這種方式會在默認的基礎上增長/image/**映射到classpath:/image/,不會影響默認的方式,能夠同時使用。 registry.addResourceHandler("/image/**") .addResourceLocations("classpath:/image/"); } }
這樣簡單一配置,咱們就完成了上面的需求。
下一篇springboot持久化操做