SpringBoot(六):SpringBoot使用CROS解決跨域問題
跨域問題其實之前就有說過,不明白的可以參考我之前的文章,這章主要講解SpringBoot CROS的支援。
這裡主要按照官方文件方式講述。
SpringBoot CROS 參考: http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#boot-features-cors
Spring CROS 參考: http://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/htmlsingle/#cors
一、程式碼準備
首先是支援Restful的controller,這裡就不使用資料庫了,簡單一點。 UserController.class
package cn.saytime.web; import cn.saytime.bean.JsonResult; import cn.saytime.bean.User; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author zh * @ClassName cn.saytime.web.UserController * @Description */ @RestController public class UserController { // 建立執行緒安全的Map static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>()); /** * 根據ID查詢使用者 * @param id * @return */ @RequestMapping(value = "user/{id}", method = RequestMethod.GET) public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){ JsonResult r = new JsonResult(); try { User user = users.get(id); r.setResult(user); r.setStatus("ok"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("error"); e.printStackTrace(); } return ResponseEntity.ok(r); } /** * 查詢使用者列表 * @return */ @CrossOrigin @RequestMapping(value = "users", method = RequestMethod.GET) public ResponseEntity<JsonResult> getUserList (){ JsonResult r = new JsonResult(); try { List<User> userList = new ArrayList<User>(users.values()); r.setResult(userList); r.setStatus("ok"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("error"); e.printStackTrace(); } return ResponseEntity.ok(r); } /** * 新增使用者 * @param user * @return */ @RequestMapping(value = "user", method = RequestMethod.POST) public ResponseEntity<JsonResult> add (@RequestBody User user){ JsonResult r = new JsonResult(); try { users.put(user.getId(), user); r.setResult(user.getId()); r.setStatus("ok"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("error"); e.printStackTrace(); } return ResponseEntity.ok(r); } /** * 根據id刪除使用者 * @param id * @return */ @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE) public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){ JsonResult r = new JsonResult(); try { users.remove(id); r.setResult(id); r.setStatus("ok"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("error"); e.printStackTrace(); } return ResponseEntity.ok(r); } /** * 根據id修改使用者資訊 * @param user * @return */ @RequestMapping(value = "user/{id}", method = RequestMethod.PUT) public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){ JsonResult r = new JsonResult(); try { User u = users.get(id); u.setUsername(user.getUsername()); u.setAge(user.getAge()); users.put(id, u); r.setResult(u); r.setStatus("ok"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("error"); e.printStackTrace(); } return ResponseEntity.ok(r); } } User.class
package cn.saytime.bean; import java.util.Date; /** * @author zh * @ClassName cn.saytime.bean.User * @Description */ public class User { private int id; private String username; private int age; private Date ctm; // Getter Setter } JsonResult.class
package cn.saytime.bean; public class JsonResult { private String status = null; private Object result = null; // Getter Setter } 二、測試是否存在跨域問題 我們在static目錄新建一個test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/2.1.0/jquery.min.js"></script> <script type="text/javascript"> function crosRequest(){ $.ajax({ url:'http://localhost:8080/users', type:'get', dataType:'json', success:function(data){ console.log(data); } }); } </script> </head> <body> <button onclick="crosRequest()">請求跨域資源</button> </body> </html>