欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android + Spring RESTful 简单登录  

程序员文章站 2022-03-12 20:14:03
...
注:
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);
        }