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

SpringMVC充当Webservice与android通信

2015-06-05 10:20 597 查看
说到SpringMVC必然要介绍SpringMVC的注解,先来介绍一下,接下来会用到的注解:

1.@RequestMapping

这是最重要的一个注解,用于处理HTTP请求地址映射,可用于类或方法上,用于类上时表示类中的所有响应请求的方法都是以该地址作为父路径,在Spring中,一般一个Controller类处理一种资源,所以每个Controller类都会加@RequestMapping注解。

常用属性:

value:指定请求的地址

method:指定请求的method类型, GET、POST、PUT、DELETE等

params:指定request中必须包含某些参数值是,才让该方法处理

<span style="font-size:14px;"><span style="font-size:14px;">@Controller
@RequestMapping("/login")
public class LoginController {
@Autowired
private CommonService commonService;
.....
}</span></span>

后台接收的数据如下图:



2.@RequestBody

用于读取Request请求的body数据,这里主要是用来接收android端发出的json字符串。
<span style="font-size:14px;">@RequestMapping(value = "/getjson")
@ResponseBody
public String returnAdmin(@RequestBody String id) {
List<User> users = commonService.getEntityList(User.class);
User admin = commonService.get(User.class, id);
// JSONObject jsb = JSONObject.fromObject(users.get(0));
JSONArray jsa = JSONArray.fromObject(users);
return jsa.toString();
}</span>
3.@ResponseBody

用于将Controller中方法返回的对象.这里返回json字符串。
4.@PathVariable

映射URL路径里面的参数

<span style="font-size:14px;">@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Contact findContactById(@PathVariable Long id) {
return contactService.findById(id);
}</span>


android端json请求写法:
<span style="font-size:14px;">HttpPost request = new HttpPost("http://192.168.40.28:8888/prj-pet/login/getjson.do");//url地址
// 先封装一个 JSON 对象
JSONObject param = new JSONObject();
try {
param.put("id", "402882e54c418e69014c418f914e0001");
// 绑定到请求 Entry
StringEntity se = new StringEntity(param.toString());
//				request.setEntity(null);
request.setEntity(se);
// 发送请求
HttpResponse httpResponse = new DefaultHttpClient().execute(request);
// 得到应答的字符串,这也是一个 JSON 格式保存的数据
String retSrc = EntityUtils.toString(httpResponse.getEntity());
// 生成 JSON 对象
text=retSrc;
JSONObject result = new JSONObject( retSrc);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}</span>
只要将这段代码,放到一个线程里面去执行,即可获取服务器数据。

最后安卓端不要忘记加上权限。

<span style="font-size:14px;"><uses-permission android:name="android.permission.INTERNET"/></span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息