JSF Bean在调用特定方法后不运行代码。

问题描述 投票:0回答:1

我有一个 commandButton,它调用了一个支持Bean内部的方法。这个Bean是 查看范围 并调用一个服务方法,该方法是 应用范围(里面调用了repository方法,将表单中的数据保存在数据库中)。现在service和repository方法运行正常,但是调用后的代码没有运行(比如日志和重定向)。

下面是支持Bean。

@Named
@ViewScoped
public class SubmitController implements Serializable {
    private static final Logger LOG = LoggerFactory.getLogger(SubmitController.class);

    private String userName;
    private String title;
    private String url;
    private String text;

    @Inject
    PostService postService;

    @PostConstruct
    void init() {
        LOG.info("Initialize SubmitController");
    }

    public void submitPost() throws IOException {
        long postID = this.postService.submitPost(this.userName, this.title, this.url, this.text);

        LOG.info("postID: {}", postID);

        FacesContext.getCurrentInstance()
                .getExternalContext()
                .redirect("item.xhtml");
    }
}

服务:

@Service
public class PostService {
    private static final Logger LOG = LoggerFactory.getLogger(PostService.class);

    @Inject
    PostRepository postRepository;

    public long submitPost(final String userName, final String title, final String url, final String text) throws IOException {
        Post post = Post.newPost()
                .withUser(new User(userName))
                .withTitle(new Title(title))
                .withUrl(new Url(url))
                .withText(new Text(text))
                .build();

        LOG.info("Submit post: {}", post.toString());

        this.postRepository.submitPost(post);

        Post refrence = this.postRepository.getRefrence(post);

        LOG.info("Refrence: {}", refrence.toString());

        return refrence.getId();
    }
}

和存储库。

@Repository
public class PostRepository {

    private static final Logger LOG = LoggerFactory.getLogger(PostRepository.class);

    @PersistenceContext(unitName = "default")
    EntityManager entityManager;

    public Post getRefrence(final Post post) {
        return this.entityManager.getReference(Post.class, post);
    }

    @Transactional
    public void submitPost(final Post post) {
        LOG.info("Save post");

        this.entityManager.persist(post);
    }
}

请注意,Repository和Service的注解是 应用范围.

是不是和范围有关,或者为什么后面的代码不在?long postID = this.postService.submitPost(this.userName, this.title, this.url, this.text); 运行?

jsf backing-beans
1个回答
0
投票

我没有添加 @Transactional 注解到 repository 方法。这解决了我的问题

© www.soinside.com 2019 - 2024. All rights reserved.