最後附有網盤鏈接(程序打包+數據庫)
Spring MVC 獲取請求參數的方法
1、@RequestParam綁定請求參數
@Controller註解說明該類非普通類,而是一個控制器類。
@RequestMapping("/helloworld")註解映射請求地址。
@Controller
public class HelloWorldController {
/**
*1.通過RequestMapping註解映射請求URL
*2.返回值通過視圖解析器解析到實際的視圖,解析方式:
*前綴(prefix)+返回值(returnVal)+後綴(suffix)得到視圖,通過轉發器轉發操作
*比如這個實例解析的實際視圖路徑如下:
* /WEB-INF/views/success.jsp
*/
@RequestMapping("/helloworld")
public String hello() {
return "success";
}
視圖success.jsp即可
//可以@RequestMapping 裏面套@RequestMapping
2 、@PathVariabl註解獲取路徑中傳遞參數
將URL中佔位符的參數綁定到controller處理方法的參數中
1 @RequestMapping(value = "/{id}/{str}")
2 public ModelAndView helloWorld(@PathVariable String id,
3 @PathVariable String str) {
4 System.out.println(id);
5 System.out.println(str);
6 return new ModelAndView("/helloWorld");
7 }
3、@ModelAttribute綁定請求參數到命令對象
spring mvc可以把這些要提交的字段封裝在一個對象中,從而請求類型就是一個POJO.
用@ModelAttribute註解獲取POST請求的FORM表單數據
jsp前端是這個樣子
1<form method="post" action="hao.do">
2 a: <input id="a" type="text" name="a"/>
3 b: <input id="b" type="text" name="b"/>
4 <input type="submit" value="Submit" />
5 </form>
java類pojo()
1 public class Pojo{
2 private String a;
3 private int b;
4 }
1 @RequestMapping(method = RequestMethod.POST)
2 public String processSubmit(@ModelAttribute("pojo") Pojo pojo) {
3
4 return "helloWorld";
5 }
4、當然如果數據少的話用HttpServletRequest獲取也可以
1 @RequestMapping(method = RequestMethod.GET)
2 public String get(HttpServletRequest request, HttpServletResponse response) {
4 System.out.println(request.getParameter("a"));
5 return "helloWorld";
6 }
5、@SessionAttributes
當我們需要在多次請求之間保持數據,一般情況需要我們明確的調用HttpSession的API來存取會話數據。Spring Web MVC提供了@SessionAttributes進行請求間透明的存取會話數據。
1、@SessionAttributes只能註解到類上
2、通過SessionStatus的setComplete()方法清除@SessionAttributes指定的會話數據
實戰例子就是:有的網頁必須保持賬號登錄狀態
@Controller
@SessionAttributes(value={"user"})
public class UserController {
@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Model model){
User user = new User("jack","123456");
model.addAttribute("user", user);
return "success";
}
}
額外自學了很多,不錯,有問題的留言或者評論哦,下課
鏈接
鏈接:https://pan.baidu.com/s/1_8Hs6V06GdX7ia5fYV4MlQ
提取碼:7s8u