zoukankan      html  css  js  c++  java
  • 在SpringMVC中操作Session、Request、Response对象

    示例

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public void addOne(UserInput input) throws Exception {
            Integer id = userMapper.insert(input);
            setSessionAttribute("userId", id, Integer.class);
        }
    
        @Override
        public void rollbackAdd() throws Exception {
            Integer id = getSessionAttribute("userId", Integer.class);
            userMapper.remove(id);
        }
    
        private <T> void setSessionAttribute(String key, T value, Class<T> valueClass) {
            RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
            ra.setAttribute(key, value, RequestAttributes.SCOPE_SESSION);
        }
    
        @SuppressWarnings("unchecked")
        private <T> T getSessionAttribute(String key, Class<T> valueClass) {
            RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
            Object value = ra.getAttribute(key, RequestAttributes.SCOPE_SESSION);
            return (T) value;
        }
    
    }

    主要是利用到了RequestContextHolder这个类。

    除此以外,还能通过RequestAttributes对象,分别获得Session、Request、Response对象

        /**
         * 获取HttpServletRequest对象
         */
        public static HttpServletRequest instance() {
            RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
            return request;
        }
    
        /**
         * 获取HttpServletResponse对象
         */
        public static HttpServletResponse instance() {
            RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
            HttpServletResponse response = ((ServletRequestAttributes) ra).getResponse();
            return response;
        }
    
        /**
         * 获取HttpSession对象
         */
        public static HttpSession instance() {
            RequestAttributes ra = RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
            HttpSession session = request.getSession();
            return session;
        }

    避免了在控制层用HttpServletRequest入参,然后将request转递到业务层已获取HttpSession的“粗暴做法”

  • 相关阅读:
    重大技术需求系统八
    2020年下半年软考真题及答案解析
    周总结五
    重大技术需求系统七
    TextWatcher 编辑框监听器
    Android四大基本组件介绍与生命周期
    JAVA String,StringBuffer与StringBuilder的区别??
    iOS开发:保持程序在后台长时间运行
    宏定义的布局约束
    随便说一些
  • 原文地址:https://www.cnblogs.com/deolin/p/7538141.html
Copyright © 2011-2022 走看看