I'm creating an endpoint with path variable and request params. How do I combine both path variable and request params into a single object? I'm using springboot 2 with java 8
@RequestMapping(path = "/schedules")
public class SchedulesController {
@GetMapping("/{area}/{subarea}")
public MyObject getFlight(@PathVariable("area") String area, @PathVariable("subarea") String subarea,
MyModel model) {
...
return new MyObject();
}
}
@Data
public class MyModel {
LocalDate datestamp,
String leadName,
String viceLeadName
}
I've looked at the spring documentation and I can't seems to find how to combine PathVariable into MyModel.
Here is my controller without the object.
@RequestMapping(path = "/schedules")
public class SchedulesController {
@GetMapping("/{area}/{subarea}")
public MyObject getFlight(@PathVariable("area") String area, @PathVariable("subarea") String subarea,
@RequestParam(value = "datestamp", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate datestamp,
@RequestParam(value = "leadName", required = false) String leadName,
@RequestParam(value = "viceLeadName", required = false) String viceLeadName) {
...
return new MyObject();
}
}
Is it possible to do the following? Where the path variables and request params are in MyModel object?
@RequestMapping(path = "/schedules")
public class SchedulesController {
@GetMapping("/{area}/{subarea}")
public MyObject getFlight(MyModel model) {
...
return new MyObject();
}
}
@Data
public class MyModel {
String area,
String subArea,
LocalDate datestamp,
String leadName,
String viceLeadName
}
Create a Model MyModel
class MyModel {
String area;
String subarea;
@DateTimeFormat(pattern = "yyyy-MM-dd")
LocalDate datestamp;
String leadname;
String viceleadname;
@Override
public String toString() {
return "MyModel [area=" + area + ", subarea=" + subarea + ", datestamp=" + datestamp + ", leadname=" + leadname
+ ", viceneadname=" + viceleadname + "]";
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSubarea() {
return subarea;
}
public void setSubarea(String subarea) {
this.subarea = subarea;
}
public LocalDate getDatestamp() {
return datestamp;
}
public void setDatestamp(LocalDate datestamp) {
this.datestamp = datestamp;
}
public String getLeadname() {
return leadname;
}
public void setLeadname(String leadname) {
this.leadname = leadname;
}
public String getViceneadname() {
return viceleadname;
}
public void setViceneadname(String viceleadname) {
this.viceleadname = viceleadname;
}
And the Request mapping will be same as you mentioned.
@GetMapping("/{area}/{subarea}")
public String getFlight(MyModel model) {
System.out.println(model);
return "success";
}
And the Request look like this:
http://localhost:8080/us/ny?datestamp=2019-05-01&leadname=abc&viceleadname=xyz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With