spring 构建api

2020-03-17  本文已影响0人  BestFei

一、Get请求
uri:/{country}/details?appName=xxx&tagName=xxxx

    @RequestMapping(value = "/{country}/details",method = RequestMethod.GET)
    public Response queryAppTag(@PathVariable("country")String country),
                                    @RequestParam(name = "appName") String appName,
                                    @RequestParam(name = "tagName") String tagName) {
        Response response = new Response();
        try {
            ...
            return response;
        }
        catch (Exception e){
            log.error(e.getMessage());
            response.setMsg(e.getMessage());
            response.setErrorCode(ErrorEnum.SystemError.getErrorCode());
            return response;
        }
    }

二、Post请求
psot带path的参数,json请求报文

    @RequestMapping(value = "/{country}/del",method = RequestMethod.POST)
    public Response delAppTag(@PathVariable("country")String country,
@RequestBody appDetailRequest appDetailRequest){
        Response response = new Response();
        try {
            ...
            return response;
        }
        catch (Exception e){
            log.error(e.getMessage());
            response.setMsg(e.getMessage());
            response.setErrorCode(ErrorEnum.SystemError.getErrorCode());
            return response;
        }
    }

三、带分页功能的api

    @RequestMapping(value = "/list/{country}", method = RequestMethod.GET)
    public ResponseCountryDetails<CountryDetail> queryAllByNation(
            @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @RequestParam(value = "pagesize", required = false, defaultValue = "5") int pageSize,
            @PathVariable String country) {
        List<CountryDetail> result = countryService.queryListByNation(country, page, pageSize);
        ResponseCountryDetails<CountryDetail> response = new ResponseCountryDetails<CountryDetail>(result);
        return response;
    }
import com.github.pagehelper.PageHelper;

    public List<CountryDetail> queryListByNation(String country, int page, int pageSize) {
        List<CountryDetail> result = null;
        try {
            // 调用pagehelper分页,采用starPage方式。starPage应放在Mapper查询函数之前
            PageHelper.startPage(page, pageSize); //每页的大小为pageSize,查询第page页的结果
            PageHelper.orderBy("count DESC "); //进行分页结果的排序
            result = this.countryDao.queryAllByNation(country);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
public interface CountryDao {
    @Select({
            " select " +
                    "          ...字段名 ,count(*) as count " +
                    "        from dbname.tablename " +
                    "        where  nation = #{country} " +
                    "        group by  字段名"
    })
    List<CountryDetail> queryAllByNation(@Param("country") String country);
}
上一篇下一篇

猜你喜欢

热点阅读