无法跨域访问
在控制器上使用@CrossOrigin(origins = {"http://localhost:8888"})进行了跨域访问的设置,
html页面修改了 url : "http://localhost/restful/persons", 但是点击按钮后还是无放跨域访问
重启服务器,删除out和target文件都试过了。



6
收起
正在回答
6回答
同学你好!
你的地址中应该写上端口号:
http://localhost:8888/restful/persons
老师的没有写,是因为老师使用的是80端口,浏览器默认使用的是80,所以老师的不写也可以。
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
懒人13
2019-11-26 11:39:26
下面的代码都是,是为跨域访问修改后的。
RestfulController.java
package com.imooc.restful.controller;
import com.imooc.restful.entity.Person;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController //此注解是在@Controller注解基础上的扩展,它表示当前控制器类是按照RESTful风格进行编写的,因此可以省略方法上的@ResponseBody注解
@RequestMapping("/restful")
@CrossOrigin(origins = {"http://localhost:8888"}, maxAge = 3600) //origins的值为允许跨域访问的url地址,maxAge为预检访问的缓存时间(ms)
public class RestfulController {
@GetMapping("/request")
// @ResponseBody
public String doGetRequest() {
return "{\"message\":\"返回查询结果\"}";
}
// /restful/request/100
@PostMapping("/request/{rid}")
// @ResponseBody
public String doPostRequest(@PathVariable("rid") Integer requestId, Person person){
System.out.println(person);
return "{\"message\":\"数据新建成功\",\"id\": " + requestId+ "}";
}
@PutMapping("/request")
// @ResponseBody
// 由于Put请求是非简单请求,因此应在web.xml开启并配置FormContentFilter过滤器
public String doPutRequest(Person person) {
System.out.println(person);
return "{\"message\":\"数据更新成功\"}";
}
@DeleteMapping("/request")
// @ResponseBody
public String doDeleteRequest(){
return "{\"message\":\"数据删除成功\"}";
}
@GetMapping("/person")
public Person findByPersonId(Integer id){
Person person = new Person();
if(id == 1){
person.setName("张三");
person.setAge(12);
} else if (id == 2) {
person.setName("李四");
person.setAge(34);
}
return person;
}
@GetMapping("/persons")
public List<Person> findPersons(){
List<Person> list = new ArrayList<Person>();
Person p1 = new Person();
p1.setName("张三");
p1.setAge(12);
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("李四");
p2.setAge(34);
p2.setBirthday(new Date());
list.add(p1);
list.add(p2);
return list;
}
}client.html中跨域访问的function代码
$(function () {
$("#btnPersons").click(function () {
$.ajax({
// url : "/restful/persons",
url : "http://localhost/restful/persons", //跨域访问
type : "get",
dataType : "json",
success : function (json) {
console.info(json)
for (var i = 0; i < json.length; i++) {
var p = json[i];
$("#divPersons").append("<h2>" + p.name + "-" + p.age + "-" + p.birthday + "</h2>")
}
}
})
})
})
SSM主流框架入门与综合项目实战2018版
- 参与学习 人
- 提交作业 205 份
- 解答问题 4317 个
Java中非常实用的SSM整合开发内容,从Spring开始,到MyBaits的进阶内容,再到SpringMVC的应用,最后是SSM整合开发案例,逐步深入,助你成长为一名Java工程师!
了解课程



恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星