2017-02-20 75 views
0

我正在嘗試開發一個允許客戶端將用戶添加到數據庫的RESTful應用程序。這是用戶級POST不會在Java中創建對象

public class User { 

private String id; 
private String name; 

public User(String id, String name){ 
    this.id = id; 
    this.name = name; 
} 

//------------Getters and setters----------------------------------------------------- 
public String getId(){ 
    return id; 
} 

public String getName(){ 
    return name; 
} 
} 

這是用戶數據庫類

public class UserDatabase { 

private Map<String, String> users = new HashMap<String, String>(); 

public UserDatabase(){ 
    users.put("2", "User2"); 
    users.put("3", "User3"); 
} 

public Map<String, String> getAllUsers(){ 
    return users; 
} 

public String getUserName(String id){ 
    return users.get(id); 
} 

public void addUser(String id, String name){ 
    users.put(id, name); 
} 
} 

這是用戶資源

@Path("/users") 
public class UserResource { 

UserDatabase usersDatabase = new UserDatabase(); 

@GET 
@Path("/{id}") 
@Produces(MediaType.APPLICATION_JSON) 
public String getUser(@PathParam("id") String id){ 
    String response = String.valueOf(usersDatabase.getAllUsers().size()); 
    return response + " " + usersDatabase.getUserName(id); 
} 

@POST 
@Consumes(MediaType.APPLICATION_JSON) 
public Response addUser(String userString) throws JSONException { 
    JSONObject user = new JSONObject(userString); 
    String userId = user.getString("id"); 
    String userName = user.getString("name"); 
    usersDatabase.addUser(userId, userName); 
    String result = "Created user with id: " + userId + " and name: " + usersDatabase.getUserName(userId); 
    return Response.status(201).entity(result).build(); 
} 

} 

這是我將做一個POST請求到客戶端添加新用戶,然後獲取GET請求以獲取我剛添加的用戶

public class TestClient { 

private final String baseUrl = "http://localhost:8080/BoardGameManager/rest"; 

public static void main(String[] args) throws IOException{ 

    TestClient client = new TestClient();  
    client.sendPostRequest("/users"); 
    client.sendGetRequest("https://stackoverflow.com/users/1"); 
} 

private void sendGetRequest(String urlString) throws IOException{ 

    //Building and sending GET request 
    URL url = new URL(baseUrl+ urlString); 
    HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
    connection.setRequestMethod("GET"); 
    int responseCode = connection.getResponseCode(); 
    System.out.println("Sending get request : "+ url); 
    System.out.println("Response code : "+ responseCode); 

    //Reading response from input Stream 
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String output; 
    StringBuffer response = new StringBuffer();  
    while ((output = in.readLine()) != null){ 
     response.append(output); 
    } 
    in.close(); 

    //printing result from response 
    System.out.println(response.toString()); 
} 

private void sendPostRequest(String urlString) throws IOException { 

    //Building POST request 
    URL url = new URL(baseUrl + urlString); 
    HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
    connection.setRequestMethod("POST"); 
    connection.setRequestProperty("Content-Type","application/json"); 
    String postData = "{\"id\": \"1\",\"name\": \"User1\"}"; 

    //Sending POST request 
    connection.setDoOutput(true); 
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); 
    outputStream.writeBytes(postData); 
    outputStream.flush(); 
    outputStream.close(); 

    //Receiving response 
    int responseCode = connection.getResponseCode(); 
    System.out.println("\nSending 'POST' request to URL : " + url); 
    System.out.println("Post Data : " + postData); 
    System.out.println("Response Code : " + responseCode); 

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String output; 
    StringBuffer response = new StringBuffer(); 
    while ((output = in.readLine()) != null) { 
     response.append(output); 
    } 
    in.close(); 

    //printing result from response 
    System.out.println(response.toString()); 

} 

} 

問題是,當我發出POST請求時,用戶被添加,但是當我嘗試使用GET請求獲取它時,我剛添加的用戶不存在,我無法理解爲什麼會發生這種情況。

回答

0

其實你正在實例化userDatabasesnew UserDatabase()所以每次你得到userDatabases的新副本,因此你每次都得到一個新的users Map

我建議,讓您的UserDatabase單身,而不是每一個新添加的用戶保留對地圖:

public class UserDatabase { 

    private static UserDatabase instance = null; 

    public static UserDatabase getInstance() { 
     if(instance == null) { 
      instance = new UserDatabase(); 
     } 

     return instance; 
    } 

    private UserDatabase(){ 
     users.put("2", "User2"); 
     users.put("3", "User3"); 
    } 

    //.... 

} 

然後實例UserDatabase這樣的:

@Path("/users") 
public class UserResource { 

    UserDatabase usersDatabase = UserDatabase.getInstance(); 

} 

現在每次你打電話UserDatabase.getInstance()你會得到相同的副本,因此相同users Map

+0

謝謝你的回覆。我按照你的說法修改了代碼,但是現在當試圖添加新用戶時,POST會給我一個錯誤。如果UserDatabase包含地圖(在構造函數中初始化)以及實例字段,那很好嗎? – Weaveon

+0

我認爲你必須保持:private Map users = new HashMap (); –

+0

你有什麼問題? –

0

實際上,如果你使用spring boot來開發你的微服務,你甚至不需要在這裏實現singleton模式。您可以在您的UserDatabase課程上使用@Service註釋。然後在你的UserResource類中執行以下操作。

@Autowired 
UserDatabase usersDatabase = new UserDatabase(); 

Spring將代表您在這裏管理單例實例。

以下依賴關係就足夠了。但我認爲你需要通過添加依賴來創建一個使用spring initializer的項目。我記得下面給出的默認依賴關係就足夠了。此外,您可能會發現一個sample project here

<dependencies> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter</artifactId> 
    </dependency> 

    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-test</artifactId> 
     <scope>test</scope> 
    </dependency> 
</dependencies> 
+0

謝謝,我一定要使用可以使用@Autowired註解哪個罐子? – Weaveon

+0

@Weaveon答案已更新。 –