SpringMVC——笔记

使用 @RequestMapping 映射请求

Spring MVC 使用@RequestMapping 注解为控制器指定可以处理那些URL请求。
  在控制器的类定义及方法定义处都可以标注
    @RequestMapping
      -类定义处: 提供初步的请求映射信息 。相对于WEB应用的根目录
      -方法处:提供进一步的细分映射信息。 相对于类定义处的URL若类定义处
        未标注 @RequestMapping , 则方法处标记的URL相对于WEB应用的根目录。
 
  DispatcherServlet 截获请求后,就通过控制器上 @RequestMapping 提供的映射信息确定请求所对应的处理方法。
 
映射请求参数 , 请求方法或请求头  
  @RequestMapping 除了可以使用URL映射请求外,
还可以是引用请求方法,请求参数及请求头映射请求

  @RequestMapping 的value , method ,params 及 heads
    分别表示 请求URL ,请求方法,请求参数参数及请求头的映射条件,他们之间是与的关系,联合使用多个条件可以让请求映射更加精确。
  params 和 headers 支持简单表达式  
    - params1 : 表示请求必须包含名为param1的请求参数。
    - !param1 : 表示请求不能包含名为param1的请求参数。
    - param1 != value1: 表示请求包含名为param1 的请求参数极其值不能为 value1。
    - {"param1=value1",param2}: 请求必须包含名为 param1 和 param2 的
      两个请求参数,且 param1 参数值必须为 value1;
 
使用@RequestMapping 映射请求  
  Ant 风格资源地址支持3种匹配符
    —— ?:匹配文件名中的一个字符
    —— *: 匹配文件名中的任意字符
    ——**“:** 匹配多层路径
  @RequestMapping 还支持 Ant 风格的URL
    - /user/*/createUser: 匹配 /user/aaa/createUser,/user/bbb/createUser 等URL
    -/user/**/createUser: 匹配 /user/createUser, /user/aaa/bbb/createUser 等URL
    -/user/createUser??: 匹配 / user/createUseraa, /user/createUserbb 等URL
 
@PathVariable 映射URL 绑定的占位符
    带占位符的URL 是Spring 3.0 新增的功能,该功能在Spring MVC 向REST 目标挺进发展中具有里程碑意义。
    通过@PathVarible 可以将URL中占位符参数绑定到控制器处理方法的入参中
        URL中的{xxx}站位符可以通过 @PathVariable("xxx") 绑定到操作方法的入参中。
  @RequestMapping("/delete/{id}")
        public String delete(@PathVariable("id" ) Integer id ){
            UserDao.delete(id);
            return "redirect:/user/list.action";
    }
REST  
  REST : 即 Representational State Transfer 。(资源) 表现层状态转化,是目前所流
    行的一种互联网软件架构。 它结构清晰,符合标准,易于理解,扩展方便,所以正得到越来越多网站的采用
  资源(Resources): 网络上的一个实体,或者说是网络上的一个具体信息,他可以
    是一段文本,一张图片,一首歌曲,一种服务,总之就是一个具体的存在,可以
    用一个URI(统一资源定位符)指向它,每种资源应对一种特定的URI,要获取这个资源
    访问它的URI就可以,因此 URI 即为每个资源的独一无二的识别服。
  表现层(Representation)把资源具体呈现出来的形式。叫做它的表现层
    (Representation) 。比如文本可以用txt格式表现,也可以用HTML格式,
    XML 格式,JSON格式表现,甚至可以采用二进制形式表现。
  状态转化(State Transfer) :每发一个请求,就代表了客户端和服务器的一次交互
    过程,HTTP 协议,是一个无状态协议,即所有的状态都保存在服务器端。因此
    客户端想要操作服务器,必须通过某种手段,让服务器发生状态转化,这种转化
    是建立在表现层之上的,所以就是表现层状态转化,HTTP 协议里面,四个表示
    操作方式的动词 GET POST PUT DELETE,他们分别对应四种基本操作: GET
    用来获取资源,POST 用来新建资源,PUT用来更新资源,DELETE 用来删除资源。
  实例:
    -/order/1 HTTP GET : 得到 id = 1 的 order
    -/order/1 HTTP DELETE : 删除 id = 1 的 order
    -/order/1 HTTP PUT : 更新 id = 1 的 order
    -/order/1 HTTP POST : 新增 id = 1 的 order
    HiddenHttpMethodFilter: 浏览器from 表单只支持 get 和post 请求
      而DELET , PUT 等method 并不支持。Spring3.0 添加了一个通过
      浏览器,可以将这些请求转化为http 方法,使的支持 GET,POST
      PUT, DELETE 请求。
 
请求处理方法签名
    Spring MVC 通过分析处理方法的签名,将HTTP请求
    信息绑定到处理方法的相应人参中。
    Spring MVC 对控制处理方法签名的限制是宽松的,几乎
    可以按喜欢的任何方式对方法进行签名。
    必要时可以对方法入参标注相应的注解。
    (@PathVariable, @RequestParam,@RequestHeader)
    Spring MVC 矿建会将http 请求信息绑定到相应的方法中
    应根据方法的返回值类型做出相应的后续处理。
  
  使用@RequestParam 绑定请求参数值
    在处理方法入参使用 @Request Param 可以把请求参数传递给请求方法。
      - value : 参数名
      - required: 是否必须,默认为true,表示请求参数中
    必须包含对应的参数,若不存在,将抛出异常。  
 @RequestMapping("/handle5")
      public String handle5(@RequestParam(value="userName",required=false)
      String usernName,@RequestParam("age") int age){
          return "success";
      }
  使用@RequestHeader 绑定请求报头的属性值
     请求头包含了若干个属性,服务器可据此获知客户端的信息,通过@RequestHeader
     即可将头中的属性值绑定到处理方法的入参中。
    
@RequestMapping("/handle7")
      public String handle7(@RequestHeader("Accept-Encoding") String encoding,
    @RequestHeader("Keep-Alive")long keppAlieve){return "success";}
 
    使用@CookieValue 绑定请求中的 Cookie 值
    @CookieValue 可让处理方法入参绑定某个Cookie 值
 @RequestParam("/headle6")
      public String handle6(@CookieValue(value="sessionId",required=false) String
        sessionId,@RequestParam("age") int age){
        return "seccess";
      }
  使用POJO 对象绑定请求参数值    
    Spring MVC 会按请求参数和POJO属性名进行自动匹配,自动为该对象填充属性值,支持
      级联属性。dept.deptId , dept.address.tel 等。
      @RequestMapping("/handle8")
        public String handle(User user){
          return "success";
      }
      
    使用Servlet API 作为入参
    @RequestMapping("/handle9")
      public void handle9(HttpServietRequest request,HttpServletResponse response){
      }
// @SessionAttributes(value={"user"},types={String.class})
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {


private static final String SUCCESS = "success";

@ModelAttribute
public void getUser(@RequestParam(value="id",required= false) Integer id,Map<String,Object> map){
if(id != null){
// 模拟从数据库中获取对象
User user = new User(1,"Tom","123456","tom@atguigu.com",12);
System.out.println("从数据库中获取一个对象:"+ user);
map.put("user",user);
}

}
@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user){
System.out.println("修改:" + user);
return SUCCESS;
}

/*注意这个注解只能放在类的上面,不能放在方法上面*/

@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Map<String,Object> map){

User user = new User(1,"Tom", "123456","tom@123.com",15);
map.put("user",user);
map.put("school","atguigu");
return SUCCESS;
}

/*
* 目标方法可以添加 Map 类型的(实际上也可以Model 类型的 或ModeMap 类型的)参数
* */

@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
System.out.println(map.getClass().getName());
map.put("names",Arrays.asList("Tom","Jerry","Mike"));
return SUCCESS;
}

/*
* 返回值可是ModelAndView 类型
* 其中可以包含视图和模型信息
* SpringMVC 会吧ModelAndView 的model 数据放到request 域中。
* */

@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String viewName = SUCCESS;
ModelAndView modelAndView = new ModelAndView(viewName);
// 添加模型到ModelAndView 中
modelAndView.addObject("time",new Date());
return modelAndView;
}

@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request,HttpServletResponse response) {
System.out.println("testServletAPI,"+request+","+ response);
return SUCCESS;
}

/*
* Spring MVC 会按请求参数名和POJO 属性进行资助匹配
* 自动为该对象填充属性值,支持级联动,如 dept.deptId,dept.address.tel 等
* */

@RequestMapping("/testPojo")
public String testPojo(User user){
System.out.println("testPojo" + user);
return SUCCESS;
}

/*@CookieValue: 映射一个Cookie 值,属性同@RequestParam*/
@RequestMapping("/testCoookieValue")
public String testCoookieValue(@CookieValue("JSESSIONID")String sessionId){
System.out.println("CoookieValue:"+ sessionId);
return SUCCESS;

}

/*
* 映射请求头信息
* 用法同@RequestParam
* */

@RequestMapping("/testRequestHander")
public String testRequestHander(@RequestHeader(value="Accept-Language") String al){
System.out.println("testRequestHander,Accept-Language:"+ al);
return SUCCESS;
}

/*
* @RequestParam 来映射请求参数
* */

@RequestMapping(value="/testRequestParam")
public String testRequestParam(@RequestParam(value="username") String un,@RequestParam(value="age",required=false,defaultValue="0") int age){
System.out.println("testRequestParam,username:"+ un + age);
return SUCCESS;
}

/*
* Rest 风格的URL
* 以CRUD 为例:
* 新增: /order POST
* 修改: /order/1 PUT update?id=1
* 获取: /order/1 GET get?id=1
* 删除: /order/1 DELETE delete?id=1
*
* 如何发送PUT 请求和DELETE 请求呢?
* 1.需要配置 HiddenHttpMethodFilter
* 2.需要发送POST请求
* 3.需要在发送POST 请求时携带一个name="_method"值的隐藏域,值为 DELETE 或PUT
*
* */

@RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
public String testRestPut(@PathVariable Integer id) {
System.out.println("testRest PUT:" + id );
return SUCCESS;
}

@RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
public String testRestDelete(@PathVariable Integer id) {
System.out.println("testRest DELETE:" + id );
return SUCCESS;
}

@RequestMapping(value="/testRest",method=RequestMethod.POST)
public String testRest() {
System.out.println("testRest POST" );
return SUCCESS;
}

@RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
public String testRest(@PathVariable Integer id) {
System.out.println("testRest GET:" + id );
return SUCCESS;
}

/*
* @PathVariable 可以来映射URL 中的站位符到目标方法的参数中
*
* */

@RequestMapping("testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id) {
System.out.println("testPathVariable:" + id);
return SUCCESS;
}

@RequestMapping("testAntPath/*/abc")
public String testAntPath() {
System.out.println("testAntPath");
return SUCCESS;
}

/*
* 了解: 可以使用 params 和headers 来更加精确的映射请求,params 和headers 支持简单的表达式,
* */

@RequestMapping(value="testParamsAndHeaders",params={"username","age!=10"},headers={"Accept-Language=en-US,zh;q=0.8"})
public String testParamsAndHeaders(){
System.out.println("testParamsAndHeaders");
return SUCCESS;
}

/*
*
* 使用method 属性来指定请求方式
*
*
* */

@RequestMapping(value="/testMethod",method=RequestMethod.POST)
public String testMethod() {
System.out.println("testMethod");
return SUCCESS;
}

/*
*
*1. @RequestMapping 除了修饰方法还可以修饰类
*2.
*
* */

@RequestMapping("/testRequestMapping")
public String testRequestMapping(){
System.out.println("testRequestMapping");
return SUCCESS;
}
}
 
 

原文地址:https://www.cnblogs.com/nmxs/p/7810350.html