0
我使用SpringFramework(STS)開發web服務。我正在處理2個項目:webservice/backend和客戶端(前端)。我的問題是,當我嘗試從服務器發送一個實體對象到客戶端時,使用具有參數的url,我在網頁上收到錯誤400,但在控制檯上沒有錯誤。我得到沒有錯誤的對象列表,但當它的實體我需要它不起作用。知道當我直接在後端調用URL時,我得到了我需要的數據。唯一的問題是將它們發送到前端。Spring mvc從服務器發送實體到客戶端
下面的代碼服務器端:
我的實體:UserProfile.java
@Entity
@Table(name="user_profile")
public class UserProfile {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id", nullable = false)
private int id;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="id_user")
private User user;
@Column(name = "coverPhoto", nullable = false)
private String coverPhoto;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="id_modelLibrary")
private ModelLibrary modelLibrary;
@OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="id_shop")
private Shop shop;
public UserProfile(){}
public UserProfile(User user){
this.user = new User();
this.setCoverPhoto("");
this.setUser(user);
this.setModelLibrary(new ModelLibrary(user));
this.setShop(new Shop(user));
}
// Getters & setters
}
控制器(服務器端):UserProfileController.java
@RestController
public class UserProfileController {
private UserProfileService userProfileService;
// Recuperer les infos de session
@RequestMapping(value = "/getProfile/{id}", method = RequestMethod.GET)
public UserProfile getMyProfile(@PathVariable("id") String userId) {
Application.context = new ClassPathXmlApplicationContext("applicationContext.xml");
userProfileService = (UserProfileService) Application.context.getBean("userProfileService");
UserProfile userProfile = userProfileService.getUserProfileByUserId(userId);
System.out.println(userProfile.getUser().toString());
return userProfile;
}
}
而且現在的代碼客戶端: UserProfileController.java
@Controller
public class UserProfileController {
private UserProfileService uProfileService = new UserProfileServiceImpl();
private UserProfile uprofile;
@RequestMapping(value = "/myProfile", method = RequestMethod.GET)
public String getMyProfile(HttpSession session, Model model){
User user = (User) session.getAttribute("Sessionuser");
UserProfile uProfile = this.uProfileService.getUserProfileByUserId(user.getId());
this.uprofile = uProfile;
System.out.println("Get profile "+ uProfile.getUser().getUsername());
model.addAttribute("userProfile", this.uprofile);
return "myprofile";
}
}
(該UserProfileService只返回的DAO方法的結果,所以無需輸入。)
的UserProfileDAO.java(客戶端)
@Repository("userProfileDAO")
public class UserProfileDAOImpl implements UserProfileDAO{
@Override
public UserProfile getUserProfileByUserId(String user_id) {
return new RestTemplate().getForObject(WebService.getWebServiceUrl() + "getProfile/" + user_id, UserProfile.class);
}
}
謝謝你的回答。我嘗試過,但仍然無法正常工作。在調試後,我發現有問題來自 返回新的RestTemplate()。getForObject(WebService.getWebServiceUrl()+「getProfile /」+ user_id,UserProfile.class); '因爲我得到的錯誤彈出窗口之後,打印後不打印... – mika 2015-01-21 11:08:05
好吧,我沒有看到它,但addObject()是這樣做的最好方法,它工作正常爲了我。 – 2015-01-21 11:25:31