从注解名称上我们可以看到,@RequestMapping注解的作用就是将请求的 URL 地址和处理请求的方式(handler方法)关联起来,建立映射关系。
SpringMVC 接收到指定的请求,就会来找到在映射关系中对应的方法来处理这个请求。
路径为:类路径/方法路径
可以防止名称重复
通过当前请求的请求路径匹配请求
是数组类型,可以匹配多个
@RequestMapping({"/hello","aaa"})
路径匹配的同时,方法也匹配
是枚举类型:GET,POST,HEAD,OPTIONS,PUT,DELETE,TRACE
@RequestMapping(value = "/hello",method = RequestMethod.GET )
“ param” 必须有param
“ !param” 必须没有param
“ param=value” 必须有param而且值为value
“ param!=value” 必须有param而且值不为value
@RequestMapping(value = "/hello",method = RequestMethod.GET ,params = "username")
@RequestMapping(value = "/hello/a*a/b",method = RequestMethod.GET ,params = "username")
REST风格提倡URL地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为URL地址的一部分,以保证整体风格的一致性。还有一点是不要使用请求扩展名。
传统 URL 地址 | REST 风格地址 |
---|---|
/remove/emp?id=5 | /emp/5 |
示例:
及@RequestMapping()中的id为占位符,代表1
@PathVariable(“id”)将占位符中的值赋给 形参
// 测试占位符
@RequestMapping("/test/rest/{id}")
// 将路径中的id(1),赋值给方法中的id
public String rest(@PathVariable("id") Integer id){
System.out.println("id:"+ id);
return "success";
}
控制器的参数名称和网页端的 名称一致 即可
<form th:action="@{/param}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="login">
form>
获取页面代码
@RequestMapping("/param")
//只要设置相同名称的参数即可
public String getParam(String username,String password){
System.out.println(username+"\n"+password);
return "success";
}
如果名字不一样可以使用 @RequestParam(value=“username”)
直接将数据封装入一个实体类对象中 (属性名和参数名一致)
@RequestMapping("/param")
//只要设置相同名称的参数即可
public String getParam(User user){
System.out.println(user);
return "success";
}
结果:
修改web.xml
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
@RequestMapping("/mav")
public ModelAndView Mav(){
/**
* 包含Model和View功能
* Model:向Request中共享数据
* View:设置逻辑视图,实现页面跳转
*/
ModelAndView mav = new ModelAndView();
//向Request中共享数据
mav.addObject("test","hello");
//设置逻辑视图
mav.setViewName("success");
return mav;
}
使用Thymleaf语法获取参数
<p th:text="${test}">p>
@RequestMapping("/model")
public String Model(Model model){
model.addAttribute("test","hello,model");
return "success";
}
使用原生Servlet API
@RequestMapping("/session")
public String Session(HttpSession session){
session.setAttribute("Session","hello,session");
return "success";
}
<p th:text="${session.Session}">p><br>
使用原生Servlet API
@RequestMapping("/Application")
public String Application(HttpSession session){
ServletContext context = session.getServletContext();
context.setAttribute("Application","hello,application");
return "success";
}
<p th:text="${application.Application}">p><br>