如何将对象从angularjs传递给spring控制器

时间:2017-07-12 14:18:00

标签: javascript java angularjs spring

我有一些角度代码要求输入用户名:

playCtrl.js         var myApp = angular.module(' myApp');

/*
 * CONTROLLERS METHOD
 */

myApp.controller('PlayController', ['$scope', '$http', function($scope, $http) {

var REQUEST_SERVICE_URI = '/Project2/play.do';
//var REQUEST_SERVICE_URI = 'http://13.59.197.145:8085/Project2/#/play';
var playerObject = {} // create playerObject

$scope.message = "Let's play!";
$scope.message2 = "Please enter your name";
$scope.user = {
        userid: '',
        username: '',
        roleId: '',
        statusId: ''

};

$scope.register = function() {

    playerObject = $scope.user;  // adding user to a playerObject
    console.log('playerObject.name: ' + playerObject.name);
    //console.log('playerObject: ' + $scope.user.name);

    console.log("REGISTER BUTTON WAS CLICKED");
    $http.post(REQUEST_SERVICE_URI, playerObject).
        then(function(playerObject) {
            alert("SUCCESS");
            //$scope.user = data;
        });
}
}])

然后我让我的SpringController.java尝试获取此用户对象:

@RestController
public class SpringController {


// has to accept 
@RequestMapping(headers="Accept=application/json", value="/play.do", method = RequestMethod.POST)
public String registerUser(Users user, BindingResult bindingResult, ModelMap modelMap, HttpSession session){
    Register r = new Register();
    System.out.println("TRYING TO CREATE A USER: " + user);

    if(r.createUser(user.getUsername())){
    session.setAttribute("username", user.getUsername());
    session.setAttribute("role", user.getRole());
    session.setAttribute("status", user.getStatus());

    System.out.println("Created user: " + user.getUsername());

    return "lobby";


    }else{

        return "login";

    }

}

我的控制台能够完美地打印出angularjs中的所有内容,并且还打印出“尝试创建用户:" +来自java方面的用户,但是所有内容都为null:尝试创建用户:用户[userid = 0,username = null,roleId = null,statusId = null] (我的用户创建实现只需要一个用户名,其他所有人都可以为null)

这是我的web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/beans.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>SpringDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/beans.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>SpringDispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping> 

这是我从控制台得到的错误:

javax.validation.ConstraintViolationException: Validation failed for classes 

[com.revature.bean.Users] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='Username cannot be empty(1-20 characters)', propertyPath=username, rootBeanClass=class com.revature.bean.Users, messageTemplate='Username cannot be empty(1-20 characters)'}

Users.java:

package com.revature.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;

@Component
@Entity
@Table(name = "Users")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "myAwesomeCache")

public class Users {

@Id
@Column(name = "U_Id")
@SequenceGenerator(name = "UID_SEQ", sequenceName = "UID_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "UID_SEQ")
private int userid;

@NotEmpty(message="Username cannot be empty(1-20 characters)")
@Size(min=1,max=20)
@Column(name = "Username")
private String username;


public Users() {
    super();
}

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "Role_ID")
private Roles role;

@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "Status_ID")
private Status status;

public Users(int userid, String username, Roles roleId, Status statusId) {
    super();
    this.userid = userid;
    this.username = username;
    this.role = roleId;
    this.status = statusId;
}

public Users(String username, Roles roleId, Status statusId) {
    super();
    this.username = username;
    this.role = roleId;
    this.status = statusId;
}

public int getUserid() {
    return userid;
}

public void setUserid(int userid) {
    this.userid = userid;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public Status getStatusId() {
    return status;
}

public void setStatusId(Status status) {
    this.status = status;
}



public Roles getRole() {
    return role;
}

public void setRole(Roles role) {
    this.role = role;
}

public Status getStatus() {
    return status;
}

public void setStatus(Status status) {
    this.status = status;
}

@Override
public String toString() {
    return "Users [userid=" + userid + ", username=" + username + ", roleId=" + role + ", statusId=" + status
            + "]";
}

}

我如何正确发送对象?

1 个答案:

答案 0 :(得分:0)

我刚想通了:我必须在SpringController方法的()中添加@RequestBody,并将输入从Object更改为String类型:

public String registerUser(@RequestBody String username, BindingResult bindingResult, ModelMap modelMap, HttpSession session)