@RequestBody接收json对象报415的解决办法

前端请求:

$.ajax({
            url: basePath() + "/index/login.do",
            type : "post",
            data: JSON.stringify(form),
            dataType : "json",
            contentType : "application/json;charset=utf8",
            success: function (data) {
                console.log(data);
            },
            error: function () {

            }
        });

后端接收:

@ResponseBody
	@RequestMapping(value = "/login",method = RequestMethod.POST,produces = "application/json;charset=utf8")
	public JSONObject login(@RequestBody LoginVo loginVo){

		JSONObject result = new JSONObject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword());
		System.out.println(loginVo.isRememberMe());
		Subject subject = SecurityUtils.getSubject();
		subject.login(token);
		if (subject.isAuthenticated()){
			result.put("result",true);
		}else{
			result.put("result",false);
		}
		return result;
	}

前端ajax请求,后端使用@RequestBody接收,报出415请求数据格式错误

错误原因:springMVC无法读取ajax设置好的dataType并以对应的方式处理请求头,进而无法处理json数据

解决办法:在maven中引入Jackson相关jar包,并在springMVC的xml中引入相关配置,maven和springMVC的相关代码如下:

maven:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.6</version>
        </dependency>

springMVC:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- 设置返回字符串编码 -->
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name = "supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <!-- json转换器 -->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

 

发布了62 篇原创文章 · 获赞 16 · 访问量 5万+
展开阅读全文

@RequestBody 实体类接收不到数据,但是用com.alibaba.fastjson.JSONObject可以

09-09

``` @RequestMapping(value = "/getTest", method = {RequestMethod.POST}) public @ResponseBody CommonResponse getTest(@RequestBody TestForm form { ``` 后台这样写,使用postman测试 请求会直接报400, ``` <!doctype html> <html lang="en"> <head> <title>HTTP Status 400 – Bad Request</title> <style type="text/css"> h1 { font-family: Tahoma, Arial, sans-serif; color: white; background-color: #525D76; font-size: 22px; } h2 { font-family: Tahoma, Arial, sans-serif; color: white; background-color: #525D76; font-size: 16px; } h3 { font-family: Tahoma, Arial, sans-serif; color: white; background-color: #525D76; font-size: 14px; } body { font-family: Tahoma, Arial, sans-serif; color: black; background-color: white; } b { font-family: Tahoma, Arial, sans-serif; color: white; background-color: #525D76; } p { font-family: Tahoma, Arial, sans-serif; background: white; color: black; font-size: 12px; } a { color: black; } a.name { color: black; } .line { height: 1px; background-color: #525D76; border: none; } </style> </head> <body> <h1>HTTP Status 400 – Bad Request</h1> <hr class="line" /> <p><b>Type</b> Status Report</p> <p><b>Description</b> The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). </p> <hr class="line" /> <h3>Apache Tomcat/8.5.42</h3> </body> </html> ``` 如果后台改为 ``` public CommonResponse getTest(@RequestBody JSONObject jsonObject) { ``` 用JSONObject接收则没有问题,请各位大佬告知原因 问答

将RequestBody json转换为Object - Spring Boot

03-30

<div class="post-text" itemprop="text"> <p>I am a begineer in java development but has previous experience on programming languages like PHP and Python. So little confused on how to proceed on spring boot with the development.</p> <p>I am developing a rest API which has the following request</p> <pre><code>{ "key":"value", "key1":"value1", "platform_settings":[ {"key":"value"} ] } </code></pre> <p><strong>What I did</strong></p> <p>I created a RestController which accepts the http request and created a function for the resource</p> <pre><code>public Share share(@RequestBody final Share share) { LOGGER.debug("This is the request", share); return share; // } </code></pre> <p>Question 1 : If it was any other programming language like PHP or Python, there will be helper function which will accept the json request and convert it to object which I can easily work on.</p> <p>In python it is as simple as </p> <pre><code>import json import requests response = requests.get(...) json_data = json.loads(response.text) //can work on json_data anyway I want. </code></pre> <p>But in java, I will have to create a POJO class, or have jackson/JPA entity as dependency which will map the request to a Class (Which I should predefine with the requests).</p> <p>Is there any better way I can do this? For every request I make, I will have to create a Class which the request can be mapped to and I will have to define the class</p> <pre><code>Entity package com.payunow.socialsharemodule.models; import java.util.Map; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Share { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String key; private String key1; private Map<String,String> platform_settings; public Share(String name, String description,Map<String,String> platform_settings) { this.key = key; this.key1 = key1; this.platform_settings = platform_settings; } //for JPA public Share() {} public String getKey() { return key; } public String getKey1() { return key1; } public Map<String,String> getPlatform_settings() { return platform_settings; } } </code></pre> <p><strong>For every request I make, I will have to create a class defining all its variables inside. Is this the only way to do this?</strong></p> </div> 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览