spring-android的使用【转】
android + Spring RESTful 简单登录 (spring3实现服务端 rest api)
url?format=json 服务器端返回json数据
url?format=xml 服务器端返回xml数据
url 默认返回html数据
登录restful风格 部分源码
android客户端 导入spring for android开源jar
spring-android-rest-template-1.0.0.RC1.jar
spring-android-core-1.0.0.RC1.jar
spring-android-auth-1.0.0.RC1.jar
服务器端部分代码(spring3.1.1+hibernate4.1.2(jpa2)完全注解方式实现 )
======================================上代码=====================================
======================================android客户端=================================
- public class SpringHttpClient {
- private static RestTemplate restTemplate;
- private final static String url = "http://192.168.0.8:6060/contact";
- private final static String login = url + "/user/userLogin/{loginname},{loginpassword}?format=json";
- private final static String query = url + "/user/list?format=json";
- private final static String add = url + "/user/add?format=json";
- private final static String detail = url + "/user/{id}/detail?format=json";
- private final static String update = url + "/user/{id}/updates?format=json";
- private final static String delete = url + "/user/{id}/delete?format=json";
- private final static String upload = url + "/user/upload?format=json";
- static {
- restTemplate = new RestTemplate();
- }
- public SpringHttpClient(){
- }
- /**
- * 登录,
- * @param username
- * @param password
- * @return {"user":{"id":"1","loginname":"superman","loginpassword":"unicom","username":"超级管理员","useremail":"superman@163.com","usermobile":null,"userstate":null,"userlogintime":null}}
- */
- public static String OAuth(String username,String password){
- Map<String, String> request = new HashMap<String, String>();
- request.put("loginname", username);
- request.put("loginpassword", password);
- return getObject(login,request);
- }
- /**
- * 得到所有的用户,
- * @return ........
- */
- public static String ListAll(){
- return getObject(query, null);
- }
- /**
- * 根据id得到唯一用户
- * @param id
- * @return{"user":{"id":"4028809b376e28be01376e294b180000","loginname":"sdfsdf","loginpassword":"sdfsdf","username":"sdfsdf","useremail":"sdfsdf","usermobile":null,"userstate":null,"userlogintime":null}}
- */
- public static String Detail(String id){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", id);
- return getObject(detail, request);
- }
- /**
- * 添加一个用户
- * @param user
- * @return
- */
- public static String Add(Users user){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", "");
- MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
- map.add("loginname", user.getLoginname());
- map.add("loginpassword", user.getLoginpassword());
- map.add("useremail", user.getUseremail());
- map.add("usermobile", user.getUsermobile());
- return postObject(add,map,request);
- }
- /**
- * 根据id更新用户 返回更新的实例和信息(restTemplate.put 也可以直接更新)
- * @param id
- * @param user
- * @return{"users":{"id":"4028809b376daa8901376dab59520001","loginname":"45345345","loginpassword":null,"username":"测试一下kankan","useremail":null,"usermobile":"ddddd","userstate":null,"userlogintime":null}}
- */
- public static String Update(String id,Users user){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", id);
- MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
- map.add("loginname", user.getLoginname());
- map.add("username", user.getUsername());
- map.add("usermobile", user.getUsermobile());
- return postObject(update,map, request);
- }
- /**
- * 更加id删除用户(也可以用restTemplate.delete 但是没有返回的信息)
- * @param id
- * @param user
- * @return {"ajax":{"success":true,"messages":"删除成功!"}}
- */
- public static String Delete(String id){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", id);
- return getObject(delete, request);
- }
- /**
- * 上传文件
- * @param path
- * @return
- */
- public static String UploadFile(String path){
- MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
- Resource resource;
- try {
- resource = new UrlResource("file://"+path);
- formData.add("json", resource);
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- HttpHeaders requestHeaders = new HttpHeaders();
- requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
- HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);
- ResponseEntity<String> response = restTemplate.exchange(upload, HttpMethod.POST, requestEntity, String.class);
- return response.getBody();
- }
=============================服务器端部分代码==============================
- /**注意下面的方法中请求的方法名称是一样的,
- * 只不过根据不同的RequestMethod.GET来找对应的方法
- * RequestMethod (
- * GET=get提交,
- * HEAD,
- * POST=post提交,
- * PUT=put更新,
- * DELETE=delete删除,
- * OPTIONS, TRACE)
- * 对应
- * <form:form method="POST">
- * <form:form method="PUT">
- * <form:form method="DELETE">
- */
- /**
- * 用户列表例子(不带分页)
- * @return
- */
- @RequestMapping(value="/list",method=RequestMethod.GET)
- public ModelAndView UserList(){
- List<Users> list = usersService.listAll();
- return new ModelAndView("main", "userslist", list);
- }
- /**
- * 用户列表例子(带分页)
- * @return
- */
- @RequestMapping(value="/query",method=RequestMethod.GET)
- public ModelAndView UserListPage(HttpServletRequest request,Model model, @ModelAttribute("command") Users command){
- model.addAttribute(Constants.COMMAND, command);
- int pn = ServletRequestUtils.getIntParameter(request, "pn", 1);
- Page<Users> list = usersService.listAllUsers(command, pn);
- model.addAttribute("page", list);
- return new ModelAndView("query");
- }
- /**
- * 新增之前绑定PO到form表单跳转到新增页面例子
- * @param model
- * @return
- */
- @RequestMapping(value="/add",method=RequestMethod.GET)
- public ModelAndView before_UserAdd(Model model){
- //相当于request.setattribute的意思
- if(!model.containsAttribute(Constants.COMMAND))
- model.addAttribute(Constants.COMMAND, new Users());
- return new ModelAndView("add");
- }
- /**
- * 新增用户例子
- * @param users
- * @return
- */
- @RequestMapping(value="/add",method=RequestMethod.POST)
- public ModelAndView after_UserAdd(Users user){
- usersService.save(user);
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("注册成功!");
- return new ModelAndView("ajax","ajax",ajax);
- //也可以直接返回列表也行
- //return new ModelAndView(new RedirectView("list"));
- }
- /**
- * 更新之前绑定PO到form表单跳转到更新页面
- * @param id
- * @param model
- * @return
- */
- @RequestMapping(value="/{id}/detail",method=RequestMethod.GET)
- public ModelAndView get_Users(@PathVariable String id,Model model){
- Users users = usersService.get(id);
- model.addAttribute("users", users);
- return new ModelAndView("detail");
- }
- /**
- * 更新之前绑定PO到form表单跳转到更新页面
- * @param id
- * @param model
- * @return
- */
- @RequestMapping(value="/{id}/updates",method=RequestMethod.GET)
- public ModelAndView before_UsersUpdate(@PathVariable String id,Model model){
- Users users = usersService.get(id);
- if(!model.containsAttribute(Constants.COMMAND))
- model.addAttribute(Constants.COMMAND, users);
- return new ModelAndView("updates");
- }
- /**
- * 更新用户例子(put更新 一般用在web)
- * @param users
- * @return
- */
- @RequestMapping(value="/{id}/updates",method=RequestMethod.PUT)
- public ModelAndView after_put_UserUpdate(Users user){
- usersService.update(user);
- return new ModelAndView("redirect:../list");
- }
- /**
- * 更新用户例子(post更新 一般用在client)
- * @param users
- * @return
- */
- @RequestMapping(value="/{id}/updates",method=RequestMethod.POST)
- public ModelAndView after_post_UserUpdate(Users user){
- usersService.update(user);
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("更新成功!");
- return new ModelAndView("ajax","ajax",ajax);
- }
- /**
- * 删除用户例子
- * @param id
- * @return
- */
- @RequestMapping(value="/{id}/delete",method=RequestMethod.GET)
- public ModelAndView UserDelete(@PathVariable String id){
- usersService.delete(id);
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("删除成功!");
- return new ModelAndView("ajax","ajax",ajax);
- }
- /**
- * 上传文件
- * @param request
- * @return
- */
- @RequestMapping(value="/upload",method=RequestMethod.POST)
- public ModelAndView Upload(@RequestParam("json") MultipartFile multi){
- try {
- byte[] bytes = multi.getBytes();
- FileOutputStream out = new FileOutputStream("D:\\"+multi.getOriginalFilename());
- out.write(bytes);
- out.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("文件上传成功!");
- return new ModelAndView("ajax","ajax",ajax);
- }
//--------------------------------------------------------------
使用Spring-Android获取和解析json数据
spring-android-core-1.0.0.M4.jar
spring-android-rest-template-1.0.0.M4.jar
gson-2.1.jar 使用google的这个json解析lib是因为这个lib较小
服务端返回数据如:
- {"id":"109","word":"test","translation":"n. 试验;检验"}
客户端建立对应的Domain类,如:
- public class Word {
- private int id;
- private String word;
- private String translation;
- }
使用Spring-Android调用,并转换成Word类
- String url = "http://localhost/api/word/detail.php?id=109";
- RestTemplate restTemplate = new RestTemplate();
- Word word = restTemplate.getForObject(url, Word.class);
另外Spirng Android的Lib库中还提供了解析XML,RSS,还有OAuth验证的实现。
//--------------------------------------------------------------------------------------
http://www.chenwg.com/android/spring-android%E7%9A%84%E4%BD%BF%E7%94%A8.html
了解J2EE的人都会知道spring这个开源框架,不过哥对J2EE的开发没什么兴趣,太重量级了,不适合互联网的应用,还是喜欢php多点,不过sping在移动开发这块也推出了spring-android,spring-android可以做什么?有什么优势呢?
spring-android主要提供了两个重要的功能:
1.Rest模板,很多Android应用都要与服务器进行交互,而现在很多互联网应用的服务器端都会提供Rest服务,数据格式一般是json、xml、rss等,如果使用spring-android,这将大大方便你的Android应用与服务器端的交互,spring-android在解析json,xml都是非常方便的;
2.Auth授权验证,现在很多互联网应用都提供了开放的API服务,而你的Android应用要接入到这些服务中去,往往要经过授权才行,现在很多应用都使用Auth授权认证,如twitter、facebook、新浪微博等,如果使用spring-android,在授权验证这块将会非常方便。
如何使用spring-android呢?
1.首先要去http://www.springsource.org/spring-android 下载spring-android,然后解压。
2.新建一个Android项目,然后将解压后的spring-android里的spring-android-core-1.0.1.RELEASE.jar和spring-android-rest-template-1.0.1.RELEASE.jar放到Android项目的lib目录下,因为要访问在网络,所以要在AndroidManifest.xml文件下加入<uses-permission android:name=”android.permission.INTERNET”/>
3.acitivity_main.xml文件如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/result_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" tools:context=".MainActivity"/></RelativeLayout> |
4.MainActivity.java如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package com.hxxy.springforandroidfirstdemo;import org.springframework.http.converter.StringHttpMessageConverter;import org.springframework.web.client.RestTemplate;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView resultTextView = (TextView) findViewById(R.id.result_text); AsyncTask<String, Void, String> simpleGetTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { // executed by a background thread // 创建一个RestTemplate实例 RestTemplate restTemplate = new RestTemplate(); // 添加字符串消息转换器 restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); return restTemplate.getForObject(params[0], String.class); } @Override protected void onPostExecute(String result) { resultTextView.setText(result); } }; // 完成时更新resultTextView simpleGetTask.execute(url); }} |
spring-android的使用【转】的更多相关文章
- Spring学习总结(一)——Spring实现IoC的多种方式
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法.没有IoC的程序中我们使用面向对象编程对象的创 ...
- 直接拿来用!最火的Android开源项目(完结篇)
直接拿来用!最火的Android开源项目(完结篇) 2014-01-06 19:59 4785人阅读 评论(1) 收藏 举报 分类: android 高手进阶教程(100) 摘要:截至目前,在GitH ...
- 直接拿来用!最火的Android开源项目(完结篇)(转)
摘要:截至目前,在GitHub“最受欢迎的开源项目”系列文章中我们已介绍了40个Android开源项目,对于如此众多的项目,你是Mark.和码友分享经验还是慨叹“活到老要学到老”?今天我们将继续介绍另 ...
- Android annotations REST
使用前: public class BookmarksToClipboardActivity extends Activity { BookmarkAdapter adapter; ListView ...
- GitHub 优秀的 Android 开源项目(转)
今天查找资源时看到的一篇文章,总结了很多实用资源,十分感谢原作者分享. 转自:http://blog.csdn.net/shulianghan/article/details/18046021 主要介 ...
- GitHub 优秀的 Android 开源项目
转自:http://blog.csdn.net/shulianghan/article/details/18046021 主要介绍那些不错个性化的View,包括ListView.ActionBar.M ...
- GitHub上不错的Android开源项目(三)
收集相关系列资料,自己用作参考,练习和实践.小伙伴们,总有一天,你也能写出 Niubility 的 Android App :-) GitHub上不错的Android开源项目(一):http://ww ...
- Spring实战1:Spring初探
主要内容 Spring的使命--简化Java开发 Spring容器 Spring的整体架构 Spring的新发展 现在的Java程序员赶上了好时候.在将近20年的历史中,Java的发展历经沉浮.尽管有 ...
- Eclipse中通过Android模拟器调用OpenGL ES2.0函数操作步骤
原文地址: Eclipse中通过Android模拟器调用OpenGL ES2.0函数操作步骤 - 网络资源是无限的 - 博客频道 - CSDN.NET http://blog.csdn.net/fen ...
- CSDN首页> 移动开发 直接拿来用!最火的Android开源项目(完结篇)
此前,CSDN移动频道推出的GitHub平台上“最受欢迎的开源项目”系列文章引发了许多读者的热议,在“直接拿来用!最火的Android开源项目”系列文章(一).(二)中,我们也相继盘点了40个GitH ...
随机推荐
- iOS 实时监听app的网络连接状态
实际iOS开发中,在网络通信中我们大部分使用第三方(只谈短链),譬如 AFNetworking.ASIHttpRequest(这个停更了,想必现在没多少人用),swift的 Alamofire 等. ...
- Kyoya and Colored Balls(组合数)
Kyoya and Colored Balls time limit per test 2 seconds memory limit per test 256 megabytes input stan ...
- weblogic8.1在myeclipse中启动正常,在单独的weblogic中无法正常启动的解决方案.
应用程序服务器weblogic8.1.5,项目在myeclipse中启动正常,在单独的服务器中启动就报错了.错误如下图: 经过观察,发现在myeclipse中设置了以下的jar包.估计是这个问题引起的 ...
- Android漫游记(1)---内存映射镜像(memory maps)
Android系统内核基于Linux2.6+内核,因此,其在进程内存管理方面的非常多机制和Linux是非常相像的.首先,让我们来看一个典型的Android进程的内存镜像(App进程和Native本地进 ...
- Unity 4.6 uGUI的点击事件
因为Unity 4.6刚刚发布,自带的uGUI功能的相关资料还不是很完善,今天刚装的Unity 4.6,想看一下uGUI是否好用,那么开始就今天的学习吧啊! 1,新建一个空的工程.
- C# 零散笔记
关于控件 控件实质就是一个类 属性中的Name就是它实例后的变量名 属性中的其他东西就是类中的变量或函数 例如: 可以直接通过Name.BackColor=Color.Yellow; 来直接操作控件的 ...
- 批处理Bat实现整合定时关机或取消定时关机
@echo off :start choice /c:12 /m "输入1为设置定时关机,2为取消定时关机: " if errorlevel 2 goto cancel if er ...
- quick-x 2.2.5 DragonBones 某些fla导出使用后player卡死
1 2 3 4 5 6 7 8 9 10 11 --test 龙骨 self._db = dragonbones.new({ skeleton="game ...
- Core Bluetooth【官方文档翻译】【02】
1.中心设备和外围设备以及它们在蓝牙通讯中的角色. 在所有的BLE( Bluetooth low energy,下文简称蓝牙4.0 )通讯中都涉及2个主要的角色:中心设备和外围设备.它是基于传统的客户 ...
- Method to fix "Naming information cannot be located because the target principal name is incorrect." for AD replication failure
Assume Failure DC FP01 and Working DC DC01 1. Stop the Key Distribution Center (KDC) service on FP01 ...