没有合适的资源?快使用搜索试试~ 我知道了~
SpringMVC实现controller中获取session的实例代码
1 下载量 31 浏览量
2020-08-31
12:03:12
上传
评论
收藏 51KB PDF 举报
温馨提示
试读
2页
本篇文章主要介绍了SpringMVC实现controller中获取session的实例代码,具有一定的参考价值,有兴趣的可以了解一下。
资源推荐
资源详情
资源评论
SpringMVC实现实现controller中获取中获取session的实例代码的实例代码
本篇文章主要介绍了SpringMVC实现controller中获取session的实例代码,具有一定的参考价值,有兴趣的可以
了解一下。
平时使用springMVC,在方法中访问session中经常很自然地调用Servlet API。用起来非常直观方便,一直没有多考虑什么。
比如这样:
@RequestMapping(value = "/logout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "/login";
}
但毕竟这样对Servlet API产生了依赖,感觉不够pojo。
于是我试着解决这个问题。
我打算用一个注解,名字就叫"sessionScope",Target可以是一个Method,也可以是Parameter。
也就是说:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.PARAMETER,ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SessionScope {
String value();
}
然后我要注册一个ArgumentResolver,专门解决被注解的东东,把他们统统替换成session里的东西。
代码如下:
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
public class SessionScopeMethodArgumentResolver implements
HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
//让方法和参数,两种target通过
if(parameter.hasParameterAnnotation(SessionScope.class))return true;
else if (parameter.getMethodAnnotation(SessionScope.class) != null)return true;
return false;
}
@Override
public Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
String annoVal = null;
if(parameter.getParameterAnnotation(SessionScope.class)!=null){
logger.debug("param anno val::::"+parameter.getParameterAnnotation(SessionScope.class).value());
annoVal = parameter.getParameterAnnotation(SessionScope.class).value();
}else if(parameter.getMethodAnnotation(SessionScope.class)!=null){
logger.debug("method anno val::::"+parameter.getMethodAnnotation(SessionScope.class).value());
annoVal = parameter.getMethodAnnotation(SessionScope.class)!=null?
StringUtils.defaultString(parameter.getMethodAnnotation(SessionScope.class).value())
:StringUtils.EMPTY;
}
资源评论
weixin_38606041
- 粉丝: 5
- 资源: 932
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功