新建一个Controller类:
Controller的写法有两种:
1.@Controller+@RequestMapping+@ResponseBody方式:
@Controller
public class TestController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
@ResponseBody
public String hello() {
return "Hello World!";
}
}
2.@RestController+@GetMapping(PostMapping、PutMapping...)方式:
@RestController
public class TestController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
运行项目,在地址栏输入:http://localhost:8080/hello
得到结果:
可以每种方式都试一遍!
然后我们创建success.html文件,再来说他们的区别:
首先用第一种方式,添加success()方法:
@Controller
public class TestController {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
@ResponseBody
public String hello() {
return "Hello World!";
}
@RequestMapping(value = "/success",method = RequestMethod.GET)
public String success() {
return "success";
}
}
浏览器访问:http://localhost:8080/success
报错,控制台信息:
javax.servlet.ServletException: Circular view path [success]: would dispatch back to the current handler URL [/success] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
意思就是无法识别方法中返回的success,此时我们需要引入thymeleaf模板引擎,在pom.xml中引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
重启,再次打开http://localhost:8080/success:
成功进入success.html!
关于thymeleaf作用,大家应该很容易猜到,不明白的可以去看下他的文档,很简单,springboot中常用,使用方法类似于Vue的v-xxx指令,或者微信小程序的wx:xxx指令,简单使用方法:
<html xmlns:th="http://www.thymeleaf.org">
<span th:text="${param.id}"></span>
我们在访问http://xxx?id=xxx时,就可以直接在通过上面的代码获取到id!
言归正传,继续说说Controller两种写法的区别:
如果使用 @Controller,那就必须指明方法中返回数据类型,如@ResponseBody,表明返回的是具体的数据如字符串,json等(如果我们直接返回一个对象,SpringBoot会自动为我们转成json格式),如上面的hello方法:
@RequestMapping(value = "/hello",method = RequestMethod.GET)
@ResponseBody
public String hello() {
return "Hello World!";
}
如果不指明,则代表返回的是一个网页路径,如上面的success方法:
@RequestMapping(value = "/success",method = RequestMethod.GET)
public String success() {
return "success";
}
我们可以按着Ctrl鼠标点击return的"success",会直接跳转到对应的success.html界面!
所以@Controller既可以返回指定数据格式数据,也可以返回具体网页路径! 而 @RestController则只能返回json等固定数据格式数据,不能再返回html,jsp页面等,因为它是@Controller+@ResponseBody的组合(可以点击@RestController注解进入内部查看),所以我们在为前端写接口时,就经常使用@RestController了!
我们在实际开发过程中,经常会划分业务模块,因为在书写Controller时,往往会为Controller里的所有方法定义一个父级RequestMapping来区分业务模块:
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
浏览器访问:http://localhost:8080/test/hello
安卓或前端同学会深有感触了!
另外,我们往往也会为项目声明一个总的路径名,如:
server.servlet.context-path=/byl
那么此时,在访问时就需要加上该路径:http://localhost:8080/byl/test/hello