GVKun编程网logo

这种在Spring中处理POST请求的REST方法如何工作?(spring resttemplate post)

14

对于想了解这种在Spring中处理POST请求的REST方法如何工作?的读者,本文将提供新的信息,我们将详细介绍springresttemplatepost,并且为您提供关于@Autowired注释在

对于想了解这种在Spring中处理POST请求的REST方法如何工作?的读者,本文将提供新的信息,我们将详细介绍spring resttemplate post,并且为您提供关于@Autowired注释在Spring中如何工作?、asp.net core webapi处理Post请求中的request payload、axios发送post请求springMVC无法接受参数如何处理、c# – .ToString()方法如何工作?的有价值信息。

本文目录一览:

这种在Spring中处理POST请求的REST方法如何工作?(spring resttemplate post)

这种在Spring中处理POST请求的REST方法如何工作?(spring resttemplate post)

我正在学习Spring Core认证,并且与在Spring MVC中进行RESTful webapp *的练习有关。

因此,在示例中,我具有以下创建新 Account 对象的方法

/** * Creates a new Account, setting its URL as the Location header on the * response. */@RequestMapping(value = "/accounts", method = RequestMethod.POST)@ResponseStatus(HttpStatus.CREATED)public HttpEntity<String> createAccount(@RequestBody Account newAccount,        @Value("#{request.requestURL}") StringBuffer url) {    Account account = accountManager.save(newAccount);    return entityWithLocation(url, account.getEntityId());}

我知道:

  1. *在这种情况下,@ *RequestMapping 批注指定此方法处理对 / accounts* 资源的 POST HttpRequest 。我知道它使用 POST 请求,因为根据REST风格,POST“动词”意味着必须创建一个新资源。 ***

  2. 我认为这个注释:

     @ResponseStatus(HttpStatus.CREATED)

表示当方法正确结束时(将 HttpResponse 发送到客户端时),它将 201CREATED
)放入HttpResponse状态字段。因此,它指定可以成功创建新对象。是真的还是我错过了什么?

  1. 该方法的第一个参数是:
    @RequestBody Account newAccount

在阅读文档时,在我看来,此参数已绑定到Web请求的正文中。请求的主体通过HttpMessageConverter传递,以根据请求的内容类型解析方法参数。

那么,到底是什么意思呢?我认为这意味着在HttpRequest 主体中
,我具有JSON格式的Account对象,并且使用Jackson将其转换为经典的 Account Java对象。是对的还是我错过了什么?

  1. 该方法的第二个参数是:

@Value(“#{request.requestURL}”)StringBuffer网址

到底是什么意思?

  1. 然后,该方法将获得的对象保存在数据库中。

  2. 最后它返回:

    return entityWithLocation(url, account.getEntityId());

但是到底是什么意思呢?什么回来了?在哪里?结果不是进入HttpResponse吗?

编辑1:

所述 entityWithLocation() 方法在同一类中的以前的方法的definied,这是它的代码:

private HttpEntity<String> entityWithLocation(StringBuffer url,        Object resourceId) {    // Configure and return an HttpEntity object - it will be used to build    // the HttpServletResponse    HttpHeaders headers = new HttpHeaders();    headers.setLocation(getLocationForChildResource(url, resourceId));    return new HttpEntity<String>(headers);}

答案1

小编典典

以下是我对您问题的理解。

  1. @RequestBody帐户newAccount

关于这一点,您的理解是正确的。

  1. @Value(“#{request.requestURL}”)StringBuffer网址

它等效于request.getRequestURL();
见API

  1. entityWithLocation(url,account.getEntityId())

根据此方法中的代码。它返回HttpEntityObject,它代表http请求或响应entity(which includes headers andbody),在您的情况下为response。里面的方法,你已经添加了locationresource(account)创建。

@Autowired注释在Spring中如何工作?

@Autowired注释在Spring中如何工作?

真正的问题是,为什么允许我通过以下两种方式编写此代码:

@Controller
public class PostController {
@Autowired 
private PostService postService;

@Autowired 
private CommentService commentService;

....
}

@Controller
public class PostController {

private PostService postService;
private CommentService commentService;

@Autowired 
public PostController(PostService postService,CommentService commentService){
    this.postService = postService;
    this.commentService = commentService;
}

....
}

这些摘要是否相同?推荐哪一个?

最佳答案
第一个解决方案通过反射直接注入值(基本上,JVM将获取您的对象并手动设置值).

第二种解决方案使用构造函数,这意味着该参数是必需的.另外,在将其自己分配给属性之前,您有时间使用所述值. (请注意,构造函数也将通过反射调用).

另一种方法是使用setter,这一次调用一个方法来设置值,这样您就可以在实际设置它之前对其进行操作,但这不是强制性的(因为它不是构造函数的一部分).

关于推荐的一个,我不确定实际上是否有一个“官方推荐的”,但是我倾向于只对强制字段使用构造函数注入而对非强制字段使用setter注入.但据我所知,这主要取决于您与之合作的团队或您的品味.

asp.net core webapi处理Post请求中的request payload

asp.net core webapi处理Post请求中的request payload

request payload的Content-Type实际上是text/plain的,如果请求的 Content-Type 为 application/json,这将导致415 Unsupported Media Type HTTP error。

有两个解决方法

1使用  application/json

Content-Type采用application/json并确保 request payload是有效的json格式,比如

1  {
2     "cookie": "value"
3 } 

Then the action signature needs to accept an object with the same shape as the JSON object.

创建实体作为接收参数

1 public class CookieWrapper
2 {
3     public string Cookie { get; set; }
4 }
5 
6 ...
7 
8 public IActionResult GetRankings([FromBody] CookieWrapper c)

 

或者使用dynamic、Dictionary
1 public IActionResult GetRankings([FromBody] dynamic c) 
2 
3 public IActionResult GetRankings([FromBody] Dictionary<string, string> c)

 

2使用 text/plain

客户端请求使用 Content-Type : text/plain,服务端添加TextPlainInputFormatter

 1 public class TextPlainInputFormatter : TextInputFormatter
 2 {
 3     public TextPlainInputFormatter()
 4     {
 5         SupportedMediaTypes.Add("text/plain");
 6         SupportedEncodings.Add(UTF8EncodingWithoutBOM);
 7         SupportedEncodings.Add(UTF16EncodingLittleEndian);
 8     }
 9 
10     protected override bool CanReadType(Type type)
11     {
12         return type == typeof(string);
13     }
14 
15     public override async Task<InputFormatterResult> ReadRequestBodyAsync(
16         InputFormatterContext context, 
17         Encoding encoding)
18     {
19         string data = null;
20         using (var streamReader = context.ReaderFactory(
21             context.HttpContext.Request.Body, 
22             encoding))
23         {
24             data = await streamReader.ReadToEndAsync();
25         }
26 
27         return InputFormatterResult.Success(data);
28     }
29 }
并在Startup.cs配置mvc
1 services.AddMvc(options =>
2 {
3     options.InputFormatters.Add(new TextPlainInputFormatter());
4 });

 

 

 翻译自https://stackoverflow.com/questions/41798814/asp-net-core-api-post-parameter-is-always-null

 

 

 

技术收录网站:核心技术(http://www.coretn.cn)

本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

 

axios发送post请求springMVC无法接受参数如何处理

axios发送post请求springMVC无法接受参数如何处理

这次给大家带来axios发送post请求springMVC无法接受参数如何处理,解决axios发送post请求springMVC无法接受参数的注意事项有哪些,下面就是实战案例,一起来看一下。

解决方法有以下三种:

1、设置axios的默认请求头

//设置全局的
axios.defaults.headers.post[''Content-Type''] = ''application/x-www-form-urlencoded'';
var instance = axios.create({}) // 这样创建出来的 只需要:
instance.defaults.headers.post[''Content-Type''] = ''application/x-www-form-urlencoded'';
登录后复制

2、使用URLSearchParams来构建参数

var params = new URLSearchParams();
params.append("username", _this.username);
params.append("password", _this.password);
axios.post("/service/login", paramsOfJson
   ).then(function (response) {
    console.log(response);
   }).catch(function (error) {
    console.log(error);
   })
登录后复制

3、后台使用@requestBody接收

@PostMapping(value = "/login")
public String testLogin(@RequestBody Map dataMap)
登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

node.js怎么通过axios实现网络请求

axios发送请求时springmvc无法接受参数

以上就是axios发送post请求springMVC无法接受参数如何处理的详细内容,更多请关注php中文网其它相关文章!

c# – .ToString()方法如何工作?

c# – .ToString()方法如何工作?

有时当我调用类的.ToString()方法时,它会返回类的完全限定名.但对于某些类的/ struct(如Int32),它返回一个字符串对应的对象(整数的值).这是否意味着Int32类重写了ToString()方法,并且返回完全限定名称的类不会覆盖它,而只是调用base(Object)的ToString()方法? Object.ToString()实现是否只返回类的完全限定名称?

解决方法

Sometimes when I call the ToString method it returns the fully qualified name of the runtime type of the object that received the call.

正确.

But for some types,such as system.int32,ToString returns the value of the receiver converted to a string.

正确.

Does the system.int32 struct override the ToString method?

是.

Do other types whose ToString methods return the fully-qualified type name not override ToString?

情况可能就是这样,是的.当然,他们可以覆盖该方法并使覆盖方法与基类方法完全相同,但这有点无意义.

So in those cases,calling ToString just calls the System.Object implementation of ToString,which returns fully qualified name?

正确.

你似乎已经掌握了它是如何工作的.我唯一的修正是要注意system.int32是一个结构,而不是一个类.

今天的关于这种在Spring中处理POST请求的REST方法如何工作?spring resttemplate post的分享已经结束,谢谢您的关注,如果想了解更多关于@Autowired注释在Spring中如何工作?、asp.net core webapi处理Post请求中的request payload、axios发送post请求springMVC无法接受参数如何处理、c# – .ToString()方法如何工作?的相关知识,请在本站进行查询。

本文标签: