我对Spring控制器和ajax有一些奇怪的问题。当我尝试使用ajax将JSON对象传递给它时,Controller方法返回404。
这是我的代码:
@Data
@Builder
@JsonAutoDetect
public class Car {
private int gears;
private String color;
}
@Slf4j
@RestController
public class Test {
@PostMapping("/ajaxJsonPost")
public @ResponseBody HttpEntity<Car> samochod(@RequestBody Car car) {
return new ResponseEntity<>(Car.builder().color(car.getColor()).gears(car.getGears()).build(), HttpStatus.OK);
}
@RequestMapping(value = "/ajaxJsonPost", method = RequestMethod.GET)
public HttpEntity<Car> samochod() {
return new ResponseEntity<>(Car.builder().color("blue").gears(1).build(), HttpStatus.OK);
}
}
我发送带有python代码的ajax:
def main():
app_url = 'http://localhost:8888/ajaxJsonPost'
session = requests.Session()
data = {'car': {'gears': 1,
'color': 'blue'}}
response = session.post(url=app_url, data=data)
# response = session.get(url=app_url)
print(response)
print(response.content)
if __name__ == "__main__":
main()
答案 0 :(得分:0)
您应该将应用程序的上下文添加到ajax调用
def main():
app_url = 'http://localhost:8888/YOUR_APP_CONTEXT/ajaxJsonPost'