繁体   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