【问题标题】:AngularJs form post data giving null values in my spring controllerAngularJs 表单发布数据在我的 spring 控制器中给出空值
【发布时间】:2017-02-11 23:01:29
【问题描述】:

大家好,我正在尝试使用 angular 发布表单,但我在 spring 控制器中得到空值。此外,在我的控制台中,我看到 sysout 的空值。此外,即使我看到打印了公牛,我也会收到错误警报在我的控制台上。

我的 JS 控制器

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}));
            });

        }
    };

我的 Spring 控制器

@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";
}

请帮帮我

谢谢 标记。

【问题讨论】:

    标签: javascript angularjs spring spring-mvc null


    【解决方案1】:

    没有指定将 JSON 转换为 Java 对象的映射器。

    如果您希望将 JSON 转换为 UserRegistration 的对象,请使用 Jackson(dore, databind, annotations)。

    看看这个:Convert nested java objects to Jackson JSON

    需要在dispatcher-servlet下面添加。这是为了将 JSON 映射到 Java 对象:

    <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>
    

    编辑 1: 控制器中的方法是这样的吗?

    @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";
    }
    

    如果您没有响应网页并使用结果被消费,请使用上述内容。如果你想从这个方法返回一些东西并显示在网页中或在其他地方使用,方法的声明将更改为:

    public @ResponseBody String saveUser(@RequestBody UserRegistration userReg)
    

    编辑 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");
            });
        };
    

    【讨论】:

    • 但我得到的响应在所有字段中都是空的
    • 当我将您建议的内容作为第一次编辑时,它会抛出“客户端发送的请求在语法上不正确”。对于第二个,当我尝试从我的角度调用它时,我的意思是当我尝试使用我的 angularjs 发布某些内容时,会出现相同的错误
    • @mark 由于错误是“客户端发送的请求在语法上不正确”,这意味着发送的请求不是正确的 JSON 格式。我大概知道为什么会这样。 formData 中的参数在单引号内。删除它们并尝试。我更新了一些我通常在 EDIT2 中使用的东西。
    • 我试过了,但它又给我一个错误“服务器拒绝了这个请求,因为请求实体的格式不受请求的方法所请求的资源支持”。更多我尝试使用日志,它向我显示以下错误..“org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型'application/json'。”。我正在使用杰克逊绑定 jar 反序列化 json
    • @mark 我认为您的 JSON 中缺少某些内容。该类可能需要 10 个变量,而您试图传递较少数量的变量。如果该类有 10 个变量,并且请求始终没有 10 个变量,那么您需要在该类上使用注解 @JsonIgnoreProperties(ignoreUnknown = true)。
    【解决方案2】:

    尝试在方法参数中添加@RequestBody:

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

    【讨论】:

    • 它仍然给我空值。
    • 是的,当我这样做时,它说客户端请求在语法上不正确。 {“姓氏”:“标记”,“名字”:“k”,“电子邮件”:“acb@xyz.com”,“街道名称”:“abc”,“aptName”:“12”,“城市”:“ fremont", "state": "CA", "country": "USA", "zip": "95747", "userName": "Mark6656", "password": "Mark" }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    相关资源
    最近更新 更多