【SpringMVC】学习笔记04-结果跳转方式
ModelAndView
设置ModelAndView对象,根据view的名称,和视图解析器跳转到指定的页面。
页面:{视图解析器前缀}+viewName+{视图解析器后缀}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
对应的conctroller类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class HelloController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //ModelAndView 模型和视图 ModelAndView mv= new ModelAndView(); //调用业务层 //封装对象,放到ModelAndView中。Model mv.addObject( "msg" , "HelloSpringMVC!" ); //封装要跳转的视图,放在ModelAndView中 mv.setViewName( "hello" ); // /WEB-INF/jsp/hello.jsp return mv; } } |
ServletAPI
通过设置ServletAPI , 不需要视图解析器 .
1、通过HttpServletResponse进行输出
2、通过HttpServletResponse实现重定向
3、通过HttpServletResponse实现转发
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
//转发
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}
SpringMVC实现转发和重定向-无需视图解析器
//转发的话 url不会发生变化
@RequestMapping("/m1/t2")
public String test20(Model model){
model.addAttribute("msg","不用视图解析器实现抓发");
//转发方式一
return "/WEB-INF/jsp/hello.jsp";
}
@RequestMapping("/m1/t3")
public String test03(Model model){
model.addAttribute("msg","不适用视图解析器实现转发:forward");
return "forward:/WEB-INF/jsp/hello.jsp";
}
@RequestMapping("/m1/t4")
public String test04(Model model){
model.addAttribute("msg","不使用视图解析器实现重定向:redirect");
return "redirect:/index.jsp";
}
重定向,不需要视图解析器,本质上就是重新请求一个新地方,所以注意路径问题。
可以重定向到另一个请求实现。
通过SpringMVC来实现转发和重定向-有视图解析器
@RequestMapping("/m1/t5") public String test05(Model model){ //转发 model.addAttribute("msg","使用视图解析器实现转发"); return "hello"; } @RequestMapping("/m1/t6") public String test06(Model model){ //重定向 model.addAttribute("msg","使用视图解析器实现重定向"); return "redirect:/index.jsp"; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现