前台请求后台用@RequestBody接收数据

2023年2月2日12:29:31

 请求示例:将传输的对象JSON.stringify()

JSON.stringify() 表示从一个对象中解析出字符串

    $.ajax({
      url: "http://localhost:8201/search",
      type: "post",
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      data: JSON.stringify({key: keyword})
    }).success(function (res) {
      console.log(res)
    })

接收样例:

	@RequestMapping(value = "/search",method = RequestMethod.POST)
	@ResponseBody
	public List<Product> search(@RequestBody SearchRequestDTO searchRequestDTO){
		List<Product> products =  searchService.search(searchRequestDTO);
		logger.info("商品数量{},商品信息{}",products.size(),products.toString());
		return products;
	}

其中DTO类:

package com.goods.search.api.DTO;

import java.io.Serializable;

public class SearchRequestDTO implements Serializable {

	private String key;

	/**
	 * 获取key
	 *
	 * @return key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * 设置key
	 *
	 * @param key key
	 */
	public void setKey(String key) {
		this.key = key;
	}

	public SearchRequestDTO() {
	}

	public SearchRequestDTO(String key) {
		this.key = key;
	}
}

 

  • 作者:c&0xff00
  • 原文链接:https://crazy-snail.blog.csdn.net/article/details/86678039
    更新时间:2023年2月2日12:29:31 ,共 872 字。