程序员社区

【SpringMvc学习及总结05】@RequestMapping注解

文章目录

      • 1.@RequestMappeing标注在方法和类上
        • 1.1 写在方法上的RequestMapping
        • 1.2 写在类上的RequestMapping
      • 2.@RequestMapping的属性
        • 2.1 method属性:规定请求方式
        • 2.2 params属性:规定请求参数
        • 2.3 headers属性:规定请求头
        • 2.4 consumes属性
        • 2.5 produces属性

1.@RequestMappeing标注在方法和类上

SpringMvc使用@RequestMapping注解为控制器指定可以处理哪些请求。
在控制器的类定义和方法定义上都可以标注:
 在类上定义:提供初步的请求信息相对于web应用的根目录
 在方法上定义:提供进一步的细分映射信息,相对于类定义处的URL
 如果类定义处未标注,则方法处标注的URL相对于WEB应用的根目录。

何为web应用的根目录?
在这里插入图片描述

1.1 写在方法上的RequestMapping

写一个前端页面:

<a href="handle01">写在方法上的RequestMapping测试....</a>

写一个控制器:

@Controller
public class RequestMappingController {
    @RequestMapping("/handle01")
    public String test1(){
        System.out.println("handle01方法执行了....");
        return "success";
    }
}

1.2 写在类上的RequestMapping

写一个前端页面:

<a href="haha/handle01">写在类上的RequestMapping测试....</a>

写一个控制器:

@Controller
@RequestMapping("/haha")
public class RequestMappingController {

    @RequestMapping("/handle01")
    public String test1(){
        System.out.println("handle01方法执行了....");
        return "success";
    }
}

2.@RequestMapping的属性

上面没有加任何属性的,默认为value属性:
@RequestMapping(value="/handle01")

2.1 method属性:规定请求方式

method属性:限定请求方式
method=RequestMethod.POST:限定请求方式为post
不是请求的方式就报错

<a href="haha/handle01">RequestMapping测试....</a>
@Controller
@RequestMapping("/haha")
public class RequestMappingController {
    @RequestMapping(value = "/handle01",method = RequestMethod.POST)
    public String test1() {
        return "success";
    }
}

报下面的错:因为超链接的提交方式为get
在这里插入图片描述

2.2 params属性:规定请求参数

params={"username"}:发送的请求中必须带有username这个属性,不带就报错。

@Controller
@RequestMapping("/haha")
public class RequestMappingController {
    @RequestMapping(value = "/handle02",params = {"username"})
    public String test2() {
        return "success";
    }
}
<a href="haha/handle02?username=kk">RequestMapping测试....</a>

params={"!username"}:发送的请求中必须不带username这个属性
params={"username=123"}:发送的请求中必须带username属性,并且值为123
params={"username!=123"}:发送的请求中必须带username属性,但值不能为123
params={"username",pwd}:发送的请求中必须带username属性和pwd属性

2.3 headers属性:规定请求头

将请求头设置为火狐:User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0

@Controller
@RequestMapping("/haha")
public class RequestMappingController {
    @RequestMapping(value = "/handle03",
            headers = "User-Agent= Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0")
    public String test3() {
        return "success";
    }
}

2.4 consumes属性

只接受内容类型是哪种的请求,规定请求头中的content-Type

2.5 produces属性

告诉浏览器返回的内容内容类型是什么,给响应中加上content-Typr

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 【SpringMvc学习及总结05】@RequestMapping注解

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区