use*_*702 3 rest soap web-services middleware
如何使用 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;
}
}
Run Code Online (Sandbox Code Playgroud)
REST 是一种完全不同的方式来看待 SOAP 的 Web 服务。特别是,它在资源、它们的表示以及它们之间的链接方面运作。(您也有 HTTP 动词,但对于像这样的简单查询服务,您可能只会使用 GET。)
该接口的 RESTful 版本的工作方式有点像这样:
现在,我们需要将这些东西映射到 URL:
/search?place=somename很容易挂在地名后面),其中包含指向……的链接。/place/{id}在哪里{id},它可能是您的数据库的主键;由于重复名称问题,我们不想在此处使用该名称),其中包含指向……的链接。/place/{id}/maxTemp、/place/{id}/minTemp、/place/{id}/humidity。我们还需要有一些方法来创建文档。推荐使用JAXB 。链接可能应该在 XML 中完成,属性称为xlink:href; 使用(通过引用)XLink 规范,它准确地指出属性的内容是一个链接(由于其一般性质,明确的声明否则在 XML 中是一个真正的问题)。
最后,您可能希望使用 JAX-RS 将 Java 代码绑定到服务。这比自己编写所有内容要容易得多。这让你可以开始做这样的事情(为了简洁,省略了数据绑定类):
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.
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它可以继续进行一点,但只要您从一个关于一切含义的良好计划开始,就可以做到这一点并不难……
| 归档时间: |
|
| 查看次数: |
21989 次 |
| 最近记录: |