Spring入門學習手冊 6:Spring MVC基礎中的基礎
Spring獲取請求引數非常簡單,只要用到 @RequestParam 註解就可以了
如果不指定請求 method 的話,無論是 get 還是 post 引數都可以輕易獲取到
程式碼是下面這樣:
package com.learn.springMVCDemo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class RequestController { @RequestMapping("requestDemo") public String doRequest(Model model, @RequestParam(name="info", defaultValue = "some information") String info) { model.addAttribute("info", info); return "hello"; } } 複製程式碼
在這段程式碼中 @RequestParam 註解的括號中 name 表示引數名, defaultValue 指明預設的引數值。
GET方法請求這個頁面: 訪問地址 http://localhost:8080/LearnSpringMVCDemoFirst_war/requestDemo?info=helloWorldFromGETMethod
執行效果:

POST方法請求這個頁面:
訪問地址 http://localhost:8080/LearnSpringMVCDemoFirst_war/
提交表單

執行結果

二、頁面重定向
重定向的時候只要在返回的時候加上 redirect 就可以了:
package com.learn.springMVCDemo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class RedirectController { @RequestMapping("redirect") public String redirectDemo(Model model) { model.addAttribute("message", "redirectInfo"); //重定向 return "redirect:/demo"; } } 複製程式碼
上面的程式碼就是重定向到 /demo 頁面了。
訪問地址: localhost:8080/LearnSpringMVCDemoFirst_war/redirect

三、獲取URI路徑(@PathVariable)
package com.learn.springMVCDemo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class PathVariableController { @RequestMapping("path/{prefix}/{name}/{suffix}") public ModelAndView PathDemo(Model model, @PathVariable(value = "prefix") String prefix, @PathVariable(value = "name") String name, @PathVariable(value = "suffix") String suffix) { ModelAndView mv = new ModelAndView("hello"); mv.addObject("message","website URI path"); model.addAttribute("prefix", prefix); model.addAttribute("name", name); model.addAttribute("suffix", suffix); return mv; } } 複製程式碼
在 @RequestMapping 的括號中固定一個以上的路徑名稱,然後給分固定的路徑名稱直接加上大括號,在請求對映的方法引數中加上 @PathVariable 註解的引數中,按照先後順序一一對應就可以獲取到路徑名稱。
執行結果:

四、不返回檢視直接返回字串
@RequestMapping("ResponseBody") @ResponseBody public String RequestBody() { return "request body message!!!"; } 複製程式碼
在請求對映方法前直接加上 @ResponseBody 註解,那麼返回的就不是檢視,而直接是ResponseBody
執行結果:

