springmvc(四)处理器方法的返回值

一、几种返回值类型

使用@Controller注解的处理器,其返回值常用四种类型:

  • ModelAndView
  • String
  • 返回自定义类型对象
  • 无返回值void

1.1、返回ModelAndView

前后端未分离开发时,返回ModelAndView,即模型+视图。

  /**
     * 返回值ModelAndView:这种方式既有数据携带,还有资源跳转
     * @return
     */
    @RequestMapping("test01")
    public ModelAndView test01(){
        ModelAndView mv=new ModelAndView();
        //相当于request.addAttribute("name","工作1");
        mv.addObject("name","工作1");
        //经过视图解析器InternalResourceViewResolver处理,将逻辑视图名称变为物理资源路径
        mv.setViewName("/jsp/result");
        return mv;
    } 

1.2、返回String

ModelAndView可以拆分两部分,Model和View,在SpringMVC中Model可以直接在参数中指定,然后返回值是逻辑视图名,视图解析器可以将逻辑视图名转换为物理视图地址。

通过内部视图资源解析器InternalResourceViewResolver将字符串与解析器中的prefix和suffix结合形成跳转的URI。

    <!--  视图解析器  -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp"/>
    </bean>
    /**
     * 返回字符串
     * @param request
     * @return
     */
    @RequestMapping("test02")
    public String test02(HttpServletRequest request){
        Job job=new Job();
        job.setId(1);
        job.setName("任务A");
        job.setDescription("紧急且重要任务");
        request.setAttribute("job",job);
        request.getSession().setAttribute("job",job);
        //经过视图解析器InternalResourceViewResolver处理,将逻辑视图名称变为物理资源路径
        return "/jsp/result";
    }
<h3>test02-------request作用域:----------${requestScope.job.id}----------${requestScope.job.name}
    ----------${requestScope.job.description}</h3>

<h3>test02-------session作用域:----------${sessionScope.job.id}----------${sessionScope.job.name}
    ----------${sessionScope.job.description}</h3>

1.3、返回对象类型

当处理器返回Object对象类型,可以是Integer、String、Map、List,也可以是自定义对象类型。但是不论是什么类型都不是作为逻辑视图出现,而是直接作为数据返回展示的。一般前端发起Ajax时候都会直接使用返回对象的形式。

返回对象的时候,需要使用@RequestBody注解,将转换后的json数据放入到响应体中。

pom文件中添加两个依赖:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.11.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.2</version>
        </dependency>

1.3.1、返回基础类型

    /**
     * 返回对象类型:Integer Double String 自定义对象类型 List Map 返回的不是逻辑视图名,而直接是数据
     * 一般是响应前端ajax请求,将json格式数据直接返回给响应体
     * @return
     */
    @ResponseBody
    @RequestMapping("test03-1")
    public Integer test031(){
        return 100;
    }

    @ResponseBody
    @RequestMapping("test03-2")
    public String test032(){
        return "abc";
    }

1.3.2、返回自定义对象类型

 @ResponseBody
    @RequestMapping("test03-3")
    public Job test033(){
        return new Job(1,"任务1","任务描述",new Date());
    }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="/js/jquery-1.11.1.js"></script>

    <script>
        $(function () {
            $("#btn1").click(function () {
                $.post("/result/test03-3","",function (data) {
                    alert(JSON.stringify(data));
                    $("#res").html("id:"+data.id+",name:"+data.name+",description:"+data.description);
                });
            });
        });
    </script>
</head>
<body>
<div>
    <button type="button" id="btn1">ajax请求自定义对象</button>
    <h3>ajax请求自定义对象结果:</h3>
    <p id="res"></p>
</div>
</body>
</html>

1.3.3、返回集合list

 @ResponseBody
    @RequestMapping("test03-4")
    public List<Job> test034(){
        List<Job> jobList=new ArrayList<>();
        int i=10;
        while (i>0){
            jobList.add(new Job(i,"任务"+i,"任务描述"+i,new Date()));
            i--;
        }
        return jobList;
    }
<div>
    <button type="button" id="btn2">ajax请求list</button>
    <h3>ajax请求list对象结果:</h3>
    <p id="res2"></p>
</div>


    <script>
        $(function () { 
            //请求list
            $("#btn2").click(function () {
                $.post("/result/test03-4","",function (data) {
                    alert(JSON.stringify(data));
                    let html="";
                    $.each(data,function(i,d){  html+="id:"+d.id+",name:"+d.name+",description:"+d.description+"<br/>";
                    });
                   $("#res2").html(html);
                });
            });
        });
    </script>

1.3.4、返回Map集合

    /**
     * 返回map集合
     * @return
     */
    @ResponseBody
    @RequestMapping("test03-5")
    public Map<String,Job> test035(){
        Map<String,Job> map=new HashMap<>();
        for(int i=0;i<10;i++){
            map.put(String.valueOf(i),new Job(i,"任务"+i,"任务描述"+i,new Date()));
        }
        return map;
    }
<div>
    <button type="button" id="btn3">ajax请求map</button>
    <h3>ajax请求map对象结果:</h3>
    <p id="res3"></p>
</div>

  <script>
        $(function () {
    
            //请求map
            $("#btn3").click(function () {
                $.post("/result/test03-5","",function (data) {
                    alert(JSON.stringify(data));
                    let html="";
                    $.each(data,function(i,d){
                        html+="id:"+d.id+",name:"+d.name+",description:"+d.description+",createTime:"+d.createTime+"<br/>";
                    });
                    $("#res3").html(html);
                });
            });
        });
    </script>

1.4、无返回值void

方法的返回值为void并不一定没有返回值,可以通过其他方式返回给前端。这种方式也为servlet中的处理方案。

 /**
     * HttpServletRequest进行服务端转发
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("test04-1")
    public void test041(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("直接使用HttpServletRequest进行服务端转发");
        request.getRequestDispatcher("/ok.jsp").forward(request,response);
    }

    /**
     * 使用HttpServletResponse进行重定向
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("test04-2")
    public void test042(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("直接使用HttpServletResponse进行重定向");
        response.sendRedirect("/ok.jsp");
    }

    /**
     * 使用HttpServletResponse做出响应
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("test04-3")
    public void test043(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw= response.getWriter();
        pw.write("112233");
        pw.flush();
        pw.close();
    }

    /**
     * 手动指定响应头实现重定向
     * @param response
     * @throws IOException
     */
    @RequestMapping("test04-4")
    public void test044(HttpServletResponse response) throws IOException {
        response.setStatus(302);
        response.setHeader("Location","/ok.jsp");
    }

二、页面导航方式

页面导航分为两种:1、转发 2、重定向

SpringMVC有两种方式实现页面转发或重定向:

  • 返回字符串
  • 使用ModelAndView

在SpingMVC进行页面导航时使用不同前缀指定转发还是重定向

  • 转发: forward:url 默认
  • 重定向: redirect:url

2.1、转发

/**
 * @Author: JSONLiu
 * @Description: SpringMVC导航方式
 * @Date Created in 2022-02-08 11:47
 * @Modified By:
 */
@Controller
@RequestMapping("nav")
public class NavigationController {

    /**
     * 字符串方式转发请求
     * @param request
     * @return
     */
    @RequestMapping("test01-1")
    public String test011(HttpServletRequest request){
        request.setAttribute("name","come on");
//        return "ok"; //默认:由视图解析器处理后将逻辑视图转换为物理资源路径
        return "forward:/ok.jsp"; //添加了forward之后,视图解析器前后缀就失效了,必须自己编写绝对路径
    }

    /**
     * ModelAndView转发请求
     * @return
     */
    @RequestMapping("test01-2")
    public ModelAndView test012(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("name","go go go");
//        mv.setViewName("ok");   //默认:由视图解析器处理后将逻辑视图转换为物理资源路径
        mv.setViewName("forward:/ok.jsp"); //添加了forward之后,视图解析器前后缀就失效了,必须自己编写绝对路径
        return mv;
    }

}

2.2、重定向

 /**
     * 字符串方式重定向
     * @param request
     * @return
     */
    @RequestMapping("test02-1")
    public String test021(HttpServletRequest request){
        request.setAttribute("name","come on"); //页面上无法获取到request作用域上的值,请求中断了
        return "redirect:/ok.jsp"; //添加了redirect之后,视图解析器前后缀就失效了,必须自己编写绝对路径
    }

    /**
     * ModelAndView方式重定向
     * @return
     */
    @RequestMapping("test02-2")
    public ModelAndView test022(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("name","go go go"); //存储在request作用域中的值以参数形式添加在url上
        mv.setViewName("redirect:/ok.jsp"); //添加了redirect之后,视图解析器前后缀就失效了,必须自己编写绝对路径
        return mv;
    }

2.3、重定向或转发到控制器

@RequestMapping("test03-1")
    public ModelAndView test031(){
        System.out.println("test03-1转发到控制器");
        ModelAndView mv=new ModelAndView();
        mv.addObject("name","哈哈哈");
        mv.setViewName("forward:/nav/test01-1");
        return mv;
    }


    @RequestMapping("test03-2")
    public ModelAndView test032(){
        System.out.println("test03-2重定向到控制器");
        ModelAndView mv=new ModelAndView();
        mv.addObject("name","哈哈哈");
        mv.setViewName("redirect:/nav/test01-1");
        return mv;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑谈子云亭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值