SpringMVC-資料處理
阿新 • • 發佈:2021-08-16
處理提交資料
1. 提交的域名稱與處理方法的引數名一致
- 提交資料【
http://localhost:8080/springmvc/hello?name=iris
】 - 處理方法
/** * location: 8080/user/t1?name=xxx * @param name */ @GetMapping("/t1") public String test01(String name, Model model) { // 接收前端引數 System.out.println("接收到前端資訊("+name+")"); // 將返回結果傳輸至前端 -- Model model.addAttribute("msg", name); // 檢視跳轉 return "test"; }
- 後臺輸出
接收到前端資訊(iris)
- 前端輸出
iris
2. 提交的域名稱與處理方法的引數名不同
- 提交資料【
http://localhost:8080/springmvc/hello?username=iris
】 - 處理方法
- 後臺輸出
接收到前端資訊(iris)
- 前端輸出
iris
3. 提交的是一個物件/JSON資料
所提交表單域須和物件的屬性名一致,引數使用物件即可,否則對應屬性值會為null
- 構建對應實體類
package cn.iris.pojo; /** * @author Iris 2021/8/16 */ public class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
- 提交資料【
http://localhost:8080/springmvc/user/t1?name=iris&age=20
】 - 處理方法
/** * location: 8080/user/t1?name=xxx&age=xxx * @param user * @param model * @return */ @GetMapping("/t1") public String test01(User user, Model model) { // 接收前端引數 System.out.println("接收到前端資訊("+user.getName()+","+ user.getAge()+")"); // 將返回結果傳輸至前端 -- Model model.addAttribute("msg", user.toString()); // 檢視跳轉 return "test"; }
- 後臺輸出
接收到前端資訊(iris,20)
- 前端輸出
User{name='iris', age=20}
資料顯示至前端
1. ModelAndView
public class ControllerTest01 implements Controller {
public ModelAndView handlerRequest(HttpServletRequest req, HttpServletResponse resp) {
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "ControllerTest01");
mv.setViewName("test");
return mv;
}
}
2. ModelMap
@GetMapping("/t3")
public String test03(ModelMap map) {
map.addAttribute("msg","aaa");
return "test";
}
3. Model
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/t2")
public String test02(@RequestParam("username") String name, Model model) {
// 將返回結果傳輸至前端 -- Model
model.addAttribute("msg", name);
// 檢視跳轉
return "test";
}
}
對比
- ModelAndView (普通發售版)
- ModelMap(繼承於LinkedHashmap,Plus版)
- Model(精簡版,開發常用,具備常規功能)