@SpringBootApplication
Controller层
@Controller(返回的是页面)
@RestController(返回字符串)等于@Controller+@ResponseBody
@RequestMapping
不携带数据给前端,只是实现前端路由
@Controller//在Spring中注册,表示本类是一个控制器类
public class ViewController {
@RequestMapping("toview")//完整路径url http://localhost:8080/toview
public String view(){
return "test.html";//且本html静态文件存放在resource目录下的static目录下
}
}
#根据上面return的是一个具体的格式文件,由于我们后面可能用到的是其他的模板(不是html)这样就会使得需要修改大量文件
#所以我们采用配置文件的方式。在配置文件中指定文件格式,return的时候只return文件名就可以了
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
//然后控制层我们可以这样写
@Controller//在Spring中注册,表示本类是一个控制器类
public class ViewController {
@RequestMapping("toview")//完整路径url http://localhost:8080/toview
public String view(){
return "test";//且本html静态文件存放在resource目录下的static目录下
}
}
携带数据给前端页面—使用(freemarker模板引擎)
<!--将携带给前端的数据解析显示出来-->
<!--FreeMarker模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
#freeMarker
#后缀
spring.freemarker.suffix=.html
spring.freemarker.template-loader-path=classpath:/static/
@RequestMapping("bringdata")
public ModelAndView data(){
ModelAndView view = new ModelAndView("test");
view.addObject("str1","hello world");
view.addObject("str2","数据带来了");
return view;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<hr/>
<div>${str1}</div>
<hr/>
<div>${str2}</div>
</body>
</html>
携带数据给前端页面—使用(thymeleaf模板引擎)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.2</version>
</dependency>
spring.thymeleaf.check-template=false
spring.thymeleaf.check-template-location=false
@RequestMapping("bringdata")
public String data(Model model){
model.addAttribute("str1","hello world");
model.addAttribute("str2","数据带来了");
return "test";
}
<!--前端页面放在resources目录下的templates目录下-->
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<hr/>
<div th:text="${str1}"></div>
<hr/>
<div th:text="${str2}"></div>
</body>
</html>
@RequestParam
前端携带参数给后端(前端URL采用?的形式)
@Controller
public class ParamsController {
@RequestMapping("param")
public String toparam(@RequestParam("num") int num, Model model){
//可以不穿参数,给参数设置默认值为0。
//public String toparam(@RequestParam(value = "num",required = false,defaultValue = "0") int num, Model model){
//传入多参
//public String toparam(@RequestParam(value = "num",required = false,defaultValue = "0") int num,@RequestParam(value = "str",required = false,defaultValue = "") String str, Model model){
//if(str.equals("测试")){}//String最好要指定默认值,不然不传值为null那么条件判断会报错。
System.out.println("num = "+num);
model.addAttribute("num",num);
return "numpage";
}
}
<!--url: http://localhost:8080/param?num=1024-->
<!--numpage.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${num}"></div>
</body>
</html>
@PathVariable
@Controller
public class ParamsController {
@RequestMapping("path/{id}/{type}")
public String topath(@PathVariable(required = false) int id,
@PathVariable(required = false) String type,Model model){
System.out.println("id="+id);
System.out.println("type="+type);
model.addAttribute("id",id);
model.addAttribute("type",type);
return "restfull";
}
}
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${id}"></div>
<div th:text="${type}"></div>
</body>
</html>
@GetMapping(查询数据)
//与RestController配合,将获得的数据返回到浏览器(没有具体的页面)。
@RestController
@RequestMapping("rest")
public class RestFullController {
//查询数据没有参数,url没有指定二级目录,可以返回任意类型。
@GetMapping //http:localhost:8080/rest
public String test(){
return "test";
}
//查询数据没有参数,url指定二级目录,可以返回任意类型。
@GetMapping("get") //http:localhost:8080/rest/get
public String get(){
return "我是返回数据";
}
//查询数据没有参数,url指定二级目录,可以返回任意类型(返回对象)。
@GetMapping("/getuser")
public User getuser(){
User user = new User(1, "张山", "男", 18);
return user;
}
//查询数据携带参数,url指定二级目录,可以返回任意类型(返回对象)。
@GetMapping("{id}")
public User getuserbyid(@PathVariable("id") int id){
User user = new User(id, "李四", "女", 21);
return user;
}
}
@
public class User {
private int id;
private String name;
private String sex;
private int age;
}
@PostMapping(新增数据)
@RestController
@RequestMapping("rest")
public class RestFullController {
@GetMapping//http:localhost:8080/rest
public String getFindUser(@RequestBody int id){
User user = service.findeUserById(id);
return user;
}
//与get的请求url都一样但是方式不一样
@PostMapping//http:localhost:8080/rest
public User postAddUser (@RequestBody User user){
System.out.println(user);
return user;
}
}
@PutMapping(与上面原理一致)
@DeleteMapping(与上面原理一致)
@ResponseBody(@ResponseBody+@Controller==@RestController)
@Controller
@ResponseBody
public class TestController {
@GetMapping("controller")
public String testController(){
return "testController";
}
}
//与下面的一模一样,其实RestController注解与Controller注解唯一的区别就是RestController里面含有ResponseBody注解
@RestController
public class TestRestController {
@GetMapping("restcontroller")
public String testRestController(){
return "testRestController";
}
}
@RequestBody
//前端将一个对象封装成json的格式传到后端,后端用与之对应的实体类接受需要加上本注解
@RestController
@RequestMapping("rest")
public class RestFullController {
@PostMapping//http:localhost:8080/rest
public User postAddUser (@RequestBody User user){
System.out.println(user);
return user;
}
}
@CrossOrigin(解决跨域问题)(最好的解决跨域的方式是使用过滤器)
@RestController
@RequestMapping("rest")
public class RestFullController {
@PostMapping//http:localhost:8080/rest
@CrossOrigin
public User postAddUser (@RequestBody User user){
System.out.println(user);
return user;
}
}
Service层
在讲下面之前先看一下几个例子
//service层的接口
public interface UserService {
public User get();
public User getUserById(int id);
}
//service层的实现类
public class UserServiceImpl implements UserService{
@Override
public User get() {
User user = new User(1, "张山", "男", 18);
System.out.println("UserServiceImpl"+user);
return user;
}
@Override
public User getUserById(@PathVariable("id") int id) {
User user = new User(id, "李四", "女", 24);
System.out.println("getUserById:"+user);
return user;
}
}
//controller层
@RestController
@RequestMapping("/action")
public class UserActionController {
private UserService userService;
@GetMapping
public User get(){
userService = new UserServiceImpl();
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
userService = new UserServiceImpl();
User userById = userService.getUserById(id);
return userById;
}
}
我们可以发现一个问题,在controller层调用service层的时候,我们在controller层使用了一个关于service层的全局变量,然后再在具体的方法里面重新赋值。当然我们也可以在全局变量的位置写全,如 private UserServiceImpl userService = new UserServiceImpl();
但是这些方法都不是很好,我们可以使用@Service注解在Service实现层里面,将本类在Spring中注册bean,然后在Controller层全局变量的地方使用@Autowrired注解将获取注册的bean。如下所示
@Service(bean的注册)+@Autowired(获取bean)
//service层的实现类
@Service
public class UserServiceImpl implements UserService{
@Override
public User get() {
User user = new User(1, "张山", "男", 18);
System.out.println("UserServiceImpl"+user);
return user;
}
@Override
public User getUserById(@PathVariable("id") int id) {
User user = new User(id, "李四", "女", 24);
System.out.println("getUserById:"+user);
return user;
}
}
//controller层
@RestController
@RequestMapping("/action")
public class UserActionController {
@Autowired
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = userService.getUserById(id);
return userById;
}
}
@Component(bean的注册)(与@Service @Controller @Repository)都是一样的,主要的作用是视觉上区分各层。而@Component表示组件,可能在任意层被调用。
@Autowired(获取bean)
@Resource(获取bean)
//如果service层有多个实现类实现一个接口(这就是我们为什么我们在Controller层使用多态的形式,很方便转换我们service层的实现)
//接口
public interface UserService {
public User get();
public User getUserById(int id);
}
//接口实现1
@Service
public class UserServiceImpl implements UserService{
@Override
public User get() {
User user = new User(1, "张山", "男", 18);
System.out.println("UserServiceImpl---get:"+user);
return user;
}
@Override
public User getUserById(@PathVariable("id") int id) {
User user = new User(id, "李四", "女", 24);
System.out.println("UserServiceImpl---getUserById:"+user);
return user;
}
}
//接口实现2
@Service
public class LoginServiceImpl implements UserService{
@Override
public User get() {
User user = new User(1, "张山", "男", 18);
System.out.println("LoginServiceImpl---get:"+user);
return user;
}
@Override
public User getUserById(@PathVariable("id") int id) {
User user = new User(id, "李四", "女", 24);
System.out.println("LoginServiceImpl---getUserById:"+user);
return user;
}
}
//那么问题来了,我Controller层如何去判断我现在想用哪一个service实现
//在目前情况(俩个实现类实现一个接口的情况下),使用@Autowired注解会在编译前直接报错。
@RestController
@RequestMapping("/action")
public class UserActionController {
@Autowired
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = userService.getUserById(id);
return userById;
}
}
//在目前情况(俩个实现类实现一个接口的情况下),使用@Resource注解会在编译时报错。
@RestController
@RequestMapping("/action")
public class UserActionController {
@Resource
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = userService.getUserById(id);
return userById;
}
}
//在目前情况(俩个实现类实现一个接口的情况下),正确方法。
@RestController
@RequestMapping("/action")
public class UserActionController {
@Resource(name="loginServiceImpl")//指定具体哪个类,并且类的首字母小写
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = userService.getUserById(id);
return userById;
}
}
//还可以同时写多个
@RestController
@RequestMapping("/action")
public class UserActionController {
// 1
@Resource(name = "loginServiceImpl")
private UserService loginService;
// 2
@Resource(name = "userServiceImpl")
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = loginService.getUserById(id);
return userById;
}
}
@Autowired+@Qualifier(获取bean)
//如果一个接口有多个实现类,并且非要想使用@Autowired注解,那么可以配合@Qualifier注解使用
@RestController
@RequestMapping("/action")
public class UserActionController {
// @Resource(name = "loginServiceImpl")
@Autowired
@Qualifier("loginServiceImpl")
private UserService loginService;
@Resource(name = "userServiceImpl")
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = loginService.getUserById(id);
return userById;
}
}
@Configuration+@Bean(bean的注册)(人为)
//如果Service层不用@Service注解注册Service层的bean,我们可以创建一个配置类进行手动配置
//接口
public interface UserService {
public User get();
public User getUserById(int id);
}
//实现类1
public class LoginServiceImpl implements UserService{
@Override
public User get() {
User user = new User(1, "张山", "男", 18);
System.out.println("LoginServiceImpl---get:"+user);
return user;
}
@Override
public User getUserById(@PathVariable("id") int id) {
User user = new User(id, "李四", "女", 24);
System.out.println("LoginServiceImpl---getUserById:"+user);
return user;
}
}
//实现类2
public class UserServiceImpl implements UserService{
@Override
public User get() {
User user = new User(1, "张山", "男", 18);
System.out.println("UserServiceImpl---get:"+user);
return user;
}
@Override
public User getUserById(@PathVariable("id") int id) {
User user = new User(id, "李四", "女", 24);
System.out.println("UserServiceImpl---getUserById:"+user);
return user;
}
}
//手动配置
@Configuration
public class MyBeans {
@Bean
public UserService loginServiceImpl(){
return new LoginServiceImpl();
}
@Bean
public UserService userServiceImpl(){
return new UserServiceImpl();
}
}
@RestController
@RequestMapping("/action")
public class UserActionController {
// @Resource(name = "loginServiceImpl")
@Autowired
@Qualifier("loginServiceImpl")
private UserService loginService;
@Resource(name = "userServiceImpl")
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = loginService.getUserById(id);
return userById;
}
}
//如果想换名字
//方法一
//手动配置
@Configuration
public class MyBeans {
@Bean
public UserService login(){
return new LoginServiceImpl();
}
@Bean
public UserService userServiceImpl(){
return new UserServiceImpl();
}
}
@RestController
@RequestMapping("/action")
public class UserActionController {
// @Resource(name = "loginServiceImpl")
@Autowired
@Qualifier("login")
private UserService loginService;
@Resource(name = "userServiceImpl")
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = loginService.getUserById(id);
return userById;
}
}
//方法二
//手动配置
@Configuration
public class MyBeans {
@Bean(name="loginAdmin")
public UserService login(){
return new LoginServiceImpl();
}
@Bean
public UserService userServiceImpl(){
return new UserServiceImpl();
}
}
@RestController
@RequestMapping("/action")
public class UserActionController {
// @Resource(name = "loginServiceImpl")
@Autowired
@Qualifier("loginAdmin")
private UserService loginService;
@Resource(name = "userServiceImpl")
private UserService userService;
@GetMapping
public User get(){
User user = userService.get();
return user;
}
@GetMapping("{id}")
public User getUserById(@PathVariable("id") int id){
User userById = loginService.getUserById(id);
return userById;
}
}
@Values
view.page=view
local.username=wwy
local.password=123456
@RestController
@RequestMapping("/action")
public class UserActionController {
@Value("${view.page}")
private String page;
@Value("${local.username}")
private String username;
@Value("${local.password}")
private String password;
@GetMapping("val")
public String getValue(){
return "page="+page+" , username="+username+" , password="+password;
}
}