控制器@controller支持的返回值类型、@ResponseBody解析ajax请求
    		       		warning:
    		            这篇文章距离上次修改已过448天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring MVC中,@Controller注解用于指示特定类作为控制器,处理web请求。@ResponseBody注解用于将返回值放入响应体中(比如JSON、XML),通常用于返回数据而不是视图。
当使用@ResponseBody注解时,Spring会使用已配置的HttpMessageConverters来转换方法的返回值,并将其写入HTTP响应中。
支持的返回类型:
- 基本数据类型(如int、long等)
- String
- 自定义对象
- 集合或数组
- ResponseEntity<T>
实例代码:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.ResponseEntity;
 
@Controller
public class MyController {
 
    // 返回基本数据类型
    @GetMapping("/intValue")
    @ResponseBody
    public int intValue() {
        return 250;
    }
 
    // 返回String
    @GetMapping("/stringValue")
    @ResponseBody
    public String stringValue() {
        return "Hello, World!";
    }
 
    // 返回自定义对象
    @GetMapping("/customObject")
    @ResponseBody
    public MyCustomObject customObject() {
        return new MyCustomObject();
    }
 
    // 返回ResponseEntity包装的对象
    @GetMapping("/responseEntity")
    public ResponseEntity<MyCustomObject> responseEntity() {
        MyCustomObject myCustomObject = new MyCustomObject();
        return ResponseEntity.ok(myCustomObject);
    }
}
 
class MyCustomObject {
    // 自定义属性和方法
}在上述代码中,MyController中的方法通过@ResponseBody注解返回不同类型的数据,这些数据将通过HTTP响应发送给客户端。客户端可能是一个Web浏览器、移动应用或其他任何发起AJAX请求的客户端。Spring MVC将自动使用合适的HttpMessageConverter将返回对象序列化为JSON(如果配置了支持JSON的转换器)或其他格式。
评论已关闭