Spring MVC Rest API、跨域请求
Rest API
package net.wuxianjie.demo.controller; import java.util.Date; import net.wuxianjie.demo.dto.UserDto; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { @GetMapping(value = "{id:\\d+}") public UserDto getUser(@PathVariable("id") Integer userId) { return new UserDto(userId, new Date(), "假名" + userId); } }
GET http://localhost:8000/users/102 Accept: application/json
跨域请求
index.html
:
<!DOCTYPE html> <html> <head lang="zh"> <meta charset="UTF-8"> <title>Test Index</title> </head> <body> <script type="text/javascript"> fetch("http://localhost:8000/users/102").then(response => { response.json().then(data => console.log(data)); }); </script> </body> </html>
方法一(手动):
package net.wuxianjie.demo.controller; import java.util.Date; import javax.servlet.http.HttpServletResponse; import net.wuxianjie.demo.dto.UserDto; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { @GetMapping(value = "{id:\\d+}") public UserDto getUser(@PathVariable("id") Integer userId, HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin", "*"); return new UserDto(userId, new Date(), "假名" + userId); } }
方法二(注解):
package net.wuxianjie.demo.controller; import java.util.Date; import net.wuxianjie.demo.dto.UserDto; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserController { @CrossOrigin @GetMapping(value = "{id:\\d+}") public UserDto getUser(@PathVariable("id") Integer userId) { return new UserDto(userId, new Date(), "假名" + userId); } }
方法三(全局配置):
app-context.xml
:
<mvc:cors> <mvc:mapping path="/users/**"/> </mvc:cors>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论