Springmvc擴充套件:驗證碼、Ajax跨域

一、驗證碼

驗證碼:屏障,防止暴力破解

1、匯入依賴

<!—— https://mvnrepository。com/artifact/com。github。penggle/kaptcha ——> com。github。penggle kaptcha 2。3。2

2、宣告驗證碼元件

<!——宣告驗證碼——> kap com。google。code。kaptcha。servlet。KaptchaServlet kaptcha。border no kaptcha。textproducer。char。length 4 kaptcha。textproducer。char。string abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ1234567890 kaptcha。background。clear。to 211,229,237 <!——session。setAttribute(“kaptcha”,“驗證碼”)——> kaptcha。session。key kaptcha kap /captcha

3、Page

完成1、2步驟,即可訪問 http://xxxx:xx/captcha

<%@ page contentType=“text/html;charset=UTF-8” language=“java”%> 驗證碼 Springmvc擴充套件:驗證碼、Ajax跨域 //?new Date()。getTime() //當瀏覽器傳送get請求時,瀏覽器會進行快取,所以我們在重新整理驗證碼時發出相同的請求,瀏覽器可能從快取中取值,導致圖片無法重新整理,加上new Date()。getTime()引數可以保證每次請求不同,不會從瀏覽器取快取

二、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()); }}

Springmvc擴充套件:驗證碼、Ajax跨域