Controller的使用

来源:互联网 发布:linux查看ftp用户权限 编辑:程序博客网 时间:2024/05/22 12:53

这里写图片描述
对于只使用@Controller注解控制器,必须配套有模板(如JSP),否则报404错误
而使用@RestController注解则不须配有模板

只使用@Controller注解

须添加模板,此处为如Spring官方的Thyemleaf模板(替代JSP的好东西),添加jar包
这里写图片描述

目录结构:

这里写图片描述

模板文件:index.heml

<h1>hello Spring Boot!</h1>

控制器类:

import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;/** * Created by Shusheng Shi on 2017/5/3. */@Controllerpublic class HelloController {    @RequestMapping(value = "/hello", method = RequestMethod.GET)    public String say() {        return "index";    }}

运行结果

这里写图片描述
现在流行前后端分离,后端只需要提供rest接口,返回一些json格式给前端,不需要模板,会影响性能

若将控制器类里的方法写成如下所示(即无method属性)

 @RequestMapping(value = "/hello")    public String say() {        return girlProperties.getCupSize();    }

那么使用GET/POST方式访问皆可.不过并不推荐如此写法,毕竟两种方法适合于不同需求

这里写图片描述

控制器方法

@RequestMapping(value = "/{id}/say", method = RequestMethod.GET)    public String say(@PathVariable("id") int id) {        return "id: " + id;    }

运行结果

这里写图片描述

控制器方法

@RequestMapping(value = "/say", method = RequestMethod.GET)    public String say(@RequestParam("id") int myId) {        return "id: " + myId;    }

运行结果

设置id默认值

@RequestMapping(value = "/say", method = RequestMethod.GET)public String say(@RequestParam(value = "id", required = false, defaultValue = "0") int myId) {        return "id: " + myId;    }

运行结果

这里写图片描述
另替代写法

//  @RequestMapping(value = "/say", method = RequestMethod.GET)    @GetMapping(value = "/say")
0 0
原创粉丝点击