本身这个知识点也不难,直接给代码吧
package cn.abalone.controller;
import cn.abalone.po.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @Author: gavy
* CreateTime: 2020-06-26-08-13
* <p>
* 关于前端给后端的传值
*/
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 第一种传值方式"map传值"
*
* @param map
* @return
*/
@RequestMapping("/test01")
public String test01(Map<String, User> map) {
User user = new User(1, "张三");
map.put("user", user);
return "user";
}
/**
* 第二种传值方式"model传值"
*
* @param model
* @return
*/
@RequestMapping("/test02")
public String test02(Model model) {
User user = new User(2, "李四");
model.addAttribute("user", user);
return "user";
}
/**
* 第三种传值方式: ModelAndView传值
*
* @return
*/
@RequestMapping("/test03")
public ModelAndView test03() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", new User(3, "王五"));
modelAndView.setViewName("user");
return modelAndView;
}
/**
* 第四种传值方式: HttpServletRequest传值
*
* @param request
* @return (ModelAttribute注解同时也会为此传值形式带来User)
*/
@RequestMapping("/test04")
public String test04(HttpServletRequest request) {
request.setAttribute("user", new User(4, "赵六"));
return "user";
}
/**
* 第五种传值方式,@ModelAttribute 在所有方法之前先运行,
* 然后存入到model中,业务方法可以直接返回视图
*
* @return
*/
@ModelAttribute
public User getUser() {
return new User(4, "杨七");
}
//业务方法直接返回视图
@RequestMapping("/test05")
public String test05() {
return "user";
}
}
Q.E.D.