spring boot MVC

1 spring boot的用途

第一,spring boot可以用来开发mvc web应用。

第二,spring boot可以用来开发rest api。

第三,spring boot也可以用来开发web app。

2 @Controller和@RestController注解

要返回jsp用@Controller注解,要返回json用@RestController注解。

3 spring boot返回jsp页面

3.1 配置

在src/main/resources下面新建application.properties文件,设置

spring.mvc.view.prefix:/index/     //告诉springboot去哪里取jsp,即前缀。

spring.mvc.view.suffix: .jsp            //告诉springboot返回的文件的类型,这里是.jsp

3.2 控制器用@Controller

    @Controller

    public class UserController {

        @RequestMapping("/index")

        return "user";

    }

   这里返回的"user"其实是告诉spring boot去/index下面找user.jsp返回。

4 springboot controller注解

4.1 @Controller

返回jsp页面。

4.2 @RestController

返回json。

4.3 @RequestMapping

配置url映射。

4.4@RequestParam

获取请求参数。

5 在controller中给jsp数据的方式

5.1 交数据的两种方式

第一,由controller函数的形参传入的对象提交数据,这个时候参数的类型可以是Map<String, Object>、Model和ModelMap。

@RequestMapping("/index")

public String index(Map<String, Object> map) {

    map.put("name", "chao");

    return "index";

}

@RequestMapping("/index")

public String index(Model model) {

    model.addAttribute("name", "chao");

    return "index";

}

@RequestMapping("/index")

public String index(ModelMap map) {

    map.addAttribute("name", "chao");

    return "index";

}

第二,由controller函数的返回值对象体检数据,这个时候只能是ModelAndView。

@RequestMapping("/index")

public ModelAndView index() {

    ModelAndView modelAndView = new ModelAndView("/index"); //这里“ /index”指定了返回的view为index.jsp

    modelAndView.addObject("name", "chao");

    return modelAndView;

}

 
原文地址:https://www.cnblogs.com/hustdc/p/8919833.html