spring 构建api

一、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 queryAllByNation(
            @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @RequestParam(value = "pagesize", required = false, defaultValue = "5") int pageSize,
            @PathVariable String country) {
        List result = countryService.queryListByNation(country, page, pageSize);
        ResponseCountryDetails response = new ResponseCountryDetails(result);
        return response;
    }
import com.github.pagehelper.PageHelper;

    public List queryListByNation(String country, int page, int pageSize) {
        List 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 queryAllByNation(@Param("country") String country);
}

你可能感兴趣的:(spring 构建api)