首页 文章资讯内容详情

springMvc--请求的跳转和传值

2026-06-01 2 花语

本文内容纲要:

-forword跳转页面的三种方式 -redirect跳转到页面 -跳转到Controller中的方法

forword跳转页面的三种方式

1.使用serlvet /** *使用forward跳转,传递基本类型参数到页面 *注意: *1.使用servlet原生APIRequest作用域 * */ @RequestMapping("/test") publicStringtest(HttpServletRequestrequest,HttpServletResponseresponse){ Stringname="张小三"; request.setAttribute("name",name); return"/back/attr"; } 2.使用Model对象 /** *使用forward跳转,传递基本类型参数到页面 *注意: *1.使用springmvc封装好的Model对象(底层就是request作用域) */ @RequestMapping("/test1") publicStringtest1(Modelmodel){ Stringname="张小四"; model.addAttribute("name",name); return"back/attr"; } 3.使用ModelAndView /** *使用modelAndView *注意事项 *modelAndView对象中的数据只能被ModelAndView对象的视图获取 */ @RequestMapping("/test2") publicModelAndViewtest2(ModelAndViewmodelAndView){ Stringname="张小五"; modelAndView.setViewName("back/attr"); modelAndView.addObject("name",name); returnmodelAndView; }

当然也可以通过new一个ModelAndView对象来实现

@RequestMapping("/test3") publicModelAndViewtest3(){ Stringname="张小六"; returnnewModelAndView("back/attr","name",name); }

redirect跳转到页面

使用servlet /** *使用redirect跳转向页面传递数据 *1.使用Servlet原生APISessionServletContext */ @RequestMapping("/test4") publicStringtest4(HttpServletRequestrequest,HttpSessionsession){ Stringname="张晓霞"; session.setAttribute("name",name); return"redirect:/back/attr.jsp"; } 使用ModelAndView /** *使用redirect跳转向页面传递数据 *1..使用ModelAndView对象modelAndView对象会把model中的数据以?形式拼接到地址栏后可以使用${param.key}接受 */ @RequestMapping("/test5") publicModelAndViewtest5(){ returnnewModelAndView("redirect:/back/attr.jsp","name","小张张"); }

跳转到Controller中的方法

forword跳转

redirect跳转类似

跳转到相同类中的方法:

/** *使用forword跳转到相同类中的某一方法 *注意: *1.不需要加上类上的@RequestMapping的值 */ @RequestMapping("/test00") publicStringtest00(){ return"forward:test1"; }

跳转到不同类中的方法

/** *使用forword跳转到不同类中的某一方法 *注意: *1.需要加上类上的@RequestMapping的值:比如:/hello */ @RequestMapping("/test01") publicStringtest01(){ return"forward:/hello/test"; }

本文内容总结:forword跳转页面的三种方式,redirect跳转到页面,跳转到Controller中的方法,

原文链接:https://www.cnblogs.com/liuconglin/p/5769893.html