SpringMVC----@RequestMapping_PathVariable映射URL绑定的占位符

Posted yikuandyk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC----@RequestMapping_PathVariable映射URL绑定的占位符相关的知识,希望对你有一定的参考价值。

1.概述

  带占位符的URL是spring3.0新增的功能,该功能在SpringMVC向REST目标挺进发展过程中具有里程碑的意义;

  通过@PathVariable可以将URL中占位符参数绑定到控制器处理方法的入参中:URL中的{xxx}占位符可以通过@PathVariable("xxx")绑定到操作方法的入参中;

2.代码

测试类:

package com.yk.springmvc.handlers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {

    private static final String SUCCESS = "success";
    
    
    @RequestMapping("/testPathVariable/{id}")
    public String testPathVariable(@PathVariable(value=("id")) Integer id){
        System.out.println("SpringMVCTest.testPathVariable()"+id);
        return SUCCESS;
    }
    
    @RequestMapping("/testAntPath/*/abc")
    public String testAntPath(){
        System.out.println("SpringMVCTest.testAntPath()");
        return SUCCESS;
    }

    /**
     * 可以使用params和headers来更加精确映射请求,params和headers支持简单的表达式
     * @return
     */
    @RequestMapping(value="testParamsAndHeaders",params={"username","age!=10"}/*,headers={"Accept-Language:zh-CN,zh;q=0.9"}*/)
    public String testParamsAndHeaders(){
        System.out.println("SpringMVCTest.testParamsAndHeaders()");
        return SUCCESS;
    }

    /**
     * 使用method属性指定请求方式
     * @return
     */
    @RequestMapping(value="/testMethod",method=RequestMethod.POST)
    public String testMethod(){
        System.out.println("SpringMVCTest.testMethod()");
        return SUCCESS;
    }

    @RequestMapping("/testRequestMapping")
    public String testRequestMapping(){
        System.out.println("SpringMVCTest.testRequestMapping()");
        //        return "success";    下面会有很多,所以定义一个常量
        return SUCCESS;
    }    
}



index.jsp

<a href="springmvc/testPathVariable/1">testPathVariable</a>



结果返回:

SpringMVCTest.testPathVariable()1
SpringMVCTest.testPathVariable()100000
SpringMVCTest.testPathVariable()100000
SpringMVCTest.testPathVariable()15555

 

以上是关于SpringMVC----@RequestMapping_PathVariable映射URL绑定的占位符的主要内容,如果未能解决你的问题,请参考以下文章