1、請求轉發
(1)直接書寫要轉發的頁面:
@Controller
public class HelloController{
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","nihao");
return "/test.jsp";
}
}
注意:請求轉發和重定向是不需要視圖解析器參與的,因為這里已經寫了完整的路徑,有視圖解析器的話拼接地址后會出錯
(2)添加forward關鍵字:
@Controller public class HelloController{ @RequestMapping("/hello") public String hello(Model model){ model.addAttribute("msg","nihao"); return "forward:/test.jsp"; } }
2、重定向
@Controller public class HelloController{ @RequestMapping("/hello") public String hello(Model model){ model.addAttribute("msg","nihao"); return "redirect:/test.jsp"; } }
可以看到地址欄已經發生變化,但是由於重定向的時候不能攜帶數據,因此,jsp頁面的內容不能顯示
3、數據的接收
(1)提交的域名稱和處理的方法的參數名一致
@Controller @RequestMapping("/teacher") public class TeacherController { @GetMapping("/t1") public String testTeacher(String tname, Model model){ //接收前端的參數,要注意要和函數中的參數保持一致 System.out.println("接收到前端的參數為:"+tname); //將返回的結果傳遞給前端 model.addAttribute("msg",tname); return "test"; } }
(2)提交的域名稱和處理的方法的參數名不一致
@Controller @RequestMapping("/teacher") public class TeacherController { @GetMapping("/t1") public String testTeacher(@RequestParam("name") String tname, Model model){ //接收前端的參數,要注意要和函數中的參數保持一致 System.out.println("接收到前端的參數為:"+tname); //將返回的結果傳遞給前端 model.addAttribute("msg",tname); return "test"; } }
4、接收一個對象
@Controller @RequestMapping("/teacher") public class TeacherController { @GetMapping("/t1") public String testTeacher(Teacher teacher){ System.out.println("接收到前端的數據為:"+teacher); return "test"; } }
在控制台打印出前端傳遞的數據:
Teacher(teacherno=null, tname=null, major=jsj, prof=null, department=null)
注意:前端傳遞數據的時候的參數名要和對象的屬性名對應
5、數據的回顯
(1)Model
@Controller @RequestMapping("nihao") public class HelloController{ @RequestMapping("/haha") public String hello(Model model){ model.addAttribute("msg","Good Morning!!");//封裝數據 return "hello";//被視圖解析器處理 } }
(2)ModelAndView
public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("msg","HelloSpringMVC"); modelAndView.setViewName("hello");//hello.jsp return modelAndView; } }
(3)ModelMap
@Controller @RequestMapping("/teacher") public class TeacherController { @GetMapping("/t1") public String testModelMap(ModelMap modelMap){ modelMap.addAttribute("msg","hhhha"); return "test"; } }
(4)三種方式的比較:
Model:方法較少,只適合於存儲數據
ModelMap:繼承了LinkedMap,除了實現自身的一些方法,同樣的繼承了LinkedMap的方法和特性
ModelAndView:可以在存儲數據的同時進行設置返回的邏輯視圖,進行控制展示層的跳轉