2021-08-17

java控制器返回视图类型_SpringMVC中的Controller方法的(返回值/参数类型)

一. Controller方法的返回值:

1、 返回的ModelAndView

ModelAndView 存放数据, addObject(),往model(request域)添加数据

ModelAndView 添加逻辑视图名, setViewName(), 经过视图解析器,得到物理视图, 转发到物理视图

@RequestMapping("/getUser.action")public ModelAndView getUser(@RequestParam(name=“userId”,required = true)Integer id) throwsException{
System.out.println(“id=”+id);

ModelAndView modelAndView= newModelAndView();

User user=userService.queryOne(id);

modelAndView.addObject(“user”, user);

modelAndView.setViewName(“userinfo”);returnmodelAndView;

}

2、 String类型, 返回的视图

a. 逻辑视图名, 经过视图解析器,得到物理视图, 转发

@RequestMapping("/index.action")publicString toIndex() {return “index”;

b. redirect:资源路径, 不经过视图解析器,要求这个资源路径写完整的路径: /开头, 表示/项目名 重定向到资源

@RequestMapping("/index.action")publicString toIndex() {//重定向到index.jsp, 完整的路径

return “redirect:/jsp/index.jsp”;

c. forward:资源路径, 不经过视图解析器,要求这个资源路径写完整的路径: /开头,表示/项目名 转发向到资源

@RequestMapping("/index.action")publicString toIndex() {return “forward:/jsp/index.jsp”;

d.响应给前端的字符串,(数据),需要结合@ResponseBody

//将user对象以json的格式响应给前端页面

@RequestMapping("/queryUserByCondition.action")

@ResponseBodypublic User queryUserByCondition(User user) throwsException{returnuser;

}

3、Java对象

需要结合@ResponseBody, 发生的数据,(json)

主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的),只能是post提交,get没有请求体

@RequestMapping("/queryUserByCondition.action")

@ResponseBodypublic User queryUserByCondition( @RequestBody User user) throwsException{returnuser;

}

4、 void, 默认逻辑视图名

controller的@RequestMapping() 前缀+ 方法名, 很少使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值