AngularJs的post传递参数action接不到

最近使用SSH和AngularJs做毕业设计,页面相济$http.post发送数据,发现在Action中无法接收到,找了很久原因得到的结果是Content-Type的问题。

Content-Type用于指定内容类型,一般是指网页中存在的Content-Type,Content-Type属性指定请求和响应的HTTP内容类型。如果未指定 ContentType,默认为text/html。
传统JQuery传递方式是 Content-Type: x-www-form-urlencoded
而AngularJs传递方式是 Content-Type: application/json

而我在Action中使用的是

@ParentPackage("structs-default")

这种方式下无法解析json字符串。
解决方式,引入struts2-json-plugin包,Action的注释改为

@ParentPackage("json-default")

完整代码

//login.js
angular.module('loginApp',[]).controller('loginCtrl',['$scope','$http',function($scope,$http){
    $scope.user={
            USER_NAME:'',
            PASSWORD:'',
    };
    $scope.submit=submit;

    function submit(){
        $.post('/spareTimeEdu/login/login',
            {'user':JSON.stringify($scope.user)}).
        success(function(data){
        });
    }
}]);
//action.java
@ParentPackage("json-default")
@Component
@Scope(value="prototype")
@Namespace("/login")
public class loginAction extends ActionSupport implements
ServletContextAware, ServletResponseAware, ServletRequestAware{

    private HttpServletRequest req;
    private HttpServletResponse resp;
    private ServletContext ctx;

    @Action(value="login")
    public void login(){
        String jsonStr=req.getParameter("user");
        Map map=new HashMap();
        //把json字符串转换为Map
        if(null!=jsonStr && ""!=jsonStr){
            Gson gson=new Gson();
            Type type = new TypeToken() {}.getType();
            map=gson.fromJson(jsonStr, type);
        }
        System.out.println(map.get("USER_NAME"));
    }
}

你可能感兴趣的:(毕业设计)