当前位置: 首页 > 知识库问答 >
问题:

bean“name”的BindingResult和普通目标对象都不能作为请求属性使用

凌通
2023-03-14

我正在尝试使用Spring读取我在Twitter和Facebook上找到的状态,并将它们发布到SQLite数据库中。每当我尝试运行我的Spring项目时,我都会得到以下错误:

Neither BindingResult nor plain target object for bean name 'facebookModel' available as request attribute
model.addAttribute("facebookModel", new FacebookModel());
package adam.social.media.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.Post;
import org.springframework.social.facebook.api.impl.FacebookTemplate;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import adam.social.media.model.FacebookModel;
import adam.social.media.model.TwitterModel;
import adam.social.media.repository.FacebookRepository;
import adam.social.media.repository.TwitterRepository;

@Controller(value = "/socialmedia")
public class SocialMediaController {    

    private Facebook facebook;
    private Twitter twitter;

    private FacebookRepository facebookRepository;
    private TwitterRepository twitterRepository;

    private static Logger logger = Logger.getLogger(SocialMediaController.class
            .getName());

    @Autowired
    public SocialMediaController(FacebookRepository facebookRepository, TwitterRepository twitterRepository) {
        logger.debug("ENTERING SocialMediaController");

        this.facebookRepository = facebookRepository;               
        this.twitterRepository = twitterRepository;

        logger.debug("EXITING SocialMediaController");
    }

    @RequestMapping(value = "/facebook/get", method = RequestMethod.GET)
    public ModelAndView getFacebookStatus(FacebookModel facebookModel) {
        logger.debug("ENTERING getFacebookStatus");

        facebook = new FacebookTemplate("CAACEdEose0cBAJxfcf9xRQsL5un1WeEyIe2dy2xjI0EmuwzNbCWCPrTGwbsukRfQNb5ojQepPsMEjZAEXVwWfbYNA2fQO72kS3SPimt3ZCud4ykUZCoFkxZC6ks64dneZCNXLLJGRcqLeQ6DBPGwMrWtaSfi3W0zJLwDG1eu5FUsWJzgVZBwV4RmQvhhR4Yh0JfmyJSEU5am4L7rYJTUK0GtcYflhYlDMZD");                        

        ModelAndView modelAndView = new ModelAndView("index");      

//      PagedList<Post> posts = facebook.feedOperations().getFeed();        
//      for(Post post : posts) { System.out.println(post.getMessage()); }               

        Post post = facebook.feedOperations().getFeed().get(0);

        facebookModel.setPostId(post.getId());
//      facebookModel.setToProfile(post.getTo().get(0).getName());
        facebookModel.setToProfile("Hi");
        facebookModel.setFromProfile(post.getFrom().getName());
        facebookModel.setCreatedTime(post.getCreatedTime());
        facebookModel.setUpdatedTime(post.getUpdatedTime());
        facebookModel.setMessage(post.getMessage());
        facebookModel.setPictureUrl(post.getPicture());

        modelAndView.addObject("facebookModel", facebookModel);                 

        logger.debug("EXITING getFacebookStatus");

        return modelAndView;
    }

    @RequestMapping(value = "/twitter/get", method = RequestMethod.GET)
    public ModelAndView getTwitterStatus(TwitterModel twitterModel) {
        logger.debug("ENTERING getTwitterStatus");

        twitter = new TwitterTemplate("");                      

        ModelAndView modelAndView = new ModelAndView("index");      

//      PagedList<Post> posts = twitter.feedOperations().getFeed();     
//      for(Post post : posts) { System.out.println(post.getMessage()); }               

        Tweet tweet = twitter.timelineOperations().getHomeTimeline().get(0);

        twitterModel.setPostId(2);
        twitterModel.setFromProfile("3");
        twitterModel.setMessage("1");

        modelAndView.addObject("twitterModel", twitterModel);                   

        logger.debug("EXITING getTwitterStatus");

        return modelAndView;
    }

    @RequestMapping(value = "/facebook/post", method = RequestMethod.POST)
    public ModelAndView postFacebookStatus(FacebookModel facebookModel, BindingResult result) {
        logger.debug("ENTERING postFacebookStatus");        

        if (result.hasErrors()) {
            Map<String, Object> params = new HashMap<String, Object>();

            List<ObjectError> errors = result.getAllErrors();           

            params.put("facebookModel", facebookModel);         
            params.put("errors", errors);           

            return new ModelAndView("inddex", params);
        }   

        facebookRepository.saveAndFlush(facebookModel);

        logger.debug("EXITING postFacebookStatus");

        return new ModelAndView("redirect:/index.html");
    }

    @RequestMapping(value = "/twitter/post", method = RequestMethod.POST)
    public ModelAndView postTwitterStatus(TwitterModel twitterModel, BindingResult result) {
        logger.debug("ENTERING postTwitterStatus");     

        if (result.hasErrors()) {
            Map<String, Object> params = new HashMap<String, Object>();

            List<ObjectError> errors = result.getAllErrors();           

            params.put("twitterModel", twitterModel);           
            params.put("errors", errors);           

            return new ModelAndView("inddex", params);
        }   

        twitterRepository.saveAndFlush(twitterModel);

        logger.debug("EXITING postTwitterStatus");

        return new ModelAndView("redirect:/index.html");
    }
}
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<head>
    <title>Social Media</title>
</head>
<body>
    <form:form modelAttribute="facebookModel" method="POST" commandName="facebookModel">
        <form:hidden path="id" />   
        <form:hidden path="postId" />   
        <form:hidden path="toProfile" />    
        <form:hidden path="fromProfile" />  
        <form:hidden path="createdTime" />  
        <form:hidden path="updatedTime" />  
        <form:hidden path="message" />  
        <form:hidden path="pictureUrl" />   

        <button name="submit" type="submit" value="Save" style="background-color: rgba(255, 255, 255, 1); border: none; outline: none; cursor: pointer">
            <img src="<c:url value="images/facebook.png"/>" />
        </button>
    </form:form>

    <form:form modelAttribute="twitterModel" method="POST" commandName="twitterModel">  
        <form:hidden path="id" />   
        <form:hidden path="postId" />   
        <form:hidden path="toProfile" />    
        <form:hidden path="fromProfile" />  
        <form:hidden path="createdTime" />  
        <form:hidden path="updatedTime" />  
        <form:hidden path="message" />  
        <form:hidden path="pictureUrl" />   

        <button name="submit" type="submit" value="Save" style="background-color: rgba(255, 255, 255, 1); border: none; outline: none; cursor: pointer">
            <img src="<c:url value="images/twitter.png"/>" />
        </button>   
    </form:form>    
</body>
</body>

谢谢你,亚当·巴里

共有1个答案

李飞翼
2023-03-14

这是因为您试图在设置模型属性之前获取它。即。在getFacebookStatus方法中,您获得了FacebookModel,我没有看到您在此之前设置过它。解决方案是创建facebookmodel的新实例并将其设置为模型属性。基本上是这样的:

 @RequestMapping(value = "/facebook/get", method = RequestMethod.GET)
 public ModelAndView getFacebookStatus() {
        logger.debug("ENTERING getFacebookStatus");

        facebook = new FacebookTemplate("CAACEdEose0cBAJxfcf9xRQsL5un1WeEyIe2dy2xjI0EmuwzNbCWCPrTGwbsukRfQNb5ojQepPsMEjZAEXVwWfbYNA2fQO72kS3SPimt3ZCud4ykUZCoFkxZC6ks64dneZCNXLLJGRcqLeQ6DBPGwMrWtaSfi3W0zJLwDG1eu5FUsWJzgVZBwV4RmQvhhR4Yh0JfmyJSEU5am4L7rYJTUK0GtcYflhYlDMZD");                        

        ModelAndView modelAndView = new ModelAndView("index");      

//      PagedList<Post> posts = facebook.feedOperations().getFeed();        
//      for(Post post : posts) { System.out.println(post.getMessage()); }               

        Post post = facebook.feedOperations().getFeed().get(0);

        FacebookModel facebookModel = new FacebookModel();
        facebookModel.setPostId(post.getId());
//      facebookModel.setToProfile(post.getTo().get(0).getName());
        facebookModel.setToProfile("Hi");
        facebookModel.setFromProfile(post.getFrom().getName());
        facebookModel.setCreatedTime(post.getCreatedTime());
        facebookModel.setUpdatedTime(post.getUpdatedTime());
        facebookModel.setMessage(post.getMessage());
        facebookModel.setPictureUrl(post.getPicture());

        modelAndView.addObject("facebookModel", facebookModel);                 

        logger.debug("EXITING getFacebookStatus");

        return modelAndView;
    }

获取模型属性:

@RequestMapping(value = "/facebook/post", method = RequestMethod.POST)
public ModelAndView postFacebookStatus(@ModelAttribute("facebookModel") FacebookModel facebookModel, BindingResult result) {

    ....
}
 类似资料: