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

上一篇:点滴积累【SQL Server】---SQL语句操作约束


下一篇:JavaWeb(一)Servlet中的request与response