简体   繁体   English

如何从MVC控制器方法中的HTTP Post方法提取数据?

[英]How to extract data from a HTTP Post method in a MVC Controller Method?

I was trying to implement some client side logging for a web page that we are building. 我试图为我们正在构建的网页实施一些客户端日志记录。 The idea is to some specific error events on the client side, which would occur when some critical information is not being returned from the server side (the information on the page is aggregated from multiple services). 这个想法是针对客户端上的某些特定错误事件,当某些关键信息没有从服务器端返回时会发生(页面上的信息是从多个服务聚合的)。

On my client side Javascript, I have : 在我的客户端Javascript上,我有:

$.ajax({
  url: 'MyURL',
  type: 'POST',
  data: 'MyErrorMessage',
});

And on my server side controller, I want to have : 在我的服务器端控制器上,我想拥有:

@RequestMapping(value = "MyURL", method = RequestMethod.POST)
protected ModelAndView logErrorMessages(String errorMessage)
{
     /* Log the error message using the server side logging framework */
}

Now, I am not exactly sure how to access the error message string in the controller. 现在,我不确定如何在控制器中访问错误消息字符串。 I tried the above approach and the String was 'null'. 我尝试了上述方法,并且String为'null'。 One other approach I considered was to put the error message string into the request URL as a @RequestParam , as defined here : here . 我考虑的另一种方法是将错误消息字符串作为@RequestParam放入请求URL中,如此@RequestParam定义: here But I am slightly squeamish about doing that since, I have the feeling that messages should not really be a part of URL parameters. 但是由于这样做,我有点愧,因为我感到消息实际上不应成为URL参数的一部分。 I am sure I am missing something very obvious here (like creating a error message object as a part of the 'Model' or something similar), but my problem is that I am new to the MVC and Web development world and haven't looked at the Model/View code, only the 'Controller' code. 我确定我在这里遗漏了一些非常明显的东西(例如,将错误消息对象作为“模型”的一部分或类似内容创建),但是我的问题是我不熟悉MVC和Web开发领域,在“模型/视图”代码中,只有“控制器”代码。 Any tips which would put me on the right track are much appreciated. 我们将不胜感激任何能使我走上正轨的技巧。

Use the @ModelAttribute annotation: 使用@ModelAttribute批注:

client side 客户端

data: "error='System Error'" ... 数据:“错误='系统错误'” ...

server side 服务器端

logErrorMessage(@ModelAttribute(name="error") String errorMessage ... logErrorMessage(@ModelAttribute(name =“ error”)字符串errorMessage ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM