Get方式传参,是典型的URL传参方式,在URL后面加上变量和所要传递的值即可,这种方式比较简单,下面以示例的形式展示其使用方法
URL:
http://localhost:8080/favccxx/rs/findInspectJobByJobId?jobId=525b8818d52cc6f835bb9e41
Java源代码:
@GET
@Path("/findInspectJobByJobId")
@Produces({ MediaType.TEXT_XML })
public String findInspectJobByJobId(@QueryParam("jobId") String jobId,
@Context HttpServletRequest request) {
InspectJob inspectJob = inspectJobService.findOne("jobId", jobId);
return JsonUtil.toJson(inspectJob);
}
将URL最后的位置当做变量去处理,如下所示的000,既是URL的地址,也是需要传递的参数。
URL:
http://localhost:8080/favccxx/rs/getInspectJobByJobId/000
Java源代码:
@POST
@Path("/getInspectJobByJobId/{jobId}")
@Produces({ MediaType.TEXT_XML })
public String getInspectJobByJobId(@PathParam("jobId") String jobId,
@Context HttpServletRequest request) {
InspectJob inspectJob = inspectJobService.findOne("jobId", jobId);
return JsonUtil.toJson(inspectJob);
}
一直误认为Json向java端传递参数,就是使用Json的格式传递的,其实并不是,默认情况下,Json向后端传递参数仍然是使用=、&连接符传递参数的。示例代码如下:
URL:
http://localhost:8080/favccxx/rs/queryInspectJobById
参数:
jobId=123456&jobName=A任务
Java源代码:
@POST
@Path("/queryInspectJobById")
@Produces({ MediaType.APPLICATION_JSON })
public String queryInspectJobById(@FormParam("jobId") String jobId,
@FormParam("jobName") String jobName, @Context HttpServletRequest request) {
System.out.println("jobId:"+ jobId + ",AndjobName is:" + jobName) ;
InspectJob inspectJob = inspectJobService.findOne("jobId", jobId);
return JsonUtil.toJson(inspectJob);
}
使用此类方式传递参数时,Json格式数据中的变量,必须是Pojo类中的参数,这样可灵活传递参数,后端根据实际需要解析此参数,进行业务处理。
URL:
http://localhost:8080/favccxx/rs/queryInspectJobByJobId
参数:
{
"jobId" : "123456",
"jobName" : "A任务"
}
Java源代码:
@POST
@Path("/queryInspectJobByJobId")
@Produces({ MediaType.APPLICATION_JSON })
public String queryInspectJobByJobId(@RequestBody String body,
@Context HttpServletRequest request) {
InspectJob inspectJobReq = JsonUtil.fromJson(body, InspectJob.class);
InspectJob inspectJob = inspectJobService.findOne("jobId", inspectJobReq.getJobId());
return JsonUtil.toJson(inspectJob);
}
前端传参格式不变,后端封装一个QueryMap类,用来查询进行分页相关的数据。
URL:
http://localhost:8080/favccxx/rs/pageQueryJob
参数:
{
"pageIndex" : 2,
"queryMap" : {
"jobId" :"525b8818d52cc6f835bb9e41"
}
}
Java源代码:
@POST
@Path("/pageQueryJob")
@Produces({ MediaType.APPLICATION_JSON })
public String pageQueryJob(@RequestBody String body,
@Context HttpServletRequest request){
PageQuery pageQuery= JsonUtil.fromJson(body,PageQuery.class);
String jobId = pageQuery.getQueryMapByKey("jobId").toString();
return null;
}