Controller层常用注解:
@(我的第一个笔记本)[注解]
- @RestController 相当于“@Controller,@Controller 和@ResponseBody”的作用,在类开头上注明,作用是返回类中所有@RequestMapping(“”) 方法 的结果。
- @Autowired 和@Resource 都是注入bean,区别有待研究
- @GetMapping(“/{id}”) 的作用是获得Get请求,相当于@RequestMapping(method = RequestMethod.GET),可用于查询记录。
- @PostMapping(“/add”) 的作用是获得POST请求,相当@RequestMapping(method = RequestMethod.POST)., 可用于往数据表中添加记录。
- Restful 风格
- @RequestMapping(params=”tohello”) ,此处”tohello”是参数,在浏览器中访问时要在”?”后面添加参数名。如:http://localhost:8080/project/hello?tohello
//单个URL
@GetMapping(value = {"/list/{deviceTypeId}","/list"})
public BaseBody getAll(@PathVariable(value = "deviceTypeId",required = false) Long deviceTypeId) throws Exception {
}
//多个URL之间用逗号隔开,表示URL可选择参数
@GetMapping(value = {"/{deviceTypeId}/{dataUnitId}","/{deviceTypeId}"})
public BaseBody getByDeviceTypeIdAndDataUnitId(@PathVariable("deviceTypeId") Long deviceTypeId,
@PathVariable(value = "dataUnitId",required = false) Long dataUnitId){
}
//
**此代表deviceTypeID是与前台绑定的,可以有多个绑定数据,之间用逗号隔开, “required = false” 代表绑定的值可以为空,默认是true。 **
@RestController
@RequestMapping("/data-unit")
public class DataUnitController {
@Autowired
DataUnitService dataUnitService;
@PostMapping("/add")
public BaseBody add(@RequestBody DataUnitAddRB dataUnitAddRB) throws Exception {
BaseBody baseBody = new BaseBody();
Long dataUnitId = dataUnitService.add(dataUnitAddRB.getDataType(),dataUnitAddRB.getDescription(),
dataUnitAddRB.getOperation());
return baseBody.successResponse("创建成功",dataUnitId);
}
@GetMapping("/{id}")
public BaseBody getById(@PathVariable("id") Long id) throws Exception {
DataUnitDO dataUnitDO = dataUnitService.findById(id);
BaseBody responseBody = new BaseBody();
return responseBody.successResponse("查询成功",dataUnitDO);
}
@GetMapping(value = {"/list/{deviceTypeId}","/list"})
public BaseBody getAll(@PathVariable(value = "deviceTypeId",required = false) Long deviceTypeId) throws Exception {
List<DataUnitDO> dataUnitDOList;
if(deviceTypeId == null){
dataUnitDOList = dataUnitService.findAll();
}else{
dataUnitDOList = dataUnitService.findByDeviceId(deviceTypeId);
}
BaseBody responseBody = new BaseBody();
return responseBody.successResponse("查询成功",dataUnitDOList);
}
/**
* 设备心跳接口
* @param key
*/
@RequestMapping("/heart/{key}")
public void keepAlive(@PathVariable("key") String key){
deviceService.heartBeatReceived(key);
}
//序号6的例子:
浏览器访问:http://localhost:8080/jeewx/hello.do?toHello
@RequestMapping(params = "toHello")
public ModelAndView toHello(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String openid = (String) request.getSession().getAttribute("openid");
System.out.println("openid 的值是:"+ openid);
return new ModelAndView("wechat/hello");
}
}