SpringMVC数据响应

一、页面跳转

1.直接返回字符串

2.返回ModelAndView

@Controller
@RequestMapping("/user")
public class UserController {
    //页面跳转,返回字符串
    @RequestMapping("/method1")
    public String method1(){
        return "success";
    }
    //页面跳转,返回ModelAndView
    @RequestMapping("/method2")
    public ModelAndView method2(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("success");
        return modelAndView;
    }
    //页面跳转,返回ModelAndView
    @RequestMapping("/method3")
    public ModelAndView method3(ModelAndView modelAndView){
        modelAndView.setViewName("success");
        return modelAndView;
    }
}

二、回写数据(需要加上@ResponseBody注解,否则会被当成页面跳转)

1.直接返回字符串

2.返回对象或集合(SpringMVC会把对象转换成json格式字符串)

2.1导入依赖

  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.4</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.4</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.11.4</version>
    </dependency>
  </dependencies>

2.2配置MVC驱动(含有json转换器)

    <!--mvc注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
@Controller
@RequestMapping("/user")
public class UserController {
    //回写数据,返回字符串
    @RequestMapping("/method1")
    @ResponseBody
    public String method1(){
        return "success";
    }
    //回写数据,返回对象
    @RequestMapping("/method2")
    @ResponseBody
    public User method2(){
        User user = new User();
        user.setId(1);
        user.setName("1");
        return user;
    }
    //回写数据,返回集合
    @RequestMapping("/method3")
    @ResponseBody
    public List<User> method3(){
        List<User> userList = new ArrayList<>();
        User user1 = new User();
        user1.setId(1);
        user1.setName("1");
        User user2 = new User();
        user2.setId(2);
        user2.setName("2");
        userList.add(user1);
        userList.add(user2);
        return userList;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值