3.2 KiB
3.2 KiB
SpringMVC笔记
访问控制
请求地址时返回对应的网页文件
@RestController
用于返回对象格式的内容,在后面会使用ModelAndView
可以返回网页文件@Controller
用于返回网页文件
环境要求
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
</dependency>
错误页面设置
在这个路径下可以配置错误码要访问的页面,也就是可以自定义页面内容
使用@Controller
返回需要访问的HTML内容页面,最后返回的字符串就是页面,这个页面位于templates
目录下
@RequestMapping("/use")
@Controller
public class UseController {
// 带参数访问
@RequestMapping(value = "hello", method = RequestMethod.GET, params = {"name"})
public String hello() {
return "hello";
}
@GetMapping("jumpPage")
public String jumpPage() {
return "jumpPage";
}
@GetMapping("index")
public String quick() {
return "user";
}
// 跳转的页面
@GetMapping("toJump")
public String toJump() {
return "redirect:jumpPage";
}
}
如果在使用@Controller
需要返回JSON内容,需要在控制器方法上加上@ResponseBody
@GetMapping("getJson")
@ResponseBody
public List<String> getJson() {
ArrayList<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
return list;
}
使用@RestController
如果使用@RestController
那么返回的就是JSON对象,但是这时候要想返回网页文件,需要使用ModelAndView
@RequestMapping("userRest")
@RestController
public class UseRestController {
@GetMapping("page/test")
public ModelAndView test() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("page/test");
modelAndView.addObject("message", "这是消息内容");
return modelAndView;
}
}
我们引入了thymeleaf
所以有以下内容<h4 th:text="'消息:'+ ${message}"></h4>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用RestController返回页面信息</title>
</head>
<body>
<h3>使用RestController返回页面信息</h3>
<h4 th:text="'消息:'+ ${message}"></h4>
</body>
</html>