我正在使用SpringFramework(STS)开发Web服务。我正在开展两个项目:webservice / backend和客户端(前端)。我的问题是,当我尝试将我的一个实体对象从服务器发送到客户端时,使用带参数的url,我在网页上得到错误400但控制台上没有错误。我可以毫无错误地传递一个对象列表但是当我需要它的实体时它不起作用。知道当我直接在后端调用URL时,我得到了我需要的数据。唯一的问题是将它们发送到前端。
这是代码服务器端:
我的实体: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);
}
}
答案 0 :(得分:0)
使用spring ModelAndView.addObject() method:
请尝试以下代码:
model.addObject("userProfile", this.uprofile);
而不是:
model.addAttribute("userProfile", this.uprofile);