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>