在jquery ajax上的Http状态404(Not Found)GET到弹簧控制器?

时间:2014-07-26 18:55:38

标签: java jquery ajax spring-mvc

我的spring控制器包含这样的get处理程序:

@RequestMapping(value = "/country", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody List<Region> getRegionsFor(@RequestParam(value = "countryName") String countryName,
            @RequestParam(value = "geonameId") Long geonameId) {
        logger.debug("fetching regions for {}, with geonameId {}", countryName, geonameId);
        RegionInfo regionInfo = restTemplate.getForObject(
                "http://api.geonames.org/childrenJSON?geonameId={geonameId}&username=geonameUser2014",
                RegionInfo.class, geonameId);
        return regionInfo.getRegions();
    }

@Controller已映射到/hostel。所以网址为/hostel/country?countryName=%27&Albania%27&&geonameId=783754

当我输入Chrome浏览器时

http://localhost:8080/HostMe/hostel/country?countryName=%27Albania%27&geonameId=783754

按预期返回json响应!!!

但我想通过以下使用jquery进行的ajax调用来访问此URL:

 $.ajax({
            headers : {
                'Accept' : 'application/json'                   
            },
            url : '/hostel/country',
            dataType : 'json',
            data : {countryName:"Albania",geonameId:783754},
            type : 'GET',
            async : true,
            success : function(response) {
                console.log("response=" + response.join(','));
            },
            error : function(errorData) {
                console.log("data on fail ");
                printObject(errorData);
            }
            });

你猜这根本不起作用。 Http状态404(未找到)返回到error:处理程序。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

ajax调用中的url是相对于主机名的。您需要添加Web应用程序上下文

url : '/HostMe/hostel/country',