下面是最新的。注意只有spring4.3以上(包含4.3)才有效。
jackson-databind
jackson-core
jackson-annotations
附上maven配置,一看就懂了
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.5</version>
</dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.5</version>
</dependency>
2.后台设置,springmvc,中只要在类上设置一个注解@CrossOrigin,那么这个类就可以接受跨域申请。注意只有spring4.3以上(包含4.3)才支持注解@CrossOrigin,这点很多文章没提到。
@CrossOrigin 的具体只接受某个域名的配置自己去网上查帮助。默认是允许所有域名访问。
具体的代码如下,
@CrossOrigin( maxAge = 3600)//配置这里就行了
@Controller
@RequestMapping("/personController")
public class PersonController {
}
@RequestMapping(value="getjsonp/{id}",method=RequestMethod.GET)
@ResponseBody
public Collection getjson(@PathVariable("id") Integer id,String callback) throws Exception{
}
@RequestMapping(value="postjson",method=RequestMethod.POST)
public String postjson(@RequestBody Person p) throws Exception{
}
var
app
=angular.module(
"myApp"
,[]);
app
.controller(
'firstController'
,
function
($scope,$http) {
//$scope.xx="xyz";
// $http.get('http://localhost:8080/SSM1/personController/getjsonp/100').success(function (data,status,headers,config){
// console.log(data);
// console.log(status);
// console.log(headers);
// console.log(config);
// }
//
// ).error(function (data,config) {
// })
$http({
url
:
'http://localhost:8080/SSM1/personController/postjsonp'
,
method
:
'POST'
,122)">data
: {
id
:
1
,
name
:
'
美国
'
,122)">age
:
16
}
}).success(
function
(){
console
.
log
(
"success!"
);
}).
error
(
"error"
);
})
});
</
script
>
@CrossOrigin( maxAge = 3600)
@Controller
@RequestMapping("/personController")
public class PersonController {
@RequestMapping(value="getjson/{id}",String callback) throws Exception{
Person p1= new Person(1,"aa",30);
Person p2= new Person(2,"bbb",50);
HashMap ps = new HashMap<Integer,Person>();
ps.put(1,p1);
ps.put(2,p2);
System.out.println(id.toString());
System.out.println(callback);
System.out.println("new Person p");
return ps.values();
}
//获取前端发出的post请求
@RequestMapping(value="postjson",method=RequestMethod.POST)
public String postjson(@RequestBody Person p) throws Exception{
System.out.println("id:"+p.getId());
System.out.println("name:"+p.getName());
System.out.println("age:"+p.getAge());
return "ok";
}
}
原文链接:https://www.f2er.com/springmvc/148502.html