在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的“粗暴做法”

 

posted @ 2017-09-17 22:06  Deolin  阅读(782)  评论(0编辑  收藏  举报