前后端分離時,獲取不到session


在前后端分離的springboot項目中,進行圖片驗證時,第一次獲取驗證圖片后,我將code值加密后存放到了session中,打算在下一個請求進行圖片驗證時直接從session中獲取code值,然后進行對比。結果調試時,在第二步過程中獲取的session一直為null。因此匹配結果一直false。當時后台代碼如下:

controller層

@ApiOperation(value = "獲取圖片驗證碼", notes = "獲取圖片驗證碼")
    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    public void verfification(HttpServletRequest request, HttpServletResponse response, HttpSession session)throws IOException{
        // 設置響應的類型為圖片格式
        response.setContentType("image/jpeg");
        // 禁止圖片緩存
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        VerificationCode verificationCode = new VerificationCode();
        // 將驗證碼存入session
        session.setAttribute("verification", MD5.eccrypt(verificationCode.getCode().toLowerCase()));
        System.out.println(session.getId());
        verificationCode.write(response.getOutputStream());
    }

    @ApiOperation(value = "驗證驗證碼是否正確", notes = "驗證驗證碼是否正確")
    @ApiImplicitParam(name = "code",value = "圖片驗證碼",required = true,dataType = "String")
    @RequestMapping(value = "/verification/{code}",method = RequestMethod.POST)
    public Response verfification(@PathVariable("code") String code,HttpSession session){
        System.out.println(session.getId());
        // 圖片驗證碼
        if(!VerificationCode.isright(code.toLowerCase(),session)){
            return new Response("圖片驗證碼錯誤!","圖片驗證碼錯誤,請重新輸入!");
        }
        return new Response(true,"圖片驗證碼正確!","圖片驗證碼成功!");
    }

 攔截器:

@Configuration
public class CorsFilterConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
// 允許跨域 config.setAllowCredentials(true);
// 設置允許跨域的域名,如:http://localhost:9004 如果為*號,則表示允許所有的 config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; } }

研究了大半個小時,才找到解決辦法:后台代碼沒有問題,需要在前端代碼每次發送請求時添加  axios.defaults.withCredentials = true 這段代碼。

此時在后台兩次請求獲取的sessionId完全相同,也就是同一個session

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM