SpringMVC實現(xiàn)controller中獲取session的實例代碼
平時使用springMVC,在方法中訪問session中經(jīng)常很自然地調(diào)用Servlet API。用起來非常直觀方便,一直沒有多考慮什么。
比如這樣:
@RequestMapping(value = "/logout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "/login";
}
但畢竟這樣對Servlet API產(chǎn)生了依賴,感覺不夠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,專門解決被注解的東東,把他們統(tǒng)統(tǒng)替換成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) {
//讓方法和參數(shù),兩種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判斷對象是否被注解,被注解則進(jìn)行resolve。
resolve時獲取注解值,注解值為session key,用webRequest從session scope中取值。
另外需要將此配置放到org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter的customArgumentResolvers列表中,可以使用bean標(biāo)簽配置,也可以直接使用mvc標(biāo)簽。
即:
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的順序不能顛倒,該不會只有我出現(xiàn)這種情況吧- -..
現(xiàn)在可以在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;
}
或者在參數(shù)上注解:
@RequestMapping(value = "/welcome")
public String welcome(@SessionScope("currentUser")User currentUser) {
return "/main";
}
至于更新session,目前只是用@sessionAttributes配合ModelMap的方式。
或者我可以不用這樣做,直接集成Apache Shiro,在controller中直接getSubject()。
把用戶信息完全讓shiro負(fù)責(zé),嗯,這個好。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IntelliJ IDEA優(yōu)化配置的實現(xiàn)
這篇文章主要介紹了IntelliJ IDEA優(yōu)化配置的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Java中final,finally,finalize三個關(guān)鍵字的區(qū)別_動力節(jié)點Java學(xué)院整理
這篇文章給大家收集整理了有關(guān)java中final,finally,finalize三個關(guān)鍵字的區(qū)別介紹,非常不錯,具有參考借鑒價值,需要的的朋友參考下吧2017-04-04
idea 創(chuàng)建properties配置文件的步驟
這篇文章主要介紹了idea 創(chuàng)建properties配置文件的步驟,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
Java編程實現(xiàn)統(tǒng)計數(shù)組中各元素出現(xiàn)次數(shù)的方法
這篇文章主要介紹了Java編程實現(xiàn)統(tǒng)計數(shù)組中各元素出現(xiàn)次數(shù)的方法,涉及java針對數(shù)組的遍歷、比較、運算等相關(guān)操作技巧,需要的朋友可以參考下2017-07-07
IntelliJ IDEA彈出“IntelliJ IDEA License Activation”的處理方法
這篇文章主要介紹了IntelliJ IDEA彈出“IntelliJ IDEA License Activation”的處理方法,本文給出解決方法,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

