最近的一个项目使用RESTEasy做webservice的实现,我们的项目使用两个工程,一个是发布webservice的,一个是web工程。
工程的目的是这样,WS工程是为了web工程或者其他的类似的web工程使用。所以我们在实现本地web工程的时候,需要自己构建一个URL,通过这个URL去请求WS,达到获取或者存储数据的功能。
这里侧重讲一下我们在POST数据碰到的问题,诚然,我通过RESTEasy tutorial和Google知道有@Form这个东东,用以直接map表单数据到WebMethod的参数对象上。但由于我们的工程是分开的,@Form失去效用。所以通过Google我想到了使用JSON来传输数据,这样就避免了使用多参数的方法。在java对象和JSON的转换上,我借用了Google的Gson.jar.
好了,直接上代码:
WebService接口:
@Path(TpoConstants.WS_ROOT)
public interface AddUserWS {
@POST
@Path(TpoConstants.WS_SAVE_USER)
@Consumes(TpoConstants.PRODUCE_TYPE_JSON)
String saveUser(String jsonUserStr);
}
WebService实现:
public class AddUserWSImpl implements AddUserWS{
private AddUserDao userDao;
public String saveUser(String jsonUserStr) {
// 通过Gson将JSON包含的数据还原为java对象
Gson gson = new Gson();
User user = gson.fromJson(jsonUserStr, User.class);
// 从spring application context 里面拿到指定的DAO
userDao = (AddUserDao)SpringApplicationContext.getBean("addUserDao");
return userDao.addUser(user);
}
}
至此,WebService已准备完毕,就等着被调用了。
public String saveUser(User user) throws MyFleetTPOException {
String saveState = null;
try {
String urlStr = "http://localhost:8080/MyFleetTPO"
+ TpoConstants.WS_ROOT + TpoConstants.WS_SAVE_USER;
saveState = ServiceUtil.getInstance().doPost(new URL(urlStr), user);
} catch (MalformedURLException e) {
logger.error(e.getLocalizedMessage(), e);
throw new MyFleetTPOException(e);
}
return saveState;
}
从上面的代码可以看出,我在Service层传入的参数是一个java对象,并且构造一个URL,然后ServiceUtil会去请求Webservice,将java对象保存到数据库。下面是ServiceUtil代码:
public String doPost(URL url, Object o){
String result = null;
try {
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", TpoConstants.PRODUCE_TYPE_JSON);
// transfer Java Object to JSON type
Gson gson = new Gson();
String input = gson.toJson(o);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (!(conn.getResponseCode() == HttpURLConnection.HTTP_OK
|| conn.getResponseCode() == HttpURLConnection.HTTP_CREATED)) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
result = output;
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
可以看出,我们在Web工程传输的参数是一个Entity:User对象,中间我们将其转化为Json,这个json被Webservice在内部还原,被DAO消化。所以通过JSON, 我们就可以简化RESTEasy的webmethod的参数简化问题。