org.springframework.web.servlet.PageNotFound.handleHttpRequestMethodNotSupported请求方法' GET'不支持

时间:2016-09-03 08:00:03

标签: javascript java jquery ajax spring-mvc

我正在尝试使用AJAX异步与服务器通信。但是,我收到以下错误消息,任何想法?:

  

org.springframework.web.servlet.PageNotFound.handleHttpRequestMethodNotSupported   请求方法' GET'不支持

控制器:

package com.math.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PiCalculatorController {
    @RequestMapping(value = "/picalculator", method = RequestMethod.GET)
    public @ResponseBody String piCalculator(@RequestParam(value = "precision") int pr, @RequestParam(value = "decimals") int de) {
        return String.valueOf(pr * de);
    }
}

使用Javascript:

var getPiCalculation;
$(document).ready(function () {
    getPiCalculation = function () {
        if ($('#precision').val() != '' || $('#decimals').val() != '') {
            $.getJSON(
                "picalculator",
                {
                    precision: $('#precision').val(),
                    decimals: $('#decimals').val()
                },
                function (data) {
                    alert("response received: " + data);
                }
            );
        } else {
            alert("Both fields need to be populated!!");
        }
    };

接头:

enter image description here

1 个答案:

答案 0 :(得分:0)

我刚刚在标题截图中看到,响应内容类型设置为text / html。这需要设置为application / json。

解决方案:

需要添加@RequestMapping:

  

produce =“application / json”

因此需要按如下方式更改控制器。

控制器:

package com.math.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PiCalculatorController {
    @RequestMapping(value = "/picalculator", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody String piCalculator(@RequestParam(value = "precision") int pr, @RequestParam(value = "decimals") int de) {
        return String.valueOf(pr * de);
    }
}

在此之后,您将在标题中获得以下内容:

enter image description here