servlet之间传参的四种方法

今天在写前后端分离的验证码登录(基于spring security)时,发现通过session和redis都无法实现传参。然后试了很多种方法才成功。现在总结一下这些方法。
1、session传参。
放入值:request.getSession().setAttribute("smsCode",smsCode);
获取值:SmsCode code = (SmsCode) request.getSession().getAttribute("smsCode");

2、redis传参。(其实就是利用redis存放数据)
放入值:redisService.set("name",value)
获取值:redisService.get("name")
redisService:

 @Override
    public boolean set(final String key, final String value) throws DataAccessException{
        return redisTemplate.execute((RedisConnection connection) -> {
            RedisSerializer serializer = redisTemplate.getStringSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
            return true;
        });
    }
    @Override
    public String get(final String key) throws DataAccessException{
        return redisTemplate.execute((RedisConnection connection) -> {
            RedisSerializer serializer = redisTemplate.getStringSerializer();
            byte[] value =  connection.get(serializer.serialize(key));
            return serializer.deserialize(value);
        });
    }

3、request传参:

request.setAttribute("name",value);
request.getAttribute("name");
request.getServletContext().setAttribute(KEY,imageCode);
ImageCode code = (ImageCode)request.getServletContext().getAttribute(KEY);

最后成功了的是最后一种方法。用的是是request.getServletContext.setAttribute来设置与获取值。

你可能感兴趣的:(springboot,springboot)