Spring MVC 控制器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22314145/article/details/82628781

Spring MVC 控制器

一. 常用注解

1.1 @Controller

@Controller注解表明了一个类是作为控制器的角色而存在的。@Controller注解覆盖了@Component注解的功能,需要开启自动扫描才能正常使用,开启自动扫描的两种方式:

//基于xml配置
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>

//基于代码的配置
@ComponentScan("org.springframework.samples.petclinic.web")

1.2 @RequestMapping

@RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

@RequestMapping注解参数:

//常用参数
value:指定请求的实际地址,指定的地址可以是URI Template 模式;
method: 指定请求的method类型, GETPOSTPUTDELETE等;

//仅作了解即可
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
params: 指定request中必须包含某些参数值时,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

1.3 @PathVariable

使用示例:

//请求url
http://localhost:8080/user/13755919043

//控制层的方法
@RequestMapping("/user/{userMobile}")
public void test(@PathVariable String userMobile){

}

1.4 @RequestParam

一般用来处理请求url中?后面所带的参数。使用示例:

//请求url
https://api.sjjz.com/admin/api/v1/dataStat/getAssetIncreaseList?pageNum=1&pageSize=15

//控制层的方法
@RequestMapping("/user")
public void test(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize){

}

1.5 @RequestBody

一般用来处理请求中附带的实体类参数(json参数)。使用示例:

//请求代码
var url="/star/add";
var data={"number":number,"name":name,"occupation":occupation,"country":country};
$.ajax({
    url:url,
    type:'post',
    async:true,
    contentType: 'application/json',
    data:JSON.stringify(data),
    success:function(){
        getData(page,size);
    }
});

//控制层的方法
@RequestMapping("/star/add")
public void test(@RequestBody Star star){

}

猜你喜欢

转载自blog.csdn.net/qq_22314145/article/details/82628781