遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

SpringMVC响应数据

返回值分类

字符串、void、转发和重定向、@ResponseBody响应json数据

 

字符串

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

Controller:

package com.qzcsbj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ReturnController {
    @RequestMapping("/testReturnString")
    public String testReturnString() {
        System.out.println("执行testReturnString方法。");
        return "success";
    }
}

  

直接访问:http://localhost:8080/testReturnString

 

void

Servlet原始API可以作为控制器中方法的参数:

1、使用request转向页面

package com.qzcsbj.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ReturnController {
    @RequestMapping("/testReturnVoid")
    public void testReturnVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("返回值是void");
        request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
    }
}

 

2、通过response页面重定向

package com.qzcsbj.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ReturnController {
    @RequestMapping("/testReturnString")
    public String testReturnString() {
        System.out.println("执行testReturnString方法。");
        return "success";
    }

    @RequestMapping("/testReturnVoid")
    public void testReturnVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("返回值是void");
        // request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
        // response.sendRedirect("/WEB-INF/jsp/success.jsp");  // 访问会报错
        response.sendRedirect("testReturnString");
    }
}

 

3、通过response指定响应结果,例如响应json数据:

package com.qzcsbj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ReturnController {
    @RequestMapping("/testReturnVoid")
    public void testReturnVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("返回值是void");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"code\":\"00\",\"msg\":\"成功\"}");
    }
}

 

直接访问:http://localhost:8080/testReturnVoid

 

转发和重定向

forward转发(最后url不会变)

controller方法在提供了String类型的返回值之后,默认就是请求转发。

也就是说,return "success";可以写成:

return "forward:/WEB-INF/jsp/success.jsp";


需要注意的是,如果用了formward:则路径必须写成实际视图url,不能写逻辑视图。 

不能写成:

return "forward:success.jsp";

也不能写成:

return "forward:success";

否则都会报404

 

Redirect重定向(最后url会变)

contrller方法提供了一个String类型返回值之后,它需要在返回值里使用:redirect:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <h1>Hello, SpringMVC</h1>

  <h1>${requestScope.username}</h1>
</body>
</html>

 

控制器

package com.qzcsbj.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ReturnController {
    @RequestMapping("/testReturnModelAndView")
    public ModelAndView testReturnModelAndView() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("username", "jack");
        mv.setViewName("success"); 
        return mv;
    }

    @RequestMapping("/testRedirect")
    public String testRedirect() {
        System.out.println("执行testRedirect方法。");
        return "redirect:testReturnModelAndView";
    }
}

 

注意,下面url变了

请求的是:http://localhost:8080/testRedirect

 

@ResponseBody响应json数据

作用:该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json、xml等

Springmvc默认用MappingJacksonHttpMessageConverter对json数据进行转换,需要加入jackson的包。

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

 

实体类

package com.qzcsbj.pojo;
 
import java.io.Serializable;
 
 
public class Account implements Serializable {
    private static final long serialVersionUID = -7258686420068923807L;
 
    private Integer id;
    private String name;
    private Float money;
 
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Float getMoney() {
        return money;
    }
 
    public void setMoney(Float money) {
        this.money = money;
    }
 
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

 

控制器中的代码:

package com.qzcsbj.controller;

import com.qzcsbj.pojo.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;


@Controller
public class ReturnJsonController {
    @RequestMapping("/testResponseJson")
    @ResponseBody
    public Account testResponseJson(@RequestBody Account account){  // 通过@requestbody把json字符串封装到account对象中
        return account;
    }
}

 

启动tomcat,通过jmeter发送请求

 

 

 

【bak】

原文会持续更新,原文地址:https://www.cnblogs.com/uncleyong/p/17053559.html

 

posted @ 2023-01-15 20:26  全栈测试笔记  阅读(54)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end