簡體   English   中英

彈簧數據findById()可用於curl但不適用於瀏覽器

[英]spring data findById() works with curl but not with browser

我有一個音樂mysql數據庫,正在嘗試用spring數據訪問它。 到目前為止,我的控制器類中有三種方法: getAlbumByIdgetAllAlbumsgetAllArtists 最后兩個與curl 'localhost:8080/demo/allAlbums'curl 'localhost:8080/demo/allAlbums' curl 'localhost:8080/demo/allArtists' curl返回所有專輯和所有藝術家。 如果我使用Firefox瀏覽器,這些方法也可以使用。 使用curl 'localhost:8080/demo/oneAlbum/{1}'我得到的結果是ID為1到16的{"present":true} (我插入了16張專輯)。 對於ID 17,我得到的結果是: {"present":false}所以這似乎可行。 但是,當我在Firefox瀏覽器中放入'localhost:8080/demo/oneAlbum/{1}' ,會收到以下消息:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Sat Jan 20 11:08:48 CET 2018 There was an unexpected error (type=Internal Server Error, status=500). For input string: "{1}"

有人可以解釋為什么會這樣嗎?

而且,令我感到奇怪的是,如果我將@PathVariablegetAlbumById從String更改為Integer,curl的調用仍然有效,但是在瀏覽器中卻收到了一條不同的消息:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Sat Jan 20 11:38:18 CET 2018 There was an unexpected error (type=Bad Request, status=400). Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "{1}"

為什么curl通話仍然有效?

@Controller
@RequestMapping(path="/demo") 
public class MainController {

    @Autowired
    private AlbumRepository  mAlbumRepository;

    @Autowired
    private ArtistRepository  mArtistRepository;

    @GetMapping(path="/oneAlbum/{id}")
//  public @ResponseBody Optional<Album> getAlbumById(@PathVariable(value = "id") Integer id) {  
    public @ResponseBody Optional<Album> getAlbumById(@PathVariable(value = "id") String id) { 

        Integer i = Integer.parseInt(id);
        return mAlbumRepository.findById(i);
    }

    @GetMapping(path="/allAlbums")
    public @ResponseBody Iterable<Album> getAllAlbums() {
        return mAlbumRepository.findAll();
    }

    @GetMapping(path="/allArtists")
    public @ResponseBody Iterable<Artist> getAllArtists() {
        return mArtistRepository.findAll();
    }    
}


@NoRepositoryBean
public interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {
       Iterable<T> findAll();
       Optional<T> findById(ID id);
}


@Repository
public interface AlbumRepository extends ReadOnlyRepository<Album, Integer> {
     Iterable<Album> findAll();
     Optional<Album> findById(Integer id);
}

實際上,您不必在網址上加上花括號。

試試這個:

localhost:8080/demo/oneAlbum/1

另外,請為該ID使用整數而不是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM