ssm 转发请求_springmvc(重定向和请求转发、数据的接收和回显)
1、請求轉發
(1)直接書寫要轉發的頁面:
@Controller
public class HelloController{
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","nihao");
return "/test.jsp";
}
}
注意:請求轉發和重定向是不需要視圖解析器參與的,因為這里已經寫了完整的路徑,有視圖解析器的話拼接地址后會出錯
(2)添加forward關鍵字:
@Controllerpublic classHelloController{
@RequestMapping("/hello")publicString hello(Model model){
model.addAttribute("msg","nihao");return "forward:/test.jsp";
}
}
2、重定向
@Controllerpublic classHelloController{
@RequestMapping("/hello")publicString hello(Model model){
model.addAttribute("msg","nihao");return "redirect:/test.jsp";
}
}
可以看到地址欄已經發生變化,但是由于重定向的時候不能攜帶數據,因此,jsp頁面的內容不能顯示
3、數據的接收
(1)提交的域名稱和處理的方法的參數名一致
@Controller
@RequestMapping("/teacher")public classTeacherController {
@GetMapping("/t1")publicString testTeacher(String tname, Model model){//接收前端的參數,要注意要和函數中的參數保持一致
System.out.println("接收到前端的參數為:"+tname);//將返回的結果傳遞給前端
model.addAttribute("msg",tname);return "test";
}
}
(2)提交的域名稱和處理的方法的參數名不一致
@Controller
@RequestMapping("/teacher")public classTeacherController {
@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 classTeacherController {
@GetMapping("/t1")publicString 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 classHelloController{
@RequestMapping("/haha")publicString hello(Model model){
model.addAttribute("msg","Good Morning!!");//封裝數據
return "hello";//被視圖解析器處理
}
}
(2)ModelAndView
public class HelloController implementsController {publicModelAndView handleRequest(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)throwsException {
ModelAndView modelAndView=newModelAndView();
modelAndView.addObject("msg","HelloSpringMVC");
modelAndView.setViewName("hello");//hello.jsp
returnmodelAndView;
}
}
(3)ModelMap
@Controller
@RequestMapping("/teacher")public classTeacherController {
@GetMapping("/t1")publicString testModelMap(ModelMap modelMap){
modelMap.addAttribute("msg","hhhha");return "test";
}
}
(4)三種方式的比較:
Model:方法較少,只適合于存儲數據
ModelMap:繼承了LinkedMap,除了實現自身的一些方法,同樣的繼承了LinkedMap的方法和特性
ModelAndView:可以在存儲數據的同時進行設置返回的邏輯視圖,進行控制展示層的跳轉
總結
以上是生活随笔為你收集整理的ssm 转发请求_springmvc(重定向和请求转发、数据的接收和回显)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 推荐CUDA程序优化的15个策略
- 下一篇: C++中的private protect