SpringBoot學習筆記3-SpringBoot 下的Spring mvc

【Android免費音樂下載app】【佳語音樂下載】建議最少2.0.3版本。最新版本:
https://gitlab.com/gaopinqiang/checkversion/raw/master/Music_Download.apk

Spring boot下的Spring mvc 和之前的Spring mvc使用是完全一樣的:
1、@Controller
即爲Spring mvc的註解,處理http請求;

2、@RestController
Spring4後新增註解;是@Controller與@ResponseBody的組合註解;用於返回字符串或json數據;

示例:
創建一個MVCController

package com.springboot.web.controller;

import com.springboot.web.model.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController//相當於@Controller與@ResponseBody的組合,裏面所有的方法都返回的是json格式數據
public class MVCController {

	@RequestMapping("/getUser")
	public Object getUser(){//加了@RestController註解就不需要@ResponseBody了,直接返回Object
		User user = new User();
		user.setId(100);
		user.setName("qiang");
		return user;
	}

}

創建一個model包,裏面寫個User類存放數據

package com.springboot.web.model;

public class User {
	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

去瀏覽器中請求:http://localhost:8081/getUser
輸出結果:{“id”:100,“name”:“qiang”}
在這裏插入圖片描述

3、@GetMapping
RequestMapping 和 Get請求方法的組合;

示例:
MVCController中增加一個getUser1方法

    @GetMapping("/getUser1")//只支持get請求 @GetMapping 等價於 @RequestMapping(value = "/getUser1",method = RequestMethod.GET)
	public Object getUser1(){
		User user = new User();
		user.setId(101);
		user.setName("qiang1");
		return user;
	}

去瀏覽器中請求:http://localhost:8081/getUser1
輸出結果:{“id”:101,“name”:“qiang1”}
在這裏插入圖片描述

4、@PostMapping
RequestMapping 和 Post請求方法的組合;
如果是get請求就會不支持

示例:
MVCController中增加一個getUser2方法

    @PostMapping("/getUser2")//只支持get請求 @GetMapping 等價於 @RequestMapping(value = "/getUser2",method = RequestMethod.POST)
	public Object getUser2(){
		User user = new User();
		user.setId(102);
		user.setName("qiang2");
		return user;
	}

去瀏覽器中請求:http://localhost:8081/getUser2
輸出結果:會提示不支持get
在這裏插入圖片描述

5、@PutMapping
RequestMapping 和 Put請求方法的組合;
比較少使用

6、@DeleteMapping
RequestMapping 和 Delete請求方法的組合;
比較少使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章