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負責,嗯,這個好。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM