如何使用 java 语言将 SOAP 转换为 REST?
package net.weather;
import java.sql.*;
import javax.jws.WebService;
@WebService
public class ProjectFinalWS{
Connection con;
Statement st;
ResultSet rs;
String res;
public void connectDB()
{
String url ="jdbc:mysql://localhost:3306/";
String dbName ="project";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try
{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+dbName,userName,password);
}catch(Exception e){}
}
public float getMaxTemp(String city)
{ float mxtemp=0;
connectDB();
try{
st=con.createStatement();
rs=st.executeQuery("select maxtemp from weather where city='"+city+"'");
rs.next();
mxtemp=rs.getFloat(1);
st.close();
con.close();
}
catch(Exception e){}
return mxtemp;
}
public float getMinTemp(String city)
{ float mntemp=0;
connectDB();
try{
st=con.createStatement();
rs=st.executeQuery("select mintemp from weather where city='"+city+"'");
rs.next();
mntemp=rs.getFloat(1);
st.close();
con.close();
}
catch(Exception e){}
return mntemp;
}
public float getHumidity(String city)
{ float humidity=0;
connectDB();
try{
st=con.createStatement();
rs=st.executeQuery("select humidity from weather where
city='"+city+"'");
rs.next();
humidity=rs.getFloat(1);
st.close();
con.close();
}
catch(Exception e){}
return humidity;
}
}
最佳答案
REST 是一种与 SOAP 完全不同的 Web 服务方式。特别是,它根据资源、它们的表示以及它们之间的链接进行操作。 (您也有关于 HTTP 动词,但对于像这样的简单查询服务,您可能只使用 GET。)
该接口(interface)的 RESTful 版本的工作方式有点像这样:
- 客户会决定他们想了解某个特定地点的一些信息,因此他们会要求服务搜索该地点并告诉他们指向该地点的链接,或者至少是与搜索条件匹配的地点;因为这可能是几个不同的地方(想想“伦敦,英国”与“安大略省伦敦”以响应对“伦敦”的搜索),结果将是一个链接到每个地方的特征的页面。它也可能会说明每个链接的含义,但这不是必需的。 (结果的格式可以是 HTML、XML、JSON 或多种不同格式中的任何一种;HTTP 内容协商是在它们之间进行选择的好方法。)
- 一旦用户从列表中确定了他们实际想要了解的信息,他们就会点击链接并获取有关该地点的可用信息的描述。该文档提供指向提供最高温度的页面、提供最低温度的另一个页面以及提供湿度的第三个页面的链接。
- 要获取实际数据,需要访问另一个链接并提供该数据。由于数据是一个简单的 float ,因此将其作为纯文本返回是非常合理的。
现在,我们需要将这些东西映射到 URL:
- 搜索:
/search?place=somename
(很容易与地名 Hook ),其中包含指向……的链接 - 地点:
/place/{id}
(其中{id}
是一些通用 ID,可能是您的数据库的主键;由于重复名称问题,我们不想在此处使用该名称),其中包含指向...的链接。 - 数据:
/place/{id}/maxTemp
,/place/{id}/minTemp
,/place/{id}/humidity
.
我们还需要有一些方法来创建文档。 推荐使用 JAXB。链接可能应该在 XML 中完成,属性名为 xlink:href
;使用(通过引用)这样的 XLink 规范准确地说明属性的内容是一个链接(由于其一般性质,否则这种明确的陈述在 XML 中是一个真正的问题)。
最后,您可能希望使用 JAX-RS 将 Java 代码绑定(bind)到服务。这比自己写要容易得多。这让您可以开始做这样的事情(为了简洁起见,省略了数据绑定(bind)类):
public class MyRestWeatherService {
@GET
@Path("/search")
@Produces("application/xml")
public SearchResults search(@QueryParam("place") String placeName) {
// ...
}
@GET
@Path("/place/{id}")
@Produces("application/xml")
public PlaceDescription place(@PathParam("id") String placeId) {
// ...
}
@GET
@Path("/place/{id}/maxTemp")
@Produces("text/plain")
public String getMaxTemperature(@PathParam("id") String placeId) {
// ...
}
// etc.
}
正如你所看到的,它可以持续一段时间,但只要你从一个好的计划开始,一切都意味着什么,这并不难......
关于web-services - 将 SOAP 转换为 REST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12725262/