码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC RESTful总结之GET请求

时间:2015-12-29 06:28:09      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:springmvc   get   restful   

   SpringMVC RESTful用法灵活,使用方便,介绍几中GET请求方法:

 1,使用@PathVariable

package com.zws.user.controller.rest;

import java.io.UnsupportedEncodingException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zws.user.beans.User;
import com.zws.utils.GsonUtil;

@Controller
@RequestMapping("/rest/user")
public class UserRestController {
    @RequestMapping(value="/getUserById0/{id}-{name}",method=RequestMethod.GET)
    public @ResponseBody String getUserById0(@PathVariable Long id, 
            @PathVariable("name") String userName) {
        User user = new User();
        user.setUserName(userName);
        user.setId(id);
        
        return GsonUtil.toJson(user);
    }
    
}

   通过使用注解@PathVariable可以将URL中的占位符参数映射到处理方法的入参,注解@PathVariable接受一个可选的字符串类型的参数用于指定哪个占位符映射到方法的哪个参,在以上例子中@PathVariable("name") String userName指定名称为name的占位符参数映射到userName参数,例如如下URL:

http://127.0.0.1:8080/SpringMVCHibernate4/rest/user/getUserById0/100-张三

则将100映射到id,张三映射到userName。

2,另一种占位符用法

@RequestMapping(value="/{id}-{name}",method=RequestMethod.GET)
public @ResponseBody String getUserById1(@PathVariable Long id, 
     @PathVariable("name") String userName) {
    User user = new User();
    user.setUserName(userName);
    user.setId(id);
        
    return GsonUtil.toJson(user);
}

   这种写法同样可以达到与方法1相同的映射效果,示例URL

http://127.0.0.1:8080/SpringMVCHibernate4/rest/user/100-张三

3,使用@RequestParam

   以上两种参数映射均为URL中带有占位符的用法,传统的带有参数的GET请求的写法如下:

@RequestMapping(value="/getUserById2",method=RequestMethod.GET)
public @ResponseBody String getUserById2(@RequestParam Long id, 
        @RequestParam("name") String userName){
    User user = new User();
    user.setUserName(userName);
    user.setId(id);
        
    return GsonUtil.toJson(user);
}

   区别于以上两种参数映射写法,这里用到了@RequestParam注解,此注解用于映射URL中?后面的参数,例如:

http://127.0.0.1:8080/SpringMVCHibernate4/rest/user/getUserById2?id=100&name=张三

则可将100映射到id,张三映射到userName。

   总结起来其实就两种写法,一种是带有占位符的参数映射方法,此时需要用到注解@PathVariable。另一种为传统的写法,用到@RequestParam注解。

本文出自 “埃文” 博客,请务必保留此出处http://wenshengzhu.blog.51cto.com/5151285/1729336

SpringMVC RESTful总结之GET请求

标签:springmvc   get   restful   

原文地址:http://wenshengzhu.blog.51cto.com/5151285/1729336

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!