Issue
I am completly new to spring boot. I am now trying to pass a registration form data(json format) from vue frontend to spring boot backend, but the backend always show the receiving data is null. How should I correctly receive the data?
RegistrationController.java
package com.example.demo.controller;
import com.example.demo.result.Result;
import com.example.demo.pojo.newUser;
//import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class RegistrationController {
@CrossOrigin
@PostMapping(value = "api/registration")
@ResponseBody
public Result registration(@RequestBody NewUser user) {
System.out.println("###CompanyName: "+ user.getCompanyName());
return new Result(200);
}
}
NewUser.java
package com.example.demo.pojo;
public class NewUser {
private String CompanyName;
public String getCompanyName() {
return CompanyName;
}
public void setCompanyName(String CompanyName) {
this.CompanyName = CompanyName;
}
}
Registration.vue
<template>
<Form @submit="onSubmit" :validation-schema="schema">
<span class="lblMandatory">* </span><span class="lblExplanatoryNote">This is a mandatory field and data must be provided.</span>
<div class="form-group">
<span class="lblSectionField">Company Name <span class="lblMandatory">*</span></span>
<Field name="CompanyName" class="form-control"/>
<ErrorMessage name="CompanyName" class="ErrorMessage"/>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</Form>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
}
},
methods: {
onSubmit(values) {
axios.post('registration', values)
.then(successResponse => {
console.log(successResponse.data.code)
console.log(values)
if (successResponse.data.code === 200) {
alert("application success")
this.$router.replace({name: 'home'})
}
else{
alert("application failed")
}
})
.catch(failResponse => {
console.log(failResponse)
})
}
}
}
</script>
But in my spring boot backend terminal it shows: ###CompanyName: null
I edit the code shorter which only contain company name, which is still null. result
Solution
Try logging your json object before you send it, from there make sure the field name can be mapped to your request dto pojo class, spring boot serialize json object with camel case strategy so if your json body is different, spring will not be able to parse the json body into your pojo class.
Also if you are trying to create rest api endpoints you should use @RestController instead of @Controller annotation.
Here is reference link about Spring @Controller and @RestController Annotations
Your pojo class also not following the java naming conventions, please refer to this link for further information.
Answered By - Aleson
Answer Checked By - Cary Denson (JavaFixing Admin)