0
coressponding數據這是我的代碼:怎麼寫JSON網絡服務來獲取從數據庫表中的Java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dto.FeedObjects;
public class Project {
public ArrayList<FeedObjects> GetFeeds(Connection connection) throws Exception
{
ArrayList<FeedObjects> feedData = new ArrayList<FeedObjects>();
try
{
//String uname = request.getParameter("uname");
PreparedStatement ps = connection.prepareStatement("SELECT id,title,description,url FROM website ORDER BY id DESC");
//ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
FeedObjects feedObject = new FeedObjects();
feedObject.SetId(rs.getInt("id"));
feedObject.setTitle(rs.getString("title"));
feedObject.setDescription(rs.getString("description"));
feedObject.setUrl(rs.getString("url"));
feedData.add(feedObject);
}
return feedData;
}
catch(Exception e)
{
throw e;
}
}
}
這個培訓班裏越來越數據庫表中的數據和JSON格式轉換:
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.ProjectManager;
import com.google.gson.Gson;
import dto.FeedObjects;
@Path("/WebService")
public class FeedService {
@GET
@Path("/GetFeeds")
@Produces("application/json")
public String feed() {
String feeds = null;
try {
ArrayList<FeedObjects> feedData = null;
ProjectManager projectManager = new ProjectManager();
feedData = projectManager.GetFeeds();
Gson gson = new Gson();
feeds = gson.toJson(feedData);
} catch (Exception e) {
System.out.println("error");
}
return feeds;
}
}
封裝模型;
import java.sql.Connection;
import java.util.ArrayList;
import dao.Database;
import dao.Project;
import dto.FeedObjects;
public class ProjectManager {
public ArrayList<FeedObjects> GetFeeds(String id)throws Exception {
ArrayList<FeedObjects> feeds = null;
try {
Database database= new Database();
Connection connection = database.Get_Connection();
Project project= new Project();
feeds=project.GetFeeds(connection);
} catch (Exception e) {
throw e;
}
return feeds;
}
}
還有一個類,我們已經得到了設定值。我能夠顯示使用該URL JSON格式的所有數據庫表的價值,但我希望當我通過ID:
http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds?id=1
,那麼它應該只顯示一個ID對應的姓名,標題,URL。我已經使用這個
http://www.9lessons.info/2012/10/restful-web-services-json-api.html的例子,但無法做到試過這種plz幫助我
plz在我的代碼中添加coz新建這樣做 – user2782773
feedData = projectManager.GetFeeds(id);我們如何在這裏只傳遞一個參數public ArrayList GetFeeds(Connection connection)拋出異常 –
user2782773
代碼不使用Project類中的GetFeeds,而是使用ProjectManager。你可以修改ProjectManager類中的字符串參數類型'id'的方法GetFeeds – Keerthivasan