1. 程式人生 > 其它 >設計模式:概述、OOP七大設計原則

設計模式:概述、OOP七大設計原則

處理前臺提交的資料

1、提交的域名稱和處理方法的引數名一致

提交資料 :http://localhost:8080/SpringMVC_05//05/t1/xiangtong

處理方法 :

@RequestMapping("/05/t1")
public String teste1(String name, Model model){
model.addAttribute("msg","相同引數"+name);
return "test1";
}

//RestFul風格
@RequestMapping("/05/t1/{name}")
public String teste1(@PathVariable String name, Model model){
model.addAttribute("msg","相同引數"+name);
return "test1";
}

2、提交的域名稱和處理方法的引數名不一致

提交資料 : http://localhost:8080/hello?username=kuangshen

處理方法 :使用@RequestParam註解進行翻譯

//@RequestParam("username") : username提交的域的名稱 .
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
   System.out.println(name);
   return "hello";
}

3、提交的是一個物件

要求提交的表單域和物件的屬性名一致 , 引數使用物件即可

  建立實體類

public class User {
   private int id;
   private String name;
   private int age;
   //構造
   //get/set
   //tostring()
}

  前臺提交的請求:http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15

  處理辦法:

@RequestMapping("/user")
public String user(User user){
   System.out.println(user);
   return "hello";
}

  說明:如果使用物件的話,前端傳遞的引數名和物件名必須一致,否則就是null。

資料顯示到前端

第一種 : 通過ModelAndView

我們前面一直都是如此 . 就不過多解釋

public class ControllerTest1 implements Controller {

public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一個模型檢視物件
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}

第二種 : 通過ModelMap

ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封裝要顯示到檢視中的資料
//相當於req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}

第三種 : 通過Model

Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
//封裝要顯示到檢視中的資料
//相當於req.setAttribute("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}

對比

就對於新手而言簡單來說使用區別就是:

Model 只有寥寥幾個方法只適合用於儲存資料,簡化了新手對於Model物件的操作和理解;

ModelMap 繼承了 LinkedMap ,除了實現了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性;

ModelAndView 可以在儲存資料的同時,可以進行設定返回的邏輯檢視,進行控制展示層的跳轉。