在Spring MVC控制器中,可以通过使用@ResponseBody
注解来发送JSON响应。@ResponseBody
注解可以将方法的返回值直接转换为JSON格式,并将其作为响应发送给客户端。
下面是一个示例代码:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@PostMapping("/api/endpoint")
@ResponseBody
public MyResponse handlePostRequest(@RequestBody MyRequest request) {
// 处理请求逻辑
MyResponse response = new MyResponse();
// 设置响应数据
response.setMessage("Success");
response.setData(request.getData());
return response;
}
}
在上面的示例中,@PostMapping
注解用于指定处理POST请求的URL路径。@RequestBody
注解用于将请求的JSON数据绑定到MyRequest
对象中。@ResponseBody
注解用于将方法的返回值转换为JSON格式,并作为响应发送给客户端。
MyRequest
和MyResponse
是自定义的请求和响应对象,你可以根据实际需求进行定义。
关于Spring MVC的更多信息,你可以参考腾讯云的产品文档:Spring MVC
领取专属 10元无门槛券
手把手带您无忧上云