modeAndView org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc-servlet.xml 1 modeAndView /
@RequestMapping("/t1")public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {rsp.sendRedirect("/index.jsp");}@RequestMapping("/t2")public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {//转发req.setAttribute("msg","/result/t3");req.getRequestDispatcher("/jsp/test.jsp").forward(req,rsp);}
springMvc.xml:
controller:
package com.lmy;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;@Controller
public class ModeAndViewController {/*** 不配置视图解析器-转发* @return*/@RequestMapping("/testForward1")public String testForward1(Model model) {model.addAttribute("smg","你好");return "/jsp/test.jsp";}/*** 不配置视图解析器-转发* @return*/@RequestMapping("/testForward2")public String testForward2(Model model) {model.addAttribute("smg","你好,转发");return "forward:/jsp/test.jsp";}/*** 不配置视图解析器-重定向* @return*/@RequestMapping("/testRedirect")public String testRedirect() {
// model.addAttribute("smg","重定向无法像转发一样携带数据");return "redirect:/jsp/test.jsp";}
}
springMvc.xml:
controller:
package com.lmy;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;@Controller
public class ModeAndViewController {/*** 配置视图解析器-转发* @return*/@RequestMapping("/testForward1")public String testForward1(Model model) {model.addAttribute("smg","你好");return "test";}/*** 重定向* @return*/@RequestMapping("/testRedirect")public String testRedirect() {
// model.addAttribute("smg","重定向无法像转发一样携带数据");return "redirect:/jsp/test.jsp";}
}
设置ModelAndView对象 , 根据view的名称 , 和视图解析器跳到指定的页面 .
页面 : {视图解析器前缀} + viewName +{视图解析器后缀}
springMvc.xml:
controller:
@RequestMapping("/testModelAndView")public ModelAndView testModelAndView() {ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("smg","你好,ModelAndView 转发");modelAndView.setViewName("test");return modelAndView;}@RequestMapping("/testModelAndView2")public ModelAndView testModelAndView2() {ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("smg","你好,ModelAndView 重定向");modelAndView.setViewName("redirect:/jsp/test.jsp");return modelAndView;}