密钥

package com.hanyixin.service;

public interface SecurityService {

    //密钥提供者微服创建接口
    String getkey();
}
package com.hanyixin.service.impl;

import java.util.Random;

import org.apache.dubbo.config.annotation.Service;

import com.hanyixin.service.SecurityService;

@Service(interfaceClass = SecurityService.class)
public class SecurityServiceImpl implements SecurityService {
    
    
    @Override
    public String getkey() {
        Random random = new Random();
        
        String s = "";
        //密钥提供者微服随机生成16位密钥字符串
        for (int i = 0; i < 16; i++) {
            char c = (char) ('a'+random.nextInt(26));
            s += c;
        }
        return s;
    }

}
package com.hanyixin.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hanyixin.service.SecurityService;

@Controller
public class SecurityController {

    @Reference
    SecurityService securityService;
    
    //密钥请求微服创建controller
    @RequestMapping("tojsp")
    public String tojsp() {
        //跳转到页面
        return "jsp";
    }
    
    //密钥请求微服的controller能够获取密钥
    @ResponseBody
    //加载时自动发送ajax请求
    @RequestMapping("getkey")
    public String getkey(HttpServletRequest request,HttpServletResponse response){
        String key = securityService.getkey();
        //将密钥存入localStorag或cookie中
        response.addCookie(new Cookie("mycookiekey",key));
        return key;
        
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- 引入 css -->
<link rel="stylesheet" type="text/css" href="/resource/bootstrap4/css/bootstrap.css">
<!-- 引入js -->
<script type="text/javascript" src="/resource/jquery/jquery-3.4.1.js"></script>
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
function getkey() {
        alert("准备获取key");
        $.post("getkey",{},function(data){
            alert("获取到的key是"+data);
        })
    }
    getkey();
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/liujinqq7/p/12846242.html