转载

SpringBoot(2)-最简SpringBoot的几点说明

  • 使用void,map,Model 时,返回对应的逻辑视图名称真实url为:prefix前缀+视图名称 +suffix后缀组成,如果返回值和请求一致,则可能报错:

Circular view path [login]: would dispatch back to the current handler URL [/login] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

  • 在控制层的类注解是 @RestController@Controller 不同,返回的并不是一个页面,而是Json字符串。原因是因为在 @Controller 上加上了 @ResponseBody

    如果要返回一个页面有两种方式,一种是将 @RestController 改成 @Controller ,另外一种是不返回 String 而是返回一个 ModelAndView ,如下所示

@RestController
public class HomeController{

 @RequestMapping({"/index"})
 public String index(){
 return "Hello SpringBoot";
 }
}
@RestController
public class IndexController{

 private String DEFAULT_INDEX = "index";


 /**
* 因为是注释的是@RestController,如果返回值是String,前台返回的是内容而不是模板
* @return
*/
 @RequestMapping({"/"})
 public ModelAndView home(){
 return new ModelAndView(DEFAULT_INDEX);
 }

}

返回JSON

 /**
* 返回JSON
* @param map
* @return
*/
 @RequestMapping("/indexHtml")
 public User helloHtml(Map<String, Object> map){
 User user = new User();
 user.setName("中文");
 user.setId(1L);
 user.setCreateDate(new Date());
 map.put("user", user);
 map.put("msg", "This is a English");
 return user;
 }

``` 

## 返回模板

``` java

 /**
* 返回模板
* @param map
* @return
*/
 @RequestMapping("/indexHtml2")
 public ModelAndView helloHtml2(Map<String, Object> map){
 ModelAndView mv = new ModelAndView("user");
 User user = getUser();
 mv.addObject("user", user);
 mv.addObject("msg", "This is a English");
 return mv;
 }

返回模板 indexHtml3

/**
 * 返回错误信息
 * @param map
 * @return
 */
@RequestMapping("/indexHtml3")
public Map helloHtml3(Map<String, Object> map) {
    User user = getUser();
    map.put("user", user);
    map.put("msg", "This is a English");
    return map;
}
原文  http://liuyiyou.cn/2017/09/12/2017-09-12-SpringBoot-2/
正文到此结束
Loading...