SpringMVC controller方法返回值见解3

3.controller方法返回值

3.1.返回ModelAndView

  • 说明:controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view

3.2.返回字符串

3.2.1.逻辑视图名

  • 说明:controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。

  • 返回字符串

    java 复制代码
    @Controller
    @RequestMapping("/account")
    public class AccountController {
        @RequestMapping(value = "/findAccount2")
        public String findAccount2(Model model) {
            //添加数据
            model.addAttribute("msg", "欢迎你 springmvc");
            return "success";
        }
    }
  • 在index.jsp里面定义超链接

    html 复制代码
    <a href="/account/findAccount2">返回字符串</a>

3.2.2.Redirect重定向

  • 说明:

    • Contrller方法返回结果重定向到一个url地址,如下商品修改提交后重定向到商品查询方法,参数无法带到商品查询方法中。
    • redirect方式相当于"response.sendRedirect()",转发后浏览器的地址栏变为转发后的地址,因为转发即执行了一个新的request和response。
    • 由于新发起一个request原来的参数在转发时就不能传递到下一个url,如果要传参数可以/item/queryItem后边加参数,如下:/item/queryItem?...&.....
  • 重定向

    java 复制代码
    @Controller
    @RequestMapping("/account")
    public class AccountController {
        
        @RequestMapping(value = "/findAccount3")
        public String findAccount3() {
            return "redirect:/account/findAccount4";
        }
    
        @RequestMapping(value = "/findAccount4")
        public String findAccount4(Model model) {
            //添加数据
            model.addAttribute("msg", "这是springmvc的重定向");
            return "success";
        }
    }
  • 在index.jsp里面定义超链接

    html 复制代码
    <a href="/account/findAccount3">重定向</a>

3.2.3.forward转发

  • 说明:

    • controller方法执行后继续执行另一个controller方法,如下商品修改提交后转向到商品查询页面,修改商品的id参数可以带到商品查询方法中。
    • forward方式相当于request.getRequestDispatcher().forward(request,response),转发后浏览器地址栏还是原来的地址。转发并没有执行新的request和response,而是和转发前的请求共用一个request和response。所以转发前请求的参数在转发后仍然可以读取到。
  • 重定向

    java 复制代码
    @Controller
    @RequestMapping("/account")
    public class AccountController {
        
        @RequestMapping(value = "/findAccount3")
        public String findAccount3() {
            return "forward:/account/findAccount4";
        }
    
        @RequestMapping(value = "/findAccount4")
        public String findAccount4(Model model) {
            //添加数据
            model.addAttribute("msg", "这是springmvc的重定向");
            return "success";
        }
    }
  • 在index.jsp里面定义超链接

    html 复制代码
    <a href="/account/findAccount3">重定向和请求转发</a>
相关推荐
代码小将1 小时前
Leetcode209做题笔记
java·笔记·算法
专注_每天进步一点点1 小时前
idea 启动Springboot项目在编译阶段报错:java: OutOfMemoryError: insufficient memory
java·spring boot·intellij-idea
dhxhsgrx2 小时前
PYTHON训练营DAY25
java·开发语言·python
不知几秋3 小时前
数字取证-内存取证(volatility)
java·linux·前端
chxii6 小时前
5java集合框架
java·开发语言
玉笥寻珍7 小时前
Web安全渗透测试基础知识之HTTP参数污染篇
网络·网络协议·安全·web安全·http
yychen_java7 小时前
R-tree详解
java·算法·r-tree
JANYI20187 小时前
嵌入式设计模式基础--C语言的继承封装与多态
java·c语言·设计模式
xrkhy8 小时前
反射, 注解, 动态代理
java
Ten peaches8 小时前
Selenium-Java版(操作元素)
java·selenium·测试工具·html