携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第9天,点击查看活动详情
今天我们来学习一下spring-mvc post和get方法的注解形式说明和对应的参数获取
1.定义一个Get方法,是用@GetMapping("/url地址")
@GetMapping("/g") //代表访问的url地址为 localhost/g
@ResponseBody
public String getMapping(){
return "this is get";
}
重启tomcat,在地址栏访问 http://localhost:8080/g
返回结果为:
2.定义一个post方法 @PostMapping("postUrl地址")
@PostMapping("/p") //url地址为 localhost/p
@ResponseBody
public String postMapping(){
return "this is post";
}
post请求我们使用表单的格式来请求 我们在tomcat默认首页index.html编写对应的提交代码
<form method="post" action="/p">
<input type="submit">提交</input>
</form>
接下来我们访问一下url并且选中提交按钮
访问的结果为:
3.获取请求get请求参数
地址栏请求url为:http://localhost:8080/g?studentName=admin
此时我们要获取studentName参数,获取代码如下
@GetMapping("/g")
@ResponseBody
public String getMapping(@RequestParam("studentName") String abc){
System.out.println(abc);
return "this is get";
}
返回的结果为:
其中@RequestParem("地址栏请求的参数名") abc是我们自己定义的变量名,不一定要和请求栏请求参数一致
4.获取post请求参数
我们在html文件中添加input框,定义参数名username和password,一会儿控制器中获取参数也要使用这两个参数名
<form method="post" action="/p">
用户名<input name="username"/>
密码<input name="password" />
<input type="submit">提交</input>
</form>
控制代码如下
@PostMapping("/p")
@ResponseBody
public String postMapping(String username,String password){
System.out.println(username+":"+password);
return "this is post";
}
post请求:
请求结果为:
5.控制器如果要在指定控制器中添加一层访问目录,使用@RequestMapping
比如:
原先的访问路径为
localhost/getStudent
localhost/getDetail
现在要求在该控制器类多添加一层访问目录,如
localhost/api/getStudent
localhost/api/getDetail
这时候,我们可以在控制器顶部设置对应目录,当前类请求都会默认添加api这一层目录层级