您的位置:首页 > 编程语言 > Java开发

Spring @PathVariable

2015-12-30 17:43 169 查看
1、 @PathVariable 

当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId},

这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
示例代码:

@Controller  
@RequestMapping("/owners/{ownerId}")  
public class RelativePathUriTemplateController {  
  
  @RequestMapping("/pets/{petId}")  
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {      
    // implementation omitted   
  }  
}  
上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。

Java代码  

@Controller  
public class PersonController {  
  
    /** 
     * 查询个人信息 
     *  
     * @param id 
     * @return 
     */  
    @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)  
    public @ResponseBody  
    Person porfile(@PathVariable int id, @PathVariable String name,  
            @PathVariable boolean status) {  
        return new Person(id, name, status);  
    }  
  
    /** 
     * 登录 
     *  
     * @param person 
     * @return 
     */  
    @RequestMapping(value = "/person/login", method = RequestMethod.POST)  
    public @ResponseBody  
    Person login(@RequestBody Person person) {  
        return person;  
    }  
}  

备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}与@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。

 这是restful式风格。 
如果映射名称有所不一,可以参考如下方式: 

Java代码  

@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)  
public @ResponseBody  
Person porfile(@PathVariable("id") int uid) {  
    return new Person(uid, name, status);  
}  

GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。


POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。
@ResponseBody可以标注任何对象,由Srping完成对象——协议的转换。

做个页面测试下: 
Js代码  

$(document).ready(function() {  
    $("#profile").click(function() {  
        profile();  
    });  
    $("#login").click(function() {  
        login();  
    });  
});  
function profile() {  
    var url = 'http://localhost:8080/spring-json/json/person/profile/';  
    var query = $('#id').val() + '/' + $('#name').val() + '/'  
            + $('#status').val();  
    url += query;  
    alert(url);  
    $.get(url, function(data) {  
        alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
                + data.status);  
    });  
}  
function login() {  
    var mydata = '{"name":"' + $('#name').val() + '","id":"'  
            + $('#id').val() + '","status":"' + $('#status').val() + '"}';  
    alert(mydata);  
    $.ajax({  
        type : 'POST',  
        contentType : 'application/json',  
        url : 'http://localhost:8080/spring-json/json/person/login',  
        processData : false,  
        dataType : 'json',  
        data : mydata,  
        success : function(data) {  
            alert("id: " + data.id + "\nname: " + data.name + "\nstatus: "  
                    + data.status);  
        },  
        error : function() {  
            alert('Err...');  
        }  
    });  

Table 
Html代码  

<table>  
    <tr>  
        <td>id</td>  
        <td><input id="id" value="100" /></td>  
    </tr>  
    <tr>  
        <td>name</td>  
        <td><input id="name" value="snowolf" /></td>  
    </tr>  
    <tr>  
        <td>status</td>  
        <td><input id="status" value="true" /></td>  
    </tr>  
    <tr>  
        <td><input type="button" id="profile" value="Profile——GET" /></td>  
        <td><input type="button" id="login" value="Login——POST" /></td>  
    </tr>  
</table>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: