Spring @PathVariable问题

时间:2018-04-13 14:04:52

标签: java spring

我已经显示了ID为1的产品,它工作正常如果我投票一次,但如果我尝试再次在另一个帐户上投票,由于某种原因,路径变量增加到2

@RequestMapping(value = "/browse/display/{id}/vote", method = RequestMethod.POST)
public String voteProduct(@PathVariable(value = "id") final String id, @RequestParam(value = "vote") final String vote) {
 final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    final Account account = (Account) auth.getPrincipal();
    final ProductCommand product = productService.findProductCommandById(Long.valueOf(id));

    if(hasVoted(product, account)) {
        return "redirect:/browse/display/" + id;
    }

    final Long PRODUCT_RATING = product.getRating() + Long.valueOf(vote);
    final Long PRODUCT_RATING_VOTERS = product.getRatingVoters() + 1L;

    final ProductVotesCommand productVote = new ProductVotesCommand();

    productVote.setVote(Long.valueOf(vote));
    productVote.setAccountId(account.getId());
    productVote.setProductId(product.getId());
    product.getVotes().add(productVote);
    product.setRating(PRODUCT_RATING);
    product.setRatingVoters(PRODUCT_RATING_VOTERS);

    productService.saveProductCommand(recipe);

    return "redirect:/browse/display/" + id;
}

~~

@Override
public Product findById(Long productId) {
    Optional<Product> productOptional= productRepository.findById(productId);

    if(!productOptional.isPresent()) {
        throw new ProductNotFound("Product with the ID" + productId + " not found");
    }

    return productOptional.get();
}

~~

@Override
@Transactional
public ProductCommand findProductCommandById(Long productId) {


    return  productToProductCommand.convert(findById(productId));

}

~~

<form  id="vote5" th:action="@{'/browse/display/' + ${product.id} + '/vote'}" th:method="POST">
    <input id="vote" name="vote" type="hidden" value="5">
    <a>5</a>
    <button type="submit">Vote</button>
</form>

如果我尝试在另一个帐户上再次投票,我会得到这个

Unable to find com.vio.spring5.domain.Product with id 2; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.vio.spring5.domain.Product with id 2

0 个答案:

没有答案