[技術博客] Springboot的Controller類使用

Springboot的Controller類使用

@Controller:處理http請求。
代碼:spring

@Controller
public class QuestionController {
......
}

@AutoWired:byType方式。把配置好的Bean拿來用,完成屬性、方法的組裝,它能夠對類成員變量、方法及構造函數進行標註,完成自動裝配的工做。當加上(required=false)時,就算找不到bean也不報錯。
代碼:數據庫

@Autowired
private QuestionMapper questionMapper;

@GetMapping:是一個組合註解,是@RequestMapping(method = RequestMethod.GET)的縮寫,用於將HTTP GET請求映射到特定處理程序方法的註釋。
代碼:springboot

@GetMapping("/question")
public String getQuestion(Model model) {
......
model.addAttribute("questionList", questionList);
......
return "questionAll";
}

以上代碼響應到頁面questionAll(能夠直接使用Model封裝內容,直接返回頁面字符串)app

@PostMapping:是一個組合註解,是@RequestMapping(method = RequestMethod.POST)的縮寫,用於將HTTP POST請求映射到特定處理程序方法的註釋。
代碼:框架

@PostMapping("/comment")
public String insertComment(@RequestParam(name = "comment") String  comment, @RequestParam(name = "id") int id , Model model) {
......
return "questionDetail";
}

@RequestMapping:對於並未用到的@RequestMapping(method=RequestMethod.),由以上可知,@RequestMapping能夠直接替代以上@GetMapping和@PostMapping兩個註解,可是,以上兩個註解並不能替代@RequestMapping,@RequestMapping至關於以上兩個註解的父類。函數

@RequestParam:獲取請求參數的值。在SpringMVC框架中,能夠經過定義@RequestMapping來處理URL請求。和@PathVariable同樣,在處理URL的函數中,去獲取URL中的參數。經過註解@RequestParam能夠輕鬆的將URL中的參數綁定處處理函數方法的變量中。
語法:@RequestParam(value=」參數名」,required=」true/false」,defaultValue=」」)value:參數名;required:是否包含該參數,默認爲true,表示該請求路徑中必須包含該參數,若是不包含就報錯;defaultValue:默認參數值,若是設置了該值,required=true將失效,自動爲false,若是沒有傳該參數,就使用默認值。
代碼:ui

@GetMapping("/questionDetail")
public String getQuestionDetail(@RequestParam(name = "id") int id, Model    model) {
}

代碼將Request參數名爲"id"的值綁定到了處理函數的參數id上。code

Springboot的Mapper類使用

@Mapper:這個用於數據庫,須要掃描到對應的註解文件。
代碼:對象

@Mapper
public interface QuestionMapper {
}

@Select 是查詢類的註解,全部的查詢均使用這個
@Result 修飾返回的結果集,關聯實體類屬性和數據庫字段一一對應,若是實體類屬性和數據庫屬性名保持一致,就不須要這個屬性來修飾。
@Insert 插入數據庫使用,直接傳入實體類會自動解析屬性到對應的值
@Update 負責修改,也能夠直接傳入對象
@Delete 負責刪除
代碼:字符串

@Select("select * from questions where id = #{id}")
Question findById(int id);

@Select("select * from questions")
List<Question> findAll();
相關文章
相關標籤/搜索