SpringMVC——返回值类型
2024-08-29 04:57:37
1.void作为返回值类型
如果你的方法写成了Void就跟原来Servlet含义是差不多的
@RequestMapping("/index*") public void firstRequest(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws ServletException, IOException { UserInfo info=new UserInfo(); info.setUser_id(1); info.setUser_name("张三"); /*request.setAttribute("user","张三"); request.getSession().setAttribute("user",info); request.getRequestDispatcher("/jsp/index.jsp").forward(request,response);*/ /** * Json格式传递 */ response.setCharacterEncoding("UTF-8"); String value = JSON.toJSONString(info); response.getWriter().write(value); }
2.String类型作为返回值类型
返回值类型为String时,一般用于返回视图名称
1.当方法返回值为Null时,默认将请求路径当做视图 /jsp/thread/secondRequest.jsp 如果说没有试图解析器,如果返回值为Null携带数据只能用JSON
2.当方法返回一个String的字符串时,当字符串为逻辑视图名时只返回视图,如果要携带数据则使用request,session或者Json
如果要用Model或者ModelMap传递数据,那么Model或者ModelMap绝对是方法入参
3.当方法返回值加入forward的时候代表转发,如果写为redirect:xxxx代表重定向,不是返回视图了,但是不会这样做!!!!!!
@RequestMapping() public String secondRequest(HttpServletRequest request,HttpServletResponse response,ModelMap model) throws IOException { // return "index" //return "forward:/jsp/index.jsp"; }
3.ModelAndView作为返回值类型
ModelAndView model是携带到页面的数据 View是视图
@RequestMapping("/threadRequest*") public ModelAndView threadRequest(){ ModelAndView mv=new ModelAndView(); mv.setViewName("index"); mv.addObject("user","王五"); return mv; }
4.Object作为返回值类型
1.当方法返回值为Null时,默认将请求路径当做视图 /jsp/thread/secondRequest.jsp 如果说没有试图解析器,如果返回值为Null携带数据只能用JSON
2.当方法返回值为String类型字符串时,就是视图的逻辑名称
3.当返回对象或者集合数据时,要使用Json格式字符串,可选fastJson手动转换,也可以使用jackson自动转换
@RequestMapping("/fourthRequest") @ResponseBody //响应体返回数据时,除了手动装换JSON格式字符串以外可以使用jackson public Object fourthRequest(){ List<UserInfo> userList=new ArrayList<>(); UserInfo info=new UserInfo(); info.setUser_id(1); info.setUser_name("张三"); UserInfo info2=new UserInfo(); info2.setUser_id(2); info2.setUser_name("李四"); userList.add(info); userList.add(info2); return userList; } }
在这里使用jackson需要导入依赖:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency>
最新文章
- Java 序列化与反序列化
- [Python学习笔记1]Python语言基础 数学运算符 字符串 列表
- web页面如何播放amr的音频文件
- Windows系统安装Oracle 11g 数据库
- 异常处理__try{}__except(EXCEPTION_EXECUTE_HANDLER){}
- Git 使用命令
- Jquery 生成时钟
- linux rpm 安装包 信息查询
- 跟我一起学extjs5(17--Grid金额字段单位MVVM方式的选择)
- English - allow&#160;to&#160;do&#160;与&#160;allow&#160;doing&#160;的区别
- SSH协议详解(转)
- 查看Oracle正在执行的任务
- poj 3662 Telephone Lines
- Mac OSX bash function 备份
- java方法重载和重写
- Javascript高级编程学习笔记(8)—— 变量
- Micro QR 和QR码
- python学习 day14 (3月19日)----
- MYSQL查询语句大全集锦
- Publish/Subscribe Model——Notification chain——观察者模式