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;
        }
                                                                                                                              
        if (webRequest.getAttribute(annoVal,RequestAttributes.SCOPE_SESSION) != null){
            return webRequest.getAttribute(annoVal,RequestAttributes.SCOPE_SESSION);
        }
        else
            return null;
    }
                                                                                                                                                       
    final Logger logger = LoggerFactory.getLogger(SessionScopeMethodArgumentResolver.class);
}
 


supportParameter判断对象是否被注解,被注解则进行resolve。


resolve时获取注解值,注解值为session key,用webRequest从session scope中取值。




另外需要将此配置放到org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter的customArgumentResolvers列表中,可以使用bean标签配置,也可以直接使用mvc标签。
即:
namespace为:xmlns:mvc="http://www.springframework.org/schema/mvc"
schema location为:http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd


复制代码
<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="pac.common.SessionScopeMethodArgumentResolver" />
    </mvc:argument-resolvers>
</mvc:annotation-driven>
<mvc:default-servlet-handler />
复制代码
 


话说mvc:annotation-driven和mvc:default-servlet-handler的顺序不能颠倒,该不会只有我出现这种情况吧- -..


现在可以在controller中使用了,比如:


@RequestMapping(value = "/index")
@SessionScope("currentUser")
public ModelAndView index(User currentUser) {
    ModelAndView mav;
    if (currentUser==null || currentUser.getId()==null)
        mav = new ModelAndView("/login");
    else {
        mav = new ModelAndView("/index");
    }
    return mav;
}
 


或者在参数上注解:


@RequestMapping(value = "/welcome")
public String welcome(@SessionScope("currentUser")User currentUser) {
    return "/main";
}
 


至于更新session,目前只是用@sessionAttributes配合ModelMap的方式。
嗯,我不是很喜欢这种方式...


 


或者我可以不用这样做,直接集成Apache Shiro,在controller中直接getSubject()。
把用户信息完全让shiro负责,嗯,这个好。

SpringMVC ,使用 Session 非常简单。可以通过在 Controller 的方法参数添加 HttpSession 类型的参数来获取 Session 对象,然后就可以直接使用 Session 对象了。 下面是一个简单的例子,演示了如何在 SpringMVC 使用 Session: ```java @Controller public class MyController { @RequestMapping("/login") public String login(HttpSession session, String username, String password) { // 根据用户名和密码进行登录验证 boolean isAuthenticated = authenticate(username, password); if (isAuthenticated) { // 如果验证成功,则将用户信息存储到 Session session.setAttribute("username", username); return "redirect:/dashboard"; } else { return "redirect:/login?error=1"; } } @RequestMapping("/dashboard") public String dashboard(HttpSession session, Model model) { // 从 Session 获取当前用户的用户名 String username = (String) session.getAttribute("username"); if (username != null) { // 如果用户名存在,则将其作为 Model 的属性传递给视图 model.addAttribute("username", username); return "dashboard"; } else { return "redirect:/login"; } } } ``` 在上面的例子,`login` 方法获取到了 HttpSession 对象,并使用 `setAttribute` 方法将用户名存储到 Session 。在 `dashboard` 方法,可以通过 `getAttribute` 方法获取 Session 存储的用户名,并将其作为 Model 的属性传递给视图。如果 Session 不存在当前用户的信息,则重定向到登录页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值