项目中要用到Rest的web service,提前做了一个Demo,做下笔记。
Demo 分2个项目,一个是restServer 一个是restClient, 都是Spring MVC架构。主要看代码:
Pojos:
package com.pojo; import java.io.Serializable; public class Phone implements Serializable{ private static final long serialVersionUID = 1L; private String phoneNumber="1"; private String phoneType="1"; public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPhoneType() { return phoneType; } public void setPhoneType(String phoneType) { this.phoneType = phoneType; } }
package com.pojo; import java.io.Serializable; public class PhoneResult implements Serializable { private static final long serialVersionUID = 1L; protected String rawPhoneNumber; protected String result; public String getRawPhoneNumber() { return rawPhoneNumber; } public void setRawPhoneNumber(String rawPhoneNumber) { this.rawPhoneNumber = rawPhoneNumber; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
restServer controller:
package com.acxiom.rest.controller; import org.codehaus.jackson.map.ObjectMapper; 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.ResponseBody; import com.pojo.Phone; import com.pojo.PhoneResult; @Controller @RequestMapping({ "/helloworld" }) public class HelloWorldController { @RequestMapping(value = { "/hi/{userName}" }, method = {RequestMethod.GET }) @ResponseBody public String hi(@PathVariable("userName") String userName) { return "Hi, " + userName; } @RequestMapping(value = { "/hello" }, method = {RequestMethod.GET }) @ResponseBody public String process(String userName) { return "Hello, " + userName; } @RequestMapping(value = { "/hiPost/{userName}" }, method = {RequestMethod.POST }) @ResponseBody public String hiPost(@PathVariable("userName") String userName) { return "Hi, " + userName; } @RequestMapping(value = { "/hello" }, method = {RequestMethod.POST }) @ResponseBody public String helloPost(String userName) { return "Hello, " + userName; } @RequestMapping(value = { "/hygiene/{phone}" }, method = {RequestMethod.POST },produces="application/json") @ResponseBody public PhoneResult hygiene(@PathVariable("phone")String phoneObject) { PhoneResult result = new PhoneResult(); try { ObjectMapper mapper = new ObjectMapper(); Phone phone = mapper.readValue(phoneObject, Phone[].class)[0]; result.setRawPhoneNumber(phone.getPhoneNumber().toUpperCase()); result.setResult("SUCCESS"); }catch (Exception e) { e.printStackTrace(); result.setResult("ERROR, " + e.getMessage()); } return result; } }
restClient controller:
package com.acxiom.rest.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; import com.pojo.Phone; import com.pojo.PhoneResult; import com.util.JsonUtil; @Controller public class HomeController { @Autowired private RestTemplate restTemplate; @RequestMapping(value = { "/home" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET }) public String home(ModelMap model) throws Exception { //test get hi method 1 String url = "http://localhost:8080/restServer/helloworld/hi/{userName}.spring"; Map<String, String> map = new HashMap<String, String>(); map.put("userName", "TOMMY"); model.addAttribute("HiResponse", getResponseMessage(url, map)); //test get hi method 2 model.addAttribute("HiResponse2", this.restTemplate.getForEntity(url, String.class, "TOMMY2").getBody()); //test get hello method url = "http://localhost:8080/restServer/helloworld/hello.spring?userName=seaboy"; model.addAttribute("HelloResponse", getResponseMessage(url, null)); //test post hello method model.addAttribute("HelloPostResponse", this.restTemplate.postForEntity("http://localhost:8080/restServer/helloworld/hello.spring?userName=seaboyPost", null, String.class).getBody()); //test post hygiene method MultiValueMap<String,Object> dataMap2 = new LinkedMultiValueMap<String, Object>(); Phone p = new Phone(); p.setPhoneNumber("0513 1111"); dataMap2.add("phone", JsonUtil.javaToJson(p)); HttpEntity<Object> entity2 = new HttpEntity<Object>(dataMap2); model.addAttribute("PhoneResponse", this.restTemplate.postForObject("http://localhost:8080/restServer/helloworld/hygiene/{phone}.spring", entity2, PhoneResult.class, dataMap2)); return "home"; } private String getResponseMessage(String url, Map<String, String> paras) { if (paras != null) { return this.restTemplate.getForEntity(url, String.class, paras).getBody(); } else { return this.restTemplate.getForEntity(url, String.class).getBody(); } } }
JsonUtil:
package com.util; import java.io.StringWriter; import org.codehaus.jackson.map.ObjectMapper; public class JsonUtil { public static String javaToJson(Object o) throws Exception{ StringWriter writer = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(writer, o); String json=writer.toString(); return json; } }
home.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>HOME PAGE</title> </head> <body> <div id="main"> <div id="top"> Hi Response: ${HiResponse} <br> Hi2 Response: ${HiResponse2} </div> <div id="buttom"> Hello Response: ${HelloResponse} <br> Hello Post Response: ${HelloPostResponse}<br> Phone Response: ${PhoneResponse.result} </div> </div> </body> </html>
测试结果:
Hi Response: Hi, TOMMY Hi2 Response: Hi, TOMMY2 Hello Response: Hello, seaboy Hello Post Response: Hello, seaboyPost Phone Response: 86 0513 11112222
相关推荐
java rest简单实例,新手入门,架包完善丰富。本地导入即可运行
自己写的小例子,部署以后就能运行,包涵七种默认action方法,适合新人入门,高手不必下载了
官方app应用示例,包含基本action,下载后import工程,参照lib目录下图片中包含的jar包导入部署即可运行。
使用Spring MVC创建REST服务简单例子
这是一个spring开发java的一个入门级例子。可以 看看!
MyEclipse搭建 REST Web Service项目简单的示例
Spring3MVC-REST-HelloWorld 实例简单代码
安装 REST 插件非常简单,只需按如下步骤进行即可: 将 Struts 2 项目下 struts2-convention-plugin-2.1.6.jar、struts2-rest-plugin-2.1.6.jar 两个 JAR 包复制到 Web 应用的 WEB-INF/lib 路径下。 由于 Struts 2 ...
rest开发简单小案例完整工程,及内包含rest开发所需的所有jar包。
慧正工作流接口调用的简单实例 REST接口调用 使用的 针对JAVA客户端使用
为了让读者对REST在WCF中的应用有一个大致的了解,我们先来进行一个简单的实例演示。[源代码从这里下载] 微软在WCF3.5中就通过提供基于WebHTTP的编程模式使我们很容易地创建基于REST的服务,WCF4.0中对此进行了较...
需要maven开发环境,使用intellij idea打开,分为服务端(server)和客户端(client)
自己学习过程中写的一个整合以上技术的小例子,只有一个向数据库插入的操作,结构简单明了,SSH+rest+spring全注解(包括对beanname命名策略配置)
go-todo-rest-api-example, 简单todo应用程序的rest式API示例 执行 REST API 示例简单todo应用程序的rest式API示例这个简单的教程或者例子,使用 /mux ( 一个漂亮的mux库) 和英镑( 一个ORM的ORM ) 来制作简单的...
JavaWeb服务SOAP(jax-ws)和REST(jax-rs)规范,CXF整合Spring和未整合Spring的简单例子。结合说明看,简单易懂:my.oschina.net/lock0818/blog/314120
这是一个REST API 在Azure上应用的简单通讯录例子。 运行环境 VS2015 并安装 Azure App Service Tools V2.9软件包。已经有Azure账号。 使用方法: 第一步: 建立 API 服务器端 打开 ContactsList.API, 鼠标右键 ...
构建一个REST风格的接口最简单的方法是创建一个基于WSGI标准(PEP 3333)的很小的库,下面是一个例子: # resty.py import cgi def notfound_404(environ, start_response): start_response('404 Not Found', [ ('...
以太坊休息基于RPC构建的简单REST API例子合约: 0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac 方法: balanceOf(address) returns (uint256) 参数: ["0x0f564a2a5fde73349890e86e9b2aa1639994bf2f"] /0xb64ef51c...
android/一个最小的Android程序实例 rest/ PHP Laravel 框架来创建 RESTful API python/简单的pyhon示例 硬件/硬件串口通信收集 doc/文档简介ppt nginx配置系统框架图 仪表板/基于ruby框架的仪表板
VS12下REST风格的ASP.NET Web API框架实例。对list实现简单的增删改查。CRUD