SpringMVC方法返回值多种情况代码实例
返回ModelAndView
如果前后端不分的开发,大部分情况下,我们返回ModelAndView,即数据模型+视图:
@Controller
@RequestMapping("/user")
publicclassHelloController{
@RequestMapping("/hello")
publicModelAndViewhello(){
ModelAndViewmv=newModelAndView("hello");
mv.addObject("username","javaboy");
returnmv;
}
}
Model中,放我们的数据,然后在ModelAndView中指定视图名称
返回Void
没有返回值。没有返回值,并不一定真的没有返回值,只是方法的返回值为void,我们可以通过其他方式给前端返回。实际上,这种方式也可以理解为Servlet中的那一套方案。
注意,由于默认的Maven项目没有Servlet,因此这里需要额外添加一个依赖:
javax.servlet javax.servlet-api 4.0.1
通过HttpServletRequest做服务端跳转
@RequestMapping("/hello2")
publicvoidhello2(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
req.getRequestDispatcher("/jsp/hello.jsp").forward(req,resp);//服务器端跳转
}
通过HttpServletRequest做服务跳转
@RequestMapping("/hello2")
publicvoidhello2(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
req.getRequestDispatcher("/jsp/hello.jsp").forward(req,resp);//服务器端跳转
}
通过HttpServletResponse做重定向
@RequestMapping("/hello3")
publicvoidhello3(HttpServletRequestreq,HttpServletResponseresp)throwsIOException{
resp.sendRedirect("/hello.jsp");
}
也可以自己手动指定响应头去实现重定向:
@RequestMapping("/hello3")
publicvoidhello3(HttpServletRequestreq,HttpServletResponseresp)throwsIOException{
resp.setStatus(302);
resp.addHeader("Location","/jsp/hello.jsp");
}
通过HttpServletResponse给出响应
@RequestMapping("/hello4")
publicvoidhello4(HttpServletRequestreq,HttpServletResponseresp)throwsIOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriterout=resp.getWriter();
out.write("hellojavaboy!");
out.flush();
out.close();
}
这种方式,既可以返回JSON,也可以返回普通字符串。
返回字符串
返回逻辑视图名
前面的ModelAndView可以拆分为两部分,Model和View,在SpringMVC中,Model我们可以直接在参数中指定,然后返回值是逻辑视图名:
@RequestMapping("/hello5")
publicStringhello5(Modelmodel){
model.addAttribute("username","javaboy");//这是数据模型
return"hello";//表示去查找一个名为hello的视图
}
服务端跳转
@RequestMapping("/hello5")
publicStringhello5(){
return"forward:/jsp/hello.jsp";
}
forward后面跟上跳转的路径。
客户端跳转
@RequestMapping("/hello5")
publicStringhello5(){
return"redirect:/user/hello";
}
真的返回一个字符串
上面三个返回的字符串,都是由特殊含义的,如果一定要返回一个字符串,需要额外添加一个注意:@ResponseBody,这个注解表示当前方法的返回值就是要展示出来返回值,没有特殊含义。
@RequestMapping("/hello5")
@ResponseBody
publicStringhello5(){
return"redirect:/user/hello";
}
上面代码表示就是想返回一段内容为redirect:/user/hello的字符串,他没有特殊含义。注意,这里如果单纯的返回一个中文字符串,是会乱码的,可以在@RequestMapping中添加produces属性来解决:
@RequestMapping(value="/hello5",produces="text/html;charset=utf-8")
@ResponseBody
publicStringhello5(){
return"Java语言程序设计";
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
2 成都训练狗狗
3 怎么训练小狗狗
4 训练狗狗软件
5 如何训练狗狗拉屎
9 狗狗负重训练
10 狗狗多大可以训练大小便
11 怎么训练狗狗萨摩耶
12 狗狗训练书
13 鞍山狗狗训练
14 训练狗狗用品
15 怎样才能训练狗狗听话
16 狗狗如何训练大小便
17 怎样训练狗狗睡狗窝
18 训练狗狗工具