如何在過濾器中獲取請求的引數及過濾器如何注入bean
1:過濾器中使用bean:因為過濾器是Tomcat容器不受spring的管理所以不能用註解直接注入。我們可以通過下面方式注入:
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();//通過ContextLoader獲取上下文
ILoginService loginService = (ILoginService)wac.getBean("loginService");//通過上下文獲取bean
如果想在過濾器中獲取bean則可以通過spring的代理,如下:
web.xml中配置:
<filter>
<filter-name>DelegatingFilterProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><init-param>
<param-name>targetBeanName</param-name>
<param-value>singLoginFiler</param-value>
</init-param>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DelegatingFilterProxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring中配置bean:
<bean id="singLoginFiler" class="com.yanshang.p2p.usecase.filter.SingLoginFiler"></bean>
然後在SingLoginFiler的過濾器中就可以注入bean了
2:在過濾器中通過request.getParameter();是獲取不到請求引數的,如何向獲取引數可以通過request.getReader()或request.getInputStream();但request.getReader()老是報reader已開啟的錯誤,應該是某個bean沒有序列化的原因,可以使用request.getInputStream()獲取,如下同過濾器判斷是否已在其它裝置登入:
public class SingLoginFiler extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
Map<String,Object> out = new HashMap<>();
String sid = "";
String singLoginId = "";
String uri = request.getRequestURI();
if(!(uri.contains("index")||uri.contains("appadv")||uri.contains("noOauth2")||uri.contains("index4")||uri.contains("all5"))){
StringBuilder content = new StringBuilder();
ServletInputStream reader = request.getInputStream();//獲取請求引數
byte[] b = new byte[1024];
int lens = -1;
while((lens=reader.read(b))>0){
content.append(new String(b, 0, lens));//將引數放到StringBuilder中
}
reader.close();
String str = content.toString();
if(!StringUtils.isEmpty(str)&&str.length()>2&&str.startsWith("{")){
JSONObject jsonObject = JSONObject.fromObject(str);//將引數轉成JSON
if(jsonObject.containsKey("sid")){
sid = jsonObject.getString("sid");
}
if(jsonObject.containsKey("singLoginId")){
singLoginId = jsonObject.getString("singLoginId");
}
}
if(!StringUtils.isEmpty(sid)&&!StringUtils.isEmpty("singLoginId")){
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
ILoginService loginService = (ILoginService)wac.getBean("loginService");
String singLogFlag = loginService.getSingLogId(sid);
if(!(StringUtils.isEmpty(singLogFlag)||singLoginId.equals(singLogFlag))){
out.put("code", "999");
out.put("msg", "已在其它裝置登入");
JsonUtil.writeJson(response,out);
}
}else{
filterChain.doFilter(request, response);
}
}else{
filterChain.doFilter(request, response);
}
}
}