ssm 转发请求_springmvc(重定向和请求转发、数据的接收和回显)
1、請(qǐng)求轉(zhuǎn)發(fā)
(1)直接書寫要轉(zhuǎn)發(fā)的頁(yè)面:
@Controller
public class HelloController{
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","nihao");
return "/test.jsp";
}
}
注意:請(qǐng)求轉(zhuǎn)發(fā)和重定向是不需要視圖解析器參與的,因?yàn)檫@里已經(jīng)寫了完整的路徑,有視圖解析器的話拼接地址后會(huì)出錯(cuò)
(2)添加forward關(guān)鍵字:
@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";
}
}
可以看到地址欄已經(jīng)發(fā)生變化,但是由于重定向的時(shí)候不能攜帶數(shù)據(jù),因此,jsp頁(yè)面的內(nèi)容不能顯示
3、數(shù)據(jù)的接收
(1)提交的域名稱和處理的方法的參數(shù)名一致
@Controller
@RequestMapping("/teacher")public classTeacherController {
@GetMapping("/t1")publicString testTeacher(String tname, Model model){//接收前端的參數(shù),要注意要和函數(shù)中的參數(shù)保持一致
System.out.println("接收到前端的參數(shù)為:"+tname);//將返回的結(jié)果傳遞給前端
model.addAttribute("msg",tname);return "test";
}
}
(2)提交的域名稱和處理的方法的參數(shù)名不一致
@Controller
@RequestMapping("/teacher")public classTeacherController {
@GetMapping("/t1")public String testTeacher(@RequestParam("name") String tname, Model model){//接收前端的參數(shù),要注意要和函數(shù)中的參數(shù)保持一致
System.out.println("接收到前端的參數(shù)為:"+tname);//將返回的結(jié)果傳遞給前端
model.addAttribute("msg",tname);return "test";
}
}
4、接收一個(gè)對(duì)象
@Controller
@RequestMapping("/teacher")public classTeacherController {
@GetMapping("/t1")publicString testTeacher(Teacher teacher){
System.out.println("接收到前端的數(shù)據(jù)為:"+teacher);return "test";
}
}
在控制臺(tái)打印出前端傳遞的數(shù)據(jù):
Teacher(teacherno=null, tname=null, major=jsj, prof=null, department=null)
注意:前端傳遞數(shù)據(jù)的時(shí)候的參數(shù)名要和對(duì)象的屬性名對(duì)應(yīng)
5、數(shù)據(jù)的回顯
(1)Model
@Controller
@RequestMapping("nihao")public classHelloController{
@RequestMapping("/haha")publicString hello(Model model){
model.addAttribute("msg","Good Morning!!");//封裝數(shù)據(jù)
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:方法較少,只適合于存儲(chǔ)數(shù)據(jù)
ModelMap:繼承了LinkedMap,除了實(shí)現(xiàn)自身的一些方法,同樣的繼承了LinkedMap的方法和特性
ModelAndView:可以在存儲(chǔ)數(shù)據(jù)的同時(shí)進(jìn)行設(shè)置返回的邏輯視圖,進(jìn)行控制展示層的跳轉(zhuǎn)
總結(jié)
以上是生活随笔為你收集整理的ssm 转发请求_springmvc(重定向和请求转发、数据的接收和回显)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 推荐CUDA程序优化的15个策略
- 下一篇: 深入理解CUDA线程层次以及关于设置线程