一、ModelAndView
设置ModelAndView对象,根据view的名称,和视图解析器跳转到指定的页面。
页面:{视图解析器前缀} + viewName + {视图解析器后缀}
二、ServletAPI
通过设置ServletAPI ,不需要视图解析器。
- 通过HttpServletResponse进行输出
package com.massimo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.IIOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller
public class ModelTest1 {
@RequestMapping("m1/t1")
public String test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "hello";
}
}
效果:
- 通过HttpServletResponse实现重定向
package com.massimo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.IIOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller
public class ModelTest1 {
@RequestMapping("/m1/t2")
public void test2(HttpServletRequest request , HttpServletResponse response) throws Exception{
response.sendRedirect("/hello");
}
}
效果:
- 通过HttpServletResponse实现转发
package com.massimo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.IIOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller
public class ModelTest1 {
@RequestMapping("m1/t3")
public void test3(HttpServletRequest request , HttpServletResponse response) throws Exception{
//转发
request.setAttribute("msg","/m1/t3");
request.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(request,response);
}
}
项目结构:
三、通过SpringMVC来实现转发和重定向——无需视图解析器
沿用上面的项目,并将视图解析器注释掉!
3.1、方式一
@RequestMapping("m1/t1")
public String test1(Model model) {
//转发
model.addAttribute("msg","ModelTest1");
return "/WEB-INF/jsp/hello.jsp";
}
效果:
3.2、方式二
@RequestMapping("m1/t1")
public String test1(Model model) {
//转发
model.addAttribute("msg","ModelTest1+forward");
return "forward:/WEB-INF/jsp/hello.jsp";
}
方式二:
3.3、方式三
@RequestMapping("m1/t1")
public String test1(Model model) {
//重定向
model.addAttribute("msg","ModelTest1+redirect");
return "redirect:/index.jsp";
}
效果:
四、通过S pringMVC来实现转发和重定向——有视图解析器
重定向,不需要视图解析器,本质就是重新请求一个新地方。所以注意路径问题。