2

Hello all i am trying to post a form using angular but i am getting null values in my spring controller.Also in my console i see null values for the sysout.Moreover i get an error alert even though i see bull is printed on my console.

My JS Controller

angular.module('ngMailChimp', ['ngAria', 'ngMessages', 'ngAnimate'])
.controller('SignUpController', function ($scope, $http) {
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
    var ctrl = this,
        newCustomer = { firstName:'',lastName:'',email:'',streetName:'',aptName:'',cityName:'',stateName:'',countryName:'', zipName:'', userName:'',password:'' };

    var signup = function () {
        if( ctrl.signupForm.$valid) {
            ctrl.showSubmittedPrompt = true;
            var formData = {
                    'firstName' : $scope.ctrl.newCustomer.firstName,
                    'lastName' : $scope.ctrl.newCustomer.lastName,
                    'email' : $scope.ctrl.newCustomer.email,
                    'streetName' : $scope.ctrl.newCustomer.streetName,
                    'aptName' : $scope.ctrl.newCustomer.aptName,
                    'cityName' : $scope.ctrl.newCustomer.cityName,
                    'stateName' : $scope.ctrl.newCustomer.stateName,
                    'countryName' : $scope.ctrl.newCustomer.countryName,
                    'zipName' : $scope.ctrl.newCustomer.zipName,
                    'userName' : $scope.ctrl.newCustomer.userName,
                    'password' : $scope.ctrl.newCustomer.password
            };

            var response = $http.post('http://localhost:8080/Weber/user/save', JSON.stringify(formData));
            response.success(function(data, status, headers, config) {
                $scope.list.push(data);
            });
            response.error(function(data, status, headers, config) {
                alert( "Exception details: " + JSON.stringify({data: data}));
            });

        }
    };

My Spring controller

@RestController
@RequestMapping(value = "/user")
public class UserRegistrationControllerImpl implements UserRegistrationController  {

@Autowired
UserRegistrationDao userDao;

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(UserRegistration userReg) {
    System.out.println(userReg.getFirstName()+" "+userReg.getLastName());
    userDao.registerUser(userReg);
    return "success";
}

Please help me out

Thank you mark.

2 Answers 2

1

There is no mapper specified for converting JSON to Java object.

Use Jackson(dore, databind, annotations) if you want the JSON to be converted to object of UserRegistration.

Check this out: Convert nested java objects to Jackson JSON

Need to add below in dispatcher-servlet. This is for mapping the JSON to Java objects:

<beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

EDIT 1: Is the method in controller something like this?

@RequestMapping(value = "/save", method = RequestMethod.POST, headers = "Accept=application/json")
public String saveUser(@RequestBody UserRegistration userReg) {
    System.out.println(userReg.getFirstName()+" "+userReg.getLastName());
    userDao.registerUser(userReg);
    return "success";
}

Use above if you are not responding back to the webpage with a result to be consumed. If you want something to be returned from this method and displayed in the webpage or consumed elsewhere, the declaration of method would change to:

public @ResponseBody String saveUser(@RequestBody UserRegistration userReg)

EDIT 2:

    $scope.post = function() {
        $scope.data = null;
        $http({
            method : 'POST',
            url : 'save',
            params : {
            firstName : $scope.ctrl.newCustomer.firstName,
            lastName : $scope.ctrl.newCustomer.lastName,
            email : $scope.ctrl.newCustomer.email,
            streetName : $scope.ctrl.newCustomer.streetName,
            aptName : $scope.ctrl.newCustomer.aptName,
            cityName : $scope.ctrl.newCustomer.cityName,
            stateName : $scope.ctrl.newCustomer.stateName,
            countryName : $scope.ctrl.newCustomer.countryName,
            zipName : $scope.ctrl.newCustomer.zipName,
            userName : $scope.ctrl.newCustomer.userName,
            password : $scope.ctrl.newCustomer.password
            }
        }).success(function(data, status, headers, config) {
             $scope.list.push(data); 
        }).error(function(data, status, headers, config) {
            alert("Exception");
        });
    };
Sign up to request clarification or add additional context in comments.

8 Comments

but the response i am getting is null in all the fields
when i put something like you suggested as the 1st edit it throws me "The request sent by the client was syntactically incorrect". For the second one also when i try to call it form my angular i mean when i try to post something using my angularjs the same error is showing up
@mark Since the error is "The request sent by the client was syntactically incorrect", it means the request sent is not of a proper JSON format. I have an inkling to why this might be. The parameters in formData are inside single quotes. Remove them and try. I have updated something that I normally use in EDIT2.
I tried that but again it throws me an error "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method".More over i tried to use log and it shows me following error.."org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported.". I am using jackson-binding jar to deserialize json
@mark I think there is something missing in your JSON. The Class is maybe expecting 10 variables whereas you are trying to pass less number of them. If the Class has 10 variables and if the request at all times does not have 10 variables, then you will need to use the annotation @JsonIgnoreProperties(ignoreUnknown = true) on the class.
|
0

Try add @RequestBody in the method arguments:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(@RequestBody UserRegistration userReg) {
    System.out.println(userReg.getFirstName()+" "+userReg.getLastName());
    userDao.registerUser(userReg);
    return "success";
}

2 Comments

It still gives me null value.
Yes,when i did that it says client request is syntactically not correct. { "lastName": "mark", "firstName": "k", "email": "[email protected]", "streetName": "abc", "aptName": "12", "city": "fremont ", "state": "CA", "country": "USA", "zip": "95747", "userName": "Mark6656", "password": "Mark" }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.