一、驗證碼
驗證碼:屏障,防止暴力破解
1、匯入依賴
<!—— https://mvnrepository。com/artifact/com。github。penggle/kaptcha ——>
2、宣告驗證碼元件
<!——宣告驗證碼——>
3、Page
完成1、2步驟,即可訪問 http://xxxx:xx/captcha
<%@ page contentType=“text/html;charset=UTF-8” language=“java”%>
二、Ajax跨域
域:協議+IP+埠
http://localhost:8989
http://localhost:8080
http://baidu。com:80
協議、IP、埠只要其中任何一個不同,就是跨域
1、解決方案
function kuayu() { var xhr = new XMLHttpRequest(); xhr。open(“get”,“http://localhost:8080/cross/test1”); xhr。send(); xhr。onreadystatechange=function(){ if (xhr。readyState==4 && xhr。status == 200){ console。log(xhr。responseText); } }}
在被訪問方的Controller類或方法上,新增如下註解:
@CrossOrigin(origins = “http://localhost:8989”)public class CrossOController(){ 。。。。。}
2、跨域攜帶cookie
A不僅要能訪問B,還能在請求中攜帶B的cookie,進而保證B中執行時有cookie可用
新增 xhr。withCredentials=true;
表示發請求時攜帶cookie
function kuayu() { var xhr = new XMLHttpRequest(); xhr。open(“get”,“http://localhost:8080/cross/test1”); xhr。withCredentials=true; xhr。send(); xhr。onreadystatechange=function(){ if (xhr。readyState==4 && xhr。status == 200){ console。log(xhr。responseText); } }}
在註解中新增屬性
origins = “http://localhost:8989”,允許響應域A
allowCredentials = “true”(預設是alse),允許跨域攜帶cookie
@CrossOrigin(origins = “http://localhost:8989”,allowCredentials = “true”)public class CrossOController(){ 。。。。。}
3、完整示例
域A為:http://localhost:8989
域B為:http://localhost:8080
<%@ page pageEncoding=“utf-8” %>
Hello World!
@CrossOrigin(origins = “http://localhost:8989”,allowCredentials = “true”)@Controller@RequestMapping(“cross”)public class CrossController { @RequestMapping(“test1”) @ResponseBody public User test1(HttpSession session){ System。out。println(“跨域test1··”); System。out。println(session。getId()); session。setAttribute(“name”,“里斯”); return new User(1,“張三”,true,new Date()); } @RequestMapping(“test2”) @ResponseBody public User test2(HttpSession session){ System。out。println(“跨域test2··”); System。out。println(session。getId()); System。out。println(session。getAttribute(“name”)); return new User(1,“張三”,true,new Date()); }}