在Spring MVC中通过angularjs $ http.get发送HashMap


问题内容

我想通过angularjs发送和检索HashMap,并在springmvc控制器中接收它。我已经成功发送和接收List,但是无法发送HashMap。我的代码是。

$scope.addskill = function(skills){     
//  $scope.list = [];       
//  $scope.list.push(skills.skillName, skills.expMonth, skills.expYear, skills.experties);          
    var map = {};
    map['name'] = skills.skillName;
    map['month'] = skills.expMonth;
    map['year'] = skills.expYear;
    map['experties'] = skills.experties;

    alert(map['name']);
    var response = $http.get('/JobSearch/user/addskill/?map=' +map);
//  var response = $http.get('/JobSearch/user/addskill/?list=' +$scope.list);
    response.success(function(data, status, headers, config){
        $scope.skills = null;
        $timeout($scope.refreshskill,1000);             
    });             
    response.error(function(data, status, headers, config) {
        alert( "Exception details: " + JSON.stringify({data: data}));
    });     
};

我的mvc控制器是:

@RequestMapping(value = "/addskill", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(@RequestBody HashMap<String,String> map){

    System.out.println(map.get("name"));
/*      
 *      public void addStudentSkill(@RequestParam("list") List list){
    try{    
        StudentSkills skills = new StudentSkills();
        skills.setSkillName(list[0]);
        skills.setExpMonth(Integer.parseInt(list[1]));
        skills.setExpYear(Integer.parseInt(list[2]));
        skills.setExperties(list[3]);
        skills.setStudent(studentService.getStudent(getStudentName()));
        studentService.addStudentSkill(skills);
    }catch(Exception e){};

*/
}

当我发送和接收列表时,注释的代码有效。我想使用密钥来检索数据。如果有更好的方法,请提出建议。

错误是无法将java.lang.string转换为hashmap


问题答案:

您正在将地图作为请求参数发送。您正在尝试在请求正文中阅读它。那可能行不通。无论如何,GET请求都没有主体。

这是您应该如何做:

var parameters = {};
parameters.name = skills.skillName;
parameters.month = skills.expMonth;
parameters.year = skills.expYear;
parameters.experties = skills.experties;

var promise = $http.get('/JobSearch/user/addskill', {
    params: parameters
});

在Spring控制器中:

@RequestMapping(value = "/addskill", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(@RequestParam("name") String name,
                            @RequestParam("name") String month,
                            @RequestParam("name") String year,
                            @RequestParam("name") String experties) {
    ...
}

就是说,给定方法的名称addStudentSkill以及它不返回任何内容的事实,似乎此方法不是用于从服务器获取数据,而是用于在服务器上创建数据。因此,此方法应映射到POST请求,并且数据应作为正文发送:

var data = {};
data.name = skills.skillName;
data.month = skills.expMonth;
data.year = skills.expYear;
data.experties = skills.experties;

var promise = $http.post('/JobSearch/user/addskill', params);

并在控制器中:

@RequestMapping(value = "/addskill", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.CREATED)
public void addStudentSkill(@RequestBody Map<String, String> data) {
    ...
}