封装获取session中值的方法

1、引入maven依赖

		<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

2、直接上代码

package cn.toroot.bj.core.constant;

import org.springframework.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public HttpServletResponse getResponse(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

	/**
     * 获取session中的用户信息
     * @return
     */
    public Map<String,Object> getSessionUser() {
        if(SecurityUtils.getSubject() != null){
            if(SecurityUtils.getSubject().getSession() != null){
                return (Map<String,Object>)SecurityUtils.getSubject().getSession().getAttribute("userInfo");
            }
        }
        return null;
    }

    /**
     * 获取session中的用户名
     * @return
     */
    public String getSessionUserName() {
        Map<String,Object> userInfo = getSessionUser();
        if(userInfo != null){
            String userStr="user";
            String nameStr = "name";
            if(userInfo.get(userStr) != null){
                Map<String,Object> user = ( Map<String,Object> )userInfo.get(userStr);
                return (String)user.get(nameStr);
            }
        }
        return null;
    }    
    /**
     * 获取session中的用户id
     * @return
     */
    public String getSessionUserId(){
        Map<String,Object> userInfo = getSessionUser();
        if(userInfo != null){
            String userStr="user";
            String nameStr = "id";
            if(userInfo.get(userStr) != null){
                Map<String,Object> user = ( Map<String,Object> )userInfo.get(userStr);
                return (String)user.get(nameStr);
            }
        }
        return null;
    }
    /**
     * 获取session
     * @return
     */
    public Session getSession() {
        if(SecurityUtils.getSubject() != null){
            return SecurityUtils.getSubject().getSession();
        }
        return null;
    } 
}

你可能感兴趣的:(封装获取session中值的方法)