简体   繁体   English

Spring MVC Rest-URL上的多个参数

[英]Spring MVC Rest - multiple parameters at URL

I have "transit manager" application. 我有“运输经理”应用程序。 It's a simply app to test how to use Spring framework. 它是一个简单的应用程序,用于测试如何使用Spring框架。 I've created endpoint for adding new transit to database (Spring Data) and it works fine. 我已经创建了用于向数据库(Spring Data)添加新传输的终结点,并且工作正常。 I have added a few transits and now I want to get daily report and here I have problems. 我添加了一些公交,现在我想获取每日报告,在这里我遇到了问题。 This is how endpoint should looks like: 这是端点的外观:

GET http://example.com/reports/daily?start_date=YYYY-MM-DD&end_date=YYYY-MM_DD

And response(in JSON) for example: 和响应(JSON)例如:

{
  "total_distance": "90",
  "total_price":      "115"
}

What I suppose to do? 我该怎么办? Should I add new fields "startDate" and "endDate" in model class? 我应该在模型类中添加新字段“ startDate”和“ endDate”吗?

This is how my model class looks: 这是我的模型类的外观:

@Entity
public class Transit {

public Transit() {
}

@Column(name = "id")
@Id
@GeneratedValue
private Long id;
@NotEmpty
private String sourceAddress;
@NotEmpty
private String destinationAddress;
private double price;
private DateTime date;
private Long distance;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getSourceAddress() {
    return sourceAddress;
}

public void setSourceAddress(String sourceAddress) {
    this.sourceAddress = sourceAddress;
}

public String getDestinationAddress() {
    return destinationAddress;
}

public void setDestinationAddress(String destinationAddress) {
    this.destinationAddress = destinationAddress;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public DateTime getDate() {
    return date;
}

public void setDate(DateTime date) {
    this.date = date;
}


public Long getDistance() {
    return distance;
}

public void setDistance(Long distance) {
    this.distance = distance;
}}

Repository class: 存储库类:

public interface TransitRepository extends JpaRepository<Transit, Long> {
List<Transit> findAllByStartDateGreaterThanEqualAndEndDateLessThanEqual(DateTime startDate, DateTime endDate);
}

Controller class: 控制器类:

@RestController
@RequestMapping("/transit")
public class TransitController {
private TransitService transitService;

@Autowired
public void setTransitService(TransitService transitService) {
    this.transitService = transitService;
}


@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void addTransit(@RequestBody Transit transit){
    transitService.calculateDistance(transit);
    transitService.addTransit(transit);
    System.out.println(transit);
}

@RequestMapping(path = "reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
    public void getDailyReport(){}

}

And service class: 和服务等级:

@Service
public class TransitService {

private TransitRepository transitRepository;
public static final String API_KEY = "xxxxxx";

@Autowired
public void setTransitRepository(TransitRepository transitRepository) {
    this.transitRepository = transitRepository;
}

public void addTransit(Transit transit) {
    transitRepository.save(transit);
}

public void calculateDistance(Transit transit) {

    GeoApiContext geoApiContext = new GeoApiContext.Builder().apiKey(API_KEY).build();
    DistanceMatrixApiRequest request = DistanceMatrixApi.newRequest(geoApiContext);

    DistanceMatrix result = request.origins(transit.getSourceAddress())
            .destinations(transit.getDestinationAddress())
            .mode(TravelMode.DRIVING)
            .units(Unit.METRIC)
            .awaitIgnoreError();

    long distance = result.rows[0].elements[0].distance.inMeters;
    transit.setDistance(distance);

}

public void countDaily(List<Transit> transitList){

}
}

You should use the annotaion @RequestParam on the parameters you need to add to your method. 您应该在需要添加到方法中的参数上使用注释@RequestParam The name in the annotaion is optional and defaults to the parameter name. 注释中的名称是可选的,默认为参数名称。

@RequestMapping(path = "reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
public void getDailyReport(@RequestParam("start_date") String startDate, @RequestParam String end_date){}

}

Adding the fields to your Transit class would not work as the GET-Request has no request body and the parameters are not in the body anyway. 将字段添加到您的Transit类中将不起作用,因为GET-Request没有请求正文,并且参数也始终不在正文中。

You should use @RequestParam annotation in your controller method. 您应该在控制器方法中使用@RequestParam批注。

@RequestMapping(path = "reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
public void getDailyReport(@RequestParam("start_date") String startDate, @RequestParam("end_date") String endDate){

     // Create a method in service class, that takes startDate and endDate as parameters.

     // And inside that method, you can write a SQL query to find the distance & price for the given date parameters

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM