Spring MVC方法的返回值类型

void返回值类型

如果你的方法写成了Void就跟原来Servlet含义是差不多的
json

 @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);
    }
String返回值类型(一般用于返回视图名称

1.当方法返回值为Null时,默认将请求路径当做视图 /jsp/thread/secondRequest.jsp 如果说没有试图解析器,如果返回值为Null携带数据只能用JSON

2.当方法返回一个String的字符串时,当字符串为逻辑视图名时只返回视图,如果要携带数据则使用request,session或者Json

如果要用Model或者ModelMap传递数据,那么Model或者ModelMap绝对是方法入参
3.当方法返回值加入forward的时候代表转发,如果写为redirect:xxxx代表重定向,不是返回视图了,但是不会这样做!!!!!!

乱码解决:
1.controller传递数据给页面,在RequestMapping当中指定produces="text/json;charset=utf-8"
2.Controller接收页面数据 使用编码过滤器
method代表请求方式
@RequestMapping(value = "/secondRequest*",produces="text/json;charset=utf-8",method = RequestMethod.GET)
    @ResponseBody
    public String secondRequest(HttpServletRequest request,HttpServletResponse response,ModelMap model) throws IOException {

        model.addAttribute("user","李四");
        //咱们都知道重定向不能携带数据,祝老爷子说要测试
        return "姓名:李四,年龄:16";
    }
ModelAndView返回值类型(model是携带到页面的数据   View是视图)

1.当返回为null时,页面不跳转。

2.当返回值没有指定视图名时,默认使用请求名作为视图名进行跳转。

3.当返回值指定了视图名,程序会按照视图名跳转。

@RequestMapping("/threadRequest*")
    public ModelAndView threadRequest(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        mv.addObject("user","王五");
        return mv;
    }
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;
    }

 

 
 




posted @ 2019-11-09 16:32  听风忆雪  阅读(553)  评论(0编辑  收藏  举报