什么是URL映射?
当前端发出一个URL请求时,后端要来映射请求获取到URL,并获取到其中的参数
@RequestMapping
添加注解@Controller 将其标识为控制器使用
添加注解@RequestMapping 来映射请求得到url
当我们输入localhost:8080/user/hello 时,后台就能拦截到请求并返回index主页
@controller
@RequestMapping("/user")
public class UserController{
@RequestMapping("hello")
public String myHello(){
return "index"; //表示springmvc返回了一个逻辑视图index
}
}
将 @RequestMapping 注解在 UserController 类上是添加根路径,用来隔离类中的相同方法。
也就是 项目名/user/hello 这样可以直接找到usercontroller中的hello方法,而不是其他类中的。
@RequestMapping
功能:请求映射,每个URL都有一个对应的函数来处理
几种写法:
@RequestMapping(“/hello”)
@RequestMapping(path={“/hello”,”/index”}) —俩个URL都可以匹配
@RequestMapping(value=”/hello”)
@RequestMapping(value=”/hello”,method=RequestMethod.GET) –限制只能GET请求
@RequestMapping(value=”/hello”,method=RequestMethod.POST) –限制只能POST请求
浏览器直接写URL或者a标签都是get请求,一般情况下,如果使用form表单提交都是post请求
如果限制只能用POST请求时,访问了GET请求就会报错,status = 405
@ResponseBody
@ResponseBody 这个注解的作用是将函数返回值作为请求返回值。没有这个注解的话,请求的响应应该是一个页面,有这个注解的话,则直接返回函数值。
例如:
@Controller
public class IndexController{
@RequestMapping(path={"/","/index"})
@ResponseBody
public String index(){
return "index";
}
加上@ResponseBody 页面就显示index,不加@ResponseBody就会去模版的目录下去寻找index页面返回。
@PathVariable和@RequestParam
两者的作用都是将request的URL里的参数的值绑定到contorller里的方法参数里的,区别在于,URL写法不同。
@PathVariable用于获取路径中的参数,将参数解析到变量中。
@RequestParam用来获取请求的参数,将参数解析到变量中。
使用@RequestParam时,URL是这样的:http://host:port/path?参数名=参数值
使用@PathVariable时,URL是这样的: http://host:port/path/参数值
例如:对于http://host:port/user/123?type=2&key=z
@RequestMapping(path = {"/profile/{groupId}/{userId}"})
@ResponseBody
public String profile(@PathVariable("userId") int userId,
@PathVariable("groupId") String groupId,
@RequestParam("type", defaultValue = "1") int type, //defaultValue是设置type的默认值
@RequestParam("key", required = false) String key) {
return String.format("Profile Page of %s / %d / t:%d k: %s", groupId, userId, type, key);
}
页面显示:Profile Page of user / 123 / t:2 k:z
如果请求中某@RequestParam的请求参数不存在,如http://host:port/user/123?type=2,返回的页面就会报错,所以要设置defaultValue(设置参数如果不存在的默认值)或者required(是否一定需要其存在,默认为ture,设置成false的话不存在就不会出错)
通过@RequestParam获取前端参数
@RequestMapping("testRequestParam")
public String filesUpload(@RequestParam ("username")String username,
@RequestParam ("password") String password) {
System.out.println(username + "and" + password);
return "index";
}
前端代码
<form action="/gadget/testRequestParam" method="post">
参数username:<input type="text" name="username">
参数password:<input type="password" name="password">
</form>
输出: 123 and 123