错误405"请求方法' GET'不受支持"用于使用POST方法

时间:2016-03-05 01:01:18

标签: javascript spring rest post get

我尝试使用JS在本地主机上提交表单:

var PREFIX_URL = "http://localhost:8080/app-rest-1.0.0-SNAPSHOT";
var ADD_MODEL_URL="/model";
var modelId;
function addModel()
{
//   if (confirm ("Вы уверены, что хотите добавить эту модель?"))
//   {
        $.ajax(
        {
            type:'POST',
            contentType: 'application/json',
            url: PREFIX_URL+ADD_MODEL_URL,
            dataType: "json",
            data: formToJson(),
            success: function (jqXHR, textStatus, errorThrown)
            {
            alert('success!');
            window.close();
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
             alert('Некорректный ввод!');
            console.log('addModel error:' + textStatus + '\n' + errorThrown);
            }
        });
//   }
}

function formToJson()
{
    return JSON.stringify(
    {
    "modelName":$('#modelName').val()
//    "modelId": modelId.toString()
    });
}

但是获得405,尽管我使用POST方法提交它。我用Jetty检查了其余的并且有同样的错误,所以我认为问题不在JS中。但是我不知道如何检查Rest本身的POST。 这是我的RestController:

@RestController
public class ModelRestController
{
    private static final Logger LOGGER = LogManager.getLogger();

    @Autowired
    private ModelService modelService;

    @RequestMapping(value="/models", method = RequestMethod.GET)
    public @ResponseBody List<Model> getAllModels()
    {
        LOGGER.debug("Getting all models");
        return modelService.getAllModels();
    }

    @RequestMapping(value="/model", method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.CREATED)
    public @ResponseBody Integer addModel(@RequestBody Model model)
    {
        LOGGER.debug("Adding model modelName = {}", model.getModelName());
        return modelService.addModel(model);
    }

    @RequestMapping (value="/model/{modelId}/{modelName}", method=RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.ACCEPTED)
    public @ResponseBody void updateModel(@PathVariable(value="modelId") Integer modelId,
                                          @PathVariable(value="modelName") String modelName)
    {
        LOGGER.debug("Updating model modelId = {}", modelId);
        modelService.updateModel(new Model(modelId,modelName));
    }

    @RequestMapping (value="/model/{modelName}", method = RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public @ResponseBody void deleteModelByName(@PathVariable(value = "modelName") String modelName)
    {
        LOGGER.debug("Deleting model modelName= {}",modelName);
        modelService.deleteModelByName(modelName);
    }

    @RequestMapping (value="/modelsdto", method = RequestMethod.GET)
    @ResponseStatus(value = HttpStatus.OK)
    public @ResponseBody
    ModelDto getModelsDto()
    {
        LOGGER.debug("Getting models Dto");
        return modelService.getModelDto();
    }

}

我无法理解为什么错误说明了GET。添加模型的模拟测试成功:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:test-spring-rest-mock.xml"})
public class ModelRestControllerMockTest
{
    @Resource
    private ModelRestController modelRestController;

    @Autowired
    private ModelService modelService;

    private MockMvc mockMvc;

    @Before
    public void setUp()
    {
        mockMvc = standaloneSetup(modelRestController)
                .setMessageConverters(new MappingJackson2HttpMessageConverter())
                .build();
    }

    @After
    public void tearDown()
    {
        verify(modelService);
        reset(modelService);
    }

    @Test
    public void testAddModel() throws Exception
    {
        expect(modelService.addModel(anyObject(Model.class))).andReturn(3);
        replay(modelService);

        String model = new ObjectMapper().writeValueAsString(new Model(3, "Volvo"));
        mockMvc.perform(post("/model")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .content(model))
                .andDo(print())
                .andExpect(status().isCreated())
                .andExpect(content().string("3"));
    }

有人可以解释一下,出了什么问题?至于我正在查看名称相似的帖子,没有这样的情况。

0 个答案:

没有答案