定義UserService接口,用UserServiceImpl實(shí)現(xiàn)該接口饶套,覆寫(xiě)deleteUser方法漩蟆,并且在HttpTestController調(diào)用此方法,實(shí)現(xiàn)delete請(qǐng)求的參數(shù)傳遞。
1 get請(qǐng)求方式
@RequestMapping(value = "/map.json", method = {RequestMethod.GET,})
@ResponseBody
public Map map(){
Map map = new HashMap();
map.put("name","cbhengboying");
map.put("sex","man");
map.put("age",22);
List list = new ArrayList();
list.add("red");
list.add("black");
list.add("blue");
list.add("yellow");
map.put("colors",list);
return map;
}
效果圖:
2 post請(qǐng)求方式
@RequestMapping(value = "post",method = RequestMethod.POST)
@ResponseBody
public User post( @RequestBody User user){
return user;
}
效果圖:
3 put請(qǐng)求方式
@RequestMapping(value = "put",method = RequestMethod.PUT)
@ResponseBody
public User put( @RequestBody User user){
return user;
}
效果圖:
4 delete請(qǐng)求方式
@RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable("id") Long id) throws Exception{
String result = userService.deleteUser(id);
System.out.println(result + "service");
return "刪除了"+ id;
}
效果圖:
以下是user的相關(guān)實(shí)體
public class User {
private Long id;
private String name;
private Integer age;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
}
注:常用到的注解
@RequestMapping:提供路由信息妓蛮,負(fù)責(zé)URL到Controller中的具體函數(shù)的映射怠李。
@Service:用于標(biāo)注業(yè)務(wù)層組件。
@RestController:用于標(biāo)注控制層組件(如struts中的action)蛤克,包含 @Controller和@ResponseBody捺癞。
@AutoWired:byType方式。把配置好的Bean拿來(lái)用构挤,完成屬性髓介、方法的組裝,它可以對(duì)類成員變量筋现、方法及構(gòu)造函數(shù)進(jìn)行標(biāo)注唐础,完成自動(dòng)裝配的工作。當(dāng)加上(required=false)時(shí)矾飞,就算找不到bean也不報(bào)錯(cuò)一膨。
@RequestBody: i) 該注解用于讀取Request請(qǐng)求的body部分?jǐn)?shù)據(jù),使用系統(tǒng)默認(rèn)配置的HttpMessageConverter進(jìn)行解析洒沦,然后把相應(yīng)的數(shù)據(jù)綁定到要返回的對(duì)象上豹绪; ii) 再把HttpMessageConverter返回的對(duì)象數(shù)據(jù)綁定到 controller中方法的參數(shù)上。
@ResponseBody:該注解用于將Controller的方法返回的對(duì)象申眼,通過(guò)適當(dāng)?shù)腍ttpMessageConverter轉(zhuǎn)換為指定格式后瞒津,寫(xiě)入到Response對(duì)象的body數(shù)據(jù)區(qū)。
@PathVariable:當(dāng)使用@RequestMapping URI template 樣式映射時(shí)括尸, 即 someUrl/{paramId}, 這時(shí)的paramId可通過(guò) @Pathvariable注解綁定它傳過(guò)來(lái)的值到方法的參數(shù)上巷蚪。