SpringMVC入門學習---資料的處理

Singgle發表於2019-05-11

1.提交資料的處理

a)提交的引數名和處理方法的引數名一致

#HelloController.java
@RequestMapping("/hello")
public String hello(String name) {
	System.out.println(name);
	return "index.jsp";
}
複製程式碼

注:我們不需要配置檢視解析器

我們在瀏覽器輸入 http://localhost:8080/02springweb_annotation/hello.do?name=asd,在控制檯上我們會看到輸出了asd

b)提交的引數名和處理方法的引數名不一致

那麼當我們在提交的引數名和處理方法的引數名不一樣的時候,怎麼解決。

#HelloController.java
@RequestMapping("/hello")
public String hello(@RequestParam("uname")String name) {
	System.out.println(name);
	return "index.jsp";
}
複製程式碼

c)提交一個物件

建立一個實體類User

#User.java
package com.xgc.entity;

public class User {
	private String name;
	private int id;
	private String pwd;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", id=" + id + ", pwd=" + pwd + "]";
	}
}
複製程式碼

HelloController.java

@RequestMapping("/user")
public String user(User user) {
	System.out.println(user);
	return "index.jsp";
}
複製程式碼

當我們輸入 http://localhost:8080/02springweb_annotation/user.do?name=zxc&pwd=123的時候,在控制檯上會輸出User [name=zxc, id=0, pwd=123]

2.將資料顯示到UI層

a)ModelAndView--需要檢視解析器

public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
	ModelAndView mv=new ModelAndView();
	mv.addObject("msg","hello springmvc");
	mv.setViewName("hello");
	return mv;
}
複製程式碼

b)ModelMap---不需要檢視解析器

@RequestMapping("/hello")
public String hello(@RequestParam("uname")String name,ModelMap model) {
	model.addAttribute("name", name);
	System.out.println(name);
	return "index.jsp";
}
複製程式碼

c)ModelAndView和ModelMap的異同

相同點:都可以將資料封裝到表示層頁面中

不同點:

ModelAndView可以指定跳轉的檢視,而ModelMap不能

ModelAndView需要檢視解析器,ModelMap不需要配置

相關文章