GVKun编程网logo

Spring Rest POST Json RequestBody内容类型不支持(springboot报错不支持post)

15

在本文中,我们将详细介绍SpringRestPOSTJsonRequestBody内容类型不支持的各个方面,并为您提供关于springboot报错不支持post的相关解答,同时,我们也将为您带来关于S

在本文中,我们将详细介绍Spring Rest POST Json RequestBody内容类型不支持的各个方面,并为您提供关于springboot报错不支持post的相关解答,同时,我们也将为您带来关于Spring MVC之@RequestBody, @ResponseBody 详解、@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别、@RequestMapping @ResponseBody 和 @RequestBody 用法与区别、@RequestMapping 和@ResponseBody 和 @RequestBody和@PathVariable 注解 注解用法的有用知识。

本文目录一览:

Spring Rest POST Json RequestBody内容类型不支持(springboot报错不支持post)

Spring Rest POST Json RequestBody内容类型不支持(springboot报错不支持post)

当我尝试使用post方法发布新对象时。RequestBody无法识别contentType。已经配置了Spring,并且POST可以与其他对象一起使用,但不能与特定对象一起使用。

org.springframework.web.HttpMediaTypeNotSupportedException: Content type ''application/json;charset=UTF-8'' not supported

如果我尝试相同的请求,只需更改requestbody对象。有用。

答案1

小编典典

我找到了解决方案。这是因为我有两个名字相同但类型不同的二传手。

我的班级有id属性int,在àHibernitify我的对象时,我将其替换为Integer。

但是很显然,我忘记删除二传手了,我有:

/** * @param id *            the id to set */public void setId(int id) {    this.id = id;}/** * @param id *            the id to set */public void setId(Integer id) {    this.id = id;}

当我删除此二传手时,其余请求工作效果很好。

引发抛出编组错误或反映类错误。异常HttpMediaTypeNotSupportedException接缝在这里真的很奇怪。

我希望这个stackoverflow可以对其他人有所帮助。

SIDE NOTE

你可以在Spring服务器控制台中检查以下错误消息:

无法评估类型[简单类型,类your.package.ClassName]的Jackson反序列化:com.fasterxml.jackson.databind.JsonMappingException:属性“ propertyname”的setter定义冲突

然后,你可以确定要解决上述问题。

<Spring>Spring MVC之@RequestBody, @ResponseBody 详解

Spring MVC之@RequestBody, @ResponseBody 详解

引言:

接上一篇文章讲述处理@RequestMapping的方法参数绑定之后,详细介绍下@RequestBody、@ResponseBody的具体用法和使用时机;

 

简介:

@RequestBody

作用: 

      i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;

      ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
  •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
  •     其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

B) PUT方式提交时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 必须;
  •     multipart/form-data, 不能处理;
  •     其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;

@ResponseBody

作用: 

      该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

      返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

 

 

HttpMessageConverter

[java] view plaincopy

  1. <span >/** 
  2.  * Strategy interface that specifies a converter that can convert from and to HTTP requests and responses. 
  3.  * 
  4.  * @author Arjen Poutsma 
  5.  * @author Juergen Hoeller 
  6.  * @since 3.0 
  7.  */  
  8. public interface HttpMessageConverter<T> {  
  9.   
  10.     /** 
  11.      * Indicates whether the given class can be read by this converter. 
  12.      * @param clazz the class to test for readability 
  13.      * @param mediaType the media type to read, can be {@code null} if not specified. 
  14.      * Typically the value of a {@code Content-Type} header. 
  15.      * @return {@code true} if readable; {@code false} otherwise 
  16.      */  
  17.     boolean canRead(Class<?> clazz, MediaType mediaType);  
  18.   
  19.     /** 
  20.      * Indicates whether the given class can be written by this converter. 
  21.      * @param clazz the class to test for writability 
  22.      * @param mediaType the media type to write, can be {@code null} if not specified. 
  23.      * Typically the value of an {@code Accept} header. 
  24.      * @return {@code true} if writable; {@code false} otherwise 
  25.      */  
  26.     boolean canWrite(Class<?> clazz, MediaType mediaType);  
  27.   
  28.     /** 
  29.      * Return the list of {@link MediaType} objects supported by this converter. 
  30.      * @return the list of supported media types 
  31.      */  
  32.     List<MediaType> getSupportedMediaTypes();  
  33.   
  34.     /** 
  35.      * Read an object of the given type form the given input message, and returns it. 
  36.      * @param clazz the type of object to return. This type must have previously been passed to the 
  37.      * {@link #canRead canRead} method of this interface, which must have returned {@code true}. 
  38.      * @param inputMessage the HTTP input message to read from 
  39.      * @return the converted object 
  40.      * @throws IOException in case of I/O errors 
  41.      * @throws HttpMessageNotReadableException in case of conversion errors 
  42.      */  
  43.     T read(Class<? extends T> clazz, HttpInputMessage inputMessage)  
  44.             throws IOException, HttpMessageNotReadableException;  
  45.   
  46.     /** 
  47.      * Write an given object to the given output message. 
  48.      * @param t the object to write to the output message. The type of this object must have previously been 
  49.      * passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}. 
  50.      * @param contentType the content type to use when writing. May be {@code null} to indicate that the 
  51.      * default content type of the converter must be used. If not {@code null}, this media type must have 
  52.      * previously been passed to the {@link #canWrite canWrite} method of this interface, which must have 
  53.      * returned {@code true}. 
  54.      * @param outputMessage the message to write to 
  55.      * @throws IOException in case of I/O errors 
  56.      * @throws HttpMessageNotWritableException in case of conversion errors 
  57.      */  
  58.     void write(T t, MediaType contentType, HttpOutputMessage outputMessage)  
  59.             throws IOException, HttpMessageNotWritableException;  
  60.   
  61. }  
  62. </span>  

该接口定义了四个方法,分别是读取数据时的 canRead(), read() 和 写入数据时的canWrite(), write()方法。

在使用 <mvc:annotation-driven />标签配置时,默认配置了RequestMappingHandlerAdapter(注意是RequestMappingHandlerAdapter不是AnnotationMethodHandlerAdapter,详情查看Spring 3.1 document “16.14 Configuring Spring MVC”章节),并为他配置了一下默认的HttpMessageConverter:

 

[java] view plaincopy

  1. ByteArrayHttpMessageConverter converts byte arrays.  
  2.   
  3. StringHttpMessageConverter converts strings.  
  4.   
  5. ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types.  
  6.   
  7. SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.  
  8.   
  9. FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.  
  10.   
  11. Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present on the classpath.  
  12.   
  13. MappingJacksonHttpMessageConverter converts to/from JSON — added if Jackson is present on the classpath.  
  14.   
  15. AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath.  
  16.   
  17. RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.  

 

ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;

StringHttpMessageConverter:   负责读取字符串格式的数据和写出二进制格式的数据;

 

ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据; 

FormHttpMessageConverter:       负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;

 

MappingJacksonHttpMessageConverter:  负责读取和写入json格式的数据;

 

SouceHttpMessageConverter:                   负责读取和写入 xml 中javax.xml.transform.Source定义的数据;

Jaxb2RootElementHttpMessageConverter:  负责读取和写入xml 标签格式的数据;

 

AtomFeedHttpMessageConverter:              负责读取和写入Atom格式的数据;

RssChannelHttpMessageConverter:           负责读取和写入RSS格式的数据;

 

当使用@RequestBody和@ResponseBody注解时,RequestMappingHandlerAdapter就使用它们来进行读取或者写入相应格式的数据。

 

HttpMessageConverter匹配过程:

@RequestBody注解时: 根据Request对象header部分的Content-Type类型,逐一匹配合适的HttpMessageConverter来读取数据;

spring 3.1源代码如下:

[java] view plaincopy

  1. <span >private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType)  
  2.             throws Exception {  
  3.   
  4.         MediaType contentType = inputMessage.getHeaders().getContentType();  
  5.         if (contentType == null) {  
  6.             StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType()));  
  7.             String paramName = methodParam.getParameterName();  
  8.             if (paramName != null) {  
  9.                 builder.append('' '');  
  10.                 builder.append(paramName);  
  11.             }  
  12.             throw new HttpMediaTypeNotSupportedException(  
  13.                     "Cannot extract parameter (" + builder.toString() + "): no Content-Type found");  
  14.         }  
  15.   
  16.         List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();  
  17.         if (this.messageConverters != null) {  
  18.             for (HttpMessageConverter<?> messageConverter : this.messageConverters) {  
  19.                 allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());  
  20.                 if (messageConverter.canRead(paramType, contentType)) {  
  21.                     if (logger.isDebugEnabled()) {  
  22.                         logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType  
  23.                                 +"\" using [" + messageConverter + "]");  
  24.                     }  
  25.                     return messageConverter.read(paramType, inputMessage);  
  26.                 }  
  27.             }  
  28.         }  
  29.         throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);  
  30.     }</span>  

@ResponseBody注解时: 根据Request对象header部分的Accept属性(逗号分隔),逐一按accept中的类型,去遍历找到能处理的HttpMessageConverter;

源代码如下:

[java] view plaincopy

  1. <span >private void writeWithMessageConverters(Object returnValue,  
  2.                 HttpInputMessage inputMessage, HttpOutputMessage outputMessage)  
  3.                 throws IOException, HttpMediaTypeNotAcceptableException {  
  4.             List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();  
  5.             if (acceptedMediaTypes.isEmpty()) {  
  6.                 acceptedMediaTypes = Collections.singletonList(MediaType.ALL);  
  7.             }  
  8.             MediaType.sortByQualityValue(acceptedMediaTypes);  
  9.             Class<?> returnValueType = returnValue.getClass();  
  10.             List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();  
  11.             if (getMessageConverters() != null) {  
  12.                 for (MediaType acceptedMediaType : acceptedMediaTypes) {  
  13.                     for (HttpMessageConverter messageConverter : getMessageConverters()) {  
  14.                         if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {  
  15.                             messageConverter.write(returnValue, acceptedMediaType, outputMessage);  
  16.                             if (logger.isDebugEnabled()) {  
  17.                                 MediaType contentType = outputMessage.getHeaders().getContentType();  
  18.                                 if (contentType == null) {  
  19.                                     contentType = acceptedMediaType;  
  20.                                 }  
  21.                                 logger.debug("Written [" + returnValue + "] as \"" + contentType +  
  22.                                         "\" using [" + messageConverter + "]");  
  23.                             }  
  24.                             this.responseArgumentUsed = true;  
  25.                             return;  
  26.                         }  
  27.                     }  
  28.                 }  
  29.                 for (HttpMessageConverter messageConverter : messageConverters) {  
  30.                     allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());  
  31.                 }  
  32.             }  
  33.             throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);  
  34.         }</span>  

 

补充:

MappingJacksonHttpMessageConverter 调用了 objectMapper.writeValue(OutputStream stream, Object)方法,使用@ResponseBody注解返回的对象就传入Object参数内。若返回的对象为已经格式化好的json串时,不使用@RequestBody注解,而应该这样处理:
1、response.setContentType("application/json; charset=UTF-8");
2、response.getWriter().print(jsonStr);
直接输出到body区,然后的视图为void。

@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别

@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别

1.@RequestMapping

国际惯例先介绍什么是@RequestMapping,@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法,此处需注意@RequestMapping用在类上可以没用,但是用在方法上必须有。

@RequestMapping("/verifyCode")
    public void verifyCode(HttpServletResponse response, HttpSession session){
        response.setDateHeader("Expires", -1);
        response.setHeader("Cache-Control", "no-cache");

        VerifyCode vc = new VerifyCode();
        try {
            vc.drawImage(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String code = vc.getCode();
        session.setAttribute("code", code);
        System.out.println(code);

    }

 

2.@ResponseBody

@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。 
作用: 
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。 
使用时机: 
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;


@ResponseBody
public void activeUser(String userId, String activecode, HttpServletResponse response){
userInfoService.activeUser(userId, activecode);
// 定时刷新
response.setContentType("text/html;charset=utf-8");
try {
response.getWriter().write("激活成功,3秒之后回到登录界面进行登录...");
response.setHeader("refresh", "3;url=/login");

} catch (IOException e) {
e.printStackTrace();
}
}

3.@RequestBody

@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。

作用:

1) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上; 
2) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

@RequestMapping @ResponseBody 和 @RequestBody 用法与区别

@RequestMapping @ResponseBody 和 @RequestBody 用法与区别

1.@RequestMapping

国际惯例先介绍什么是@RequestMapping,@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法,此处需注意@RequestMapping用在类上可以没用,但是用在方法上必须有

例如:

@Controller
//设置想要跳转的父路径
@RequestMapping(value = "/Controllers")
public class StatisticUserCtrl {
    //如需注入,则写入需要注入的类
    //@Autowired

            // 设置方法下的子路经
            @RequestMapping(value = "/method")
            public String helloworld() {

                return "helloWorld";

            }
}

原理也非常好了解,其对应的 action 就是“ (父路径) controller/(父路径下方法路经)method ”。因此,在本地服务器上访问方法 http://localhost:8080/controller/method 就会返回(跳转)到“ helloWorld.jsp ”页面。

说到这了,顺便说一下 @PathVariable 注解,其用来获取请求路径(url )中的动态参数。

页面发出请求:

function login() {
    var url = "${pageContext.request.contextPath}/person/login/";
    var query = $(''#id'').val() + ''/'' + $(''#name'').val() + ''/'' + $(''#status'').val();
    url += query;
    $.get(url, function(data) {
        alert("id: " + data.id + "name: " + data.name + "status: "
                + data.status);
    });
}

如:

/**
* @RequestMapping(value = "user/login/{id}/{name}/{status}") 中的 {id}/{name}/{status}
* 与 @PathVariable int id、@PathVariable String name、@PathVariable boolean status
* 一一对应,按名匹配。
*/

@RequestMapping(value = "user/login/{id}/{name}/{status}")
@ResponseBody
//@PathVariable注解下的数据类型均可用
public User login(@PathVariable int id, @PathVariable String name, @PathVariable boolean status) {
//返回一个User对象响应ajax的请求
    return new User(id, name, status);
}

ResponseBody

@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。 
作用: 
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。 
使用时机: 
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

当页面发出异步请求:

function login() {
    var datas = ''{"username":"'' + $(''#username'').val() + ''","userid":"'' + $(''#userid'').val() + ''","status":"'' + $(''#status'').val() + ''"}'';
    $.ajax({
        type : ''POST'',
        contentType : ''application/json'',
        url : "${pageContext.request.contextPath}/user/login",
        processData : false,
        dataType : ''json'',
        data : datas,
        success : function(data) {
            alert("userid: " + data.userid + "username: " + data.username + "status: "+ data.status);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert("出现异常,异常信息:"+textStatus,"error");
        }
    });
};

如:

@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中,返回json对象响应回去
public User login(User user) {   
    User user = new User();
    user .setUserid(1);
    user .setUsername("MrF");
    user .setStatus("1");
    return user ;
}

步获取 json 数据,加上 @Responsebody 注解后,就会直接返回 json 数据。

@RequestBody

@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。

作用:

1) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上; 
2) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:

application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理); 
multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据); 
其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

B) PUT方式提交时, 根据request header Content-Type的值来判断:

application/x-www-form-urlencoded, 必须;multipart/form-data, 不能处理;其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;

例如:

@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中
public User login(@RequestBody User user) {   
// 这样就不会再被解析为跳转路径,而是直接将user对象写入 HTTP 响应正文中
    return user;    
}

@RequestMapping 和@ResponseBody 和 @RequestBody和@PathVariable 注解 注解用法

@RequestMapping 和@ResponseBody 和 @RequestBody和@PathVariable 注解 注解用法

接下来讲解一下 @RequestMapping  和@ResponseBody 和 @RequestBody和@PathVariable 注解 注解用法

@RequestMapping 为url映射路径

@ResponseBody  将数据以json数据返回ajax的回掉方法

@RequestBody  将url的参数以实体形式传入action

@PathVariable 注解  分解resultful的风格

jsp源码

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-1.5.js"></script>
<script type="text/javascript">

function findStudentInfo() {
debugger
$.ajax({
type:"get",
url:"${pageContext.request.contextPath}/getemps",
dataType:"json",
success : function (data) {
debugger
$("#showMessageDiv").empty();
$("#showMessageDiv").append("<table id=''table1''></table>");
$("#table1").append("<tr><td>员工ID</td><td>姓名</td><td>性别</td><td>邮箱地址</td></tr>");
$.each(data,function (i,result) {
var sex="女"
if (result.gender==1){sex="男"}
var item="<tr><td>"+result.id+"</td><td>"+result.lastName+"</td><td>"+sex+"</td><td>"+result.email+"</td>";
$("#table1").append(item);
});

},
error:function(){
alert("错误");
}
});
}

function findStudentInfo1() {
debugger
var datas =''{"id":" 1","email":"123@11.com "}'';
$.ajax({
type : ''POST'',
contentType : ''application/json'',
url : "${pageContext.request.contextPath}/getemps1",
dataType : ''json'',
data : datas,
success : function(data){
$("#showMessageDiv").empty();
$("#showMessageDiv").append("<table id=''table1''></table>");
$("#table1").append("<tr><td>员工ID</td><td>姓名</td><td>性别</td><td>邮箱地址</td></tr>");
var sex="女"
if (data.gender==1){sex="男"}
var item="<tr><td>"+data.id+"</td><td>"+data.lastName+"</td><td>"+sex+"</td><td>"+data.email+"</td>";
$("#table1").append(item);
},
error : function()
{
alert(''Sorry, it is wrong!'');
}
});
}
function findStudentInfo2() {
debugger
var datas =''{"id":" 1","email":"jerry1@atguigu.com"}'';
$.ajax({
contentType : ''application/json'',
type : ''POST'',
url:"${pageContext.request.contextPath}/getemps2",
dataType:"json",
data : datas,
success : function (data) {
debugger
$("#showMessageDiv").empty();
$("#showMessageDiv").append("<table id=''table1''></table>");
$("#table1").append("<tr><td>员工ID</td><td>姓名</td><td>性别</td><td>邮箱地址</td></tr>");
$.each(data,function (i,result) {
var sex="女"
if (result.gender==1){sex="男"}
var item="<tr><td>"+result.id+"</td><td>"+result.lastName+"</td><td>"+sex+"</td><td>"+result.email+"</td>";
$("#table1").append(item);
});

},
error:function(){
alert("错误");
}
});
}
function findStudentInfo3() {
debugger
$.ajax({
type : ''POST'',
contentType : ''application/json'',
url : "${pageContext.request.contextPath}/getemps3?id=1",
dataType : ''json'',
success : function(data){
$("#showMessageDiv").empty();
$("#showMessageDiv").append("<table id=''table1''></table>");
$("#table1").append("<tr><td>员工ID</td><td>姓名</td><td>性别</td><td>邮箱地址</td></tr>");
var sex="女"
if (data.gender==1){sex="男"}
var item="<tr><td>"+data.id+"</td><td>"+data.lastName+"</td><td>"+sex+"</td><td>"+data.email+"</td>";
$("#table1").append(item);
},
error : function()
{
alert(''Sorry, it is wrong!'');
}
});
}
function findStudentInfo4() {
debugger
$.ajax({
type : ''POST'',
contentType : ''application/json'',
url : "${pageContext.request.contextPath}/testPathVariable/4",
dataType : ''json'',
success : function(data){
$("#showMessageDiv").empty();
$("#showMessageDiv").append("<table id=''table1''></table>");
$("#table1").append("<tr><td>员工ID</td><td>姓名</td><td>性别</td><td>邮箱地址</td></tr>");
var sex="女"
if (data.gender==1){sex="男"}
var item="<tr><td>"+data.id+"</td><td>"+data.lastName+"</td><td>"+sex+"</td><td>"+data.email+"</td>";
$("#table1").append(item);
},
error : function()
{
alert(''Sorry, it is wrong!'');
}
});
}
</script>
<body>

<div id="showMessageDiv">
</div>
<div id="data">
<input type="button" value="返回list" onclick="findStudentInfo()"/>
<input type="button" value="返回实体以RequestBody接受参数" onclick="findStudentInfo1()"/>
<input type="button" value="返回list以RequestBody接受参数" onclick="findStudentInfo2()"/>
<input type="button" value="返回实体以Requestparam接受参数" onclick="findStudentInfo3()"/>
<input type="button" value="返回实体以testPathVariable接受参数" onclick="findStudentInfo4()"/>
</div>
</body>
</html>

2 action源码

package com.atguigu.mybatis.controller;

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.mybatis.bean.Employee;
import com.atguigu.mybatis.service.EmployeeService;

@Controller
public class EmployeeController {

@Autowired
EmployeeService employeeService;

@RequestMapping("/getemps")
@ResponseBody
public String empsList() throws JsonGenerationException, JsonMappingException, IOException{
List<Employee> emps = employeeService.getEmps();
ObjectMapper mapper= new ObjectMapper();
String jsonStr = mapper.writeValueAsString(emps );
return jsonStr;
}
@RequestMapping("/getemps1")
@ResponseBody
public Employee emps(@RequestBody Employee e) throws JsonGenerationException, JsonMappingException, IOException{
Employee e1=employeeService.getEmpById(e.getId());
return e1;
}

@RequestMapping("/getemps2")
@ResponseBody
public String empsListbyemail(@RequestBody Employee e) throws JsonGenerationException, JsonMappingException, IOException{
List<Employee> emps = employeeService.getEmpByemail(e.getEmail());
ObjectMapper mapper= new ObjectMapper();
String jsonStr = mapper.writeValueAsString(emps );
return jsonStr;
}

@RequestMapping("/getemps3")
@ResponseBody
public Employee emps(@RequestParam(value = "id") Integer id) throws JsonGenerationException, JsonMappingException, IOException{
Employee e1=employeeService.getEmpById(id);
return e1;
}
@RequestMapping("/testPathVariable/{id}")
@ResponseBody
public Employee testPathVariableemps(@PathVariable("id") Integer id) throws JsonGenerationException, JsonMappingException, IOException{
Employee e1=employeeService.getEmpById(id);
return e1;
}
}

关于Spring Rest POST Json RequestBody内容类型不支持springboot报错不支持post的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Spring MVC之@RequestBody, @ResponseBody 详解、@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别、@RequestMapping @ResponseBody 和 @RequestBody 用法与区别、@RequestMapping 和@ResponseBody 和 @RequestBody和@PathVariable 注解 注解用法的相关信息,请在本站寻找。

本文标签: