web中filter需要注入bean(如service,dao等bean)--- DelegatingFilterProxy

本文介绍了如何利用DelegatingFilterProxy在web.xml和applicationContext.xml中配置,以便让filter能够通过Spring容器管理,并实现bean的注入。在web.xml中展示了两种配置方法,同时强调了context-param的重要性。在applicationContext.xml中,配置的bean名称需与filter-name一致。当需要保留Filter的init和destroy方法时,需设置targetFilterLifecycle为true。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

DelegatingFilterProxy就是一个对于servlet filter的代理,用这个类的好处主要是通过spring容器来管理servlet filter的生命周期,还有就是如果filter中需要一些Spring容器的实例,可以通过spring直接注入,另外读取一些配置文件这些便利的操作都可以通过Spring来配置实现。


在web.xml中配置如下:

(1)配置方法一:

<!-- 在使用DelegatingFilterProxy代理filter的时候必须加上如下俩个web配置,否则报错 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 设置过滤器 -->
	<filter>
		<filter-name>LoginFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>LoginFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

(2)配置方法二:

<!-- 在使用DelegatingFilterProxy代理filter的时候必须加上如下俩个web配置,否则报错 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 设置过滤器 -->
	<filter>
		<filter-name>LoginFilter1</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetBeanName</param-name>
			<param-value>LoginFilter</param-value>
		</init-param>
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>LoginFilter1</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

注: No WebApplicationContext found: no ContextLoaderListener registered 错误解决就是在web中加入context-param和listener俩个配置(可能顺序也是有要求的)

<context-param>是让web应用启动时加载spring bean 容器。

在applicationContext.xml中配置如下:

<!-- 可注入bean的filter -->
	<bean id="LoginFilter" class="com.byepimples.interceptor.LoginFilter"> 
	</bean>




在Spring中配置的bean的name要和web.xml中的<filter-name>一样


或者在DelegatingFilterProxy的filter配置中配置初始参数:targetBeanName,对应到Spring配置中的beanname


如果要保留Filter原有的init,destroy方法的调用,还需要配置初始化参数targetFilterLifecycle为true,该参数默认为false


三.Filte中的代码

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import com.byepimples.entity.User;
import com.byepimples.service.UserService;


public class LoginFilter extends OncePerRequestFilter{
	
	@Autowired
	private UserService userService;

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		
		//不拦截的url
		String[] notFilter=new String[]{"/register.do","/post/respost.do","/restopic.do","/login.jsp","login.do"};
		//请求的url
		String uri=request.getRequestURI();
		//url中包含byepimples(这是我工程名)才进行过滤
		if(uri.indexOf("byepimples")!=-1){
			//是否过滤
			boolean doFilter=true;
		
			
			for(String s:notFilter){
				//如果uri中包含不过滤的uri,则不进行过滤
				if(uri.indexOf(s)!=-1){
					doFilter=false;
					break;
				}
			}
			if (doFilter) {
				//执行过滤
				/*
				//方法一.普通web从session中获取登录者实体
				Object obj=request.getSession().getAttribute("token");  //写入session中的key-value
				System.out.println("--------getSession().getAttribute(token)--"+request.getSession().getAttribute("token"));
				if(obj == null){
					//如果session中不存在所需要的实体,则需要重新登录(或提醒)
					//设置request和response的字符集,防止乱码
					request.setCharacterEncoding("UTF-8");
					response.setCharacterEncoding("UTF-8");
					//跳转到登陆页面
//					request.getRequestDispatcher("/login.jsp").forward(request, response); //这俩种都可以,一个是重定向,一个是请求转发
					response.sendRedirect("/byepimples/login.jsp");
				}
				*/
				//方法二.此方法用于android和web交互,因为安卓每次请求的session值都会改变,用第一种方法值为null,每次都需要登录,达不到效果
				String tokenApp=request.getParameter("token");
				System.out.println("app中token值 =----"+tokenApp);
				String usernameApp=request.getParameter("username");
				System.out.println("App中username---------"+usernameApp);
				User user=userService.getUserByUserName(usernameApp);
				System.out.println("数据库中user----"+user.toString());
				System.err.println("数据库中user.getToken()----"+user.getToken());
				if(!tokenApp.equals(user.getToken())){
					request.setCharacterEncoding("UTF-8");
					response.setCharacterEncoding("UTF-8");
					PrintWriter out=response.getWriter();
					out.write("0");
					out.flush();
					out.close();
					return;
//					response.sendRedirect("/byepimples/login.jsp");  //web端直接用这个跳转到指定页面
				}
				else{
					//如果session中存在 登录者/所需 实体,则继续请求
					PrintWriter out=response.getWriter();
					out.write("1");
					out.flush();
					out.close();
					return;
//					filterChain.doFilter(request, response);  //web端直接用这个,使用上边的方法是因为android需要
				}
			}else{
				//如果不执行过滤,则可以直接请求
				filterChain.doFilter(request, response);
			}
		}else{
			//如果uri中不包含byepimples,则继续
			filterChain.doFilter(request, response);
		}
		
	}

}


Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ODataConnectorImpl': Unsatisfied dependency expressed through field 'messages'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'weibaobiaoMessages': Unsatisfied dependency expressed through field 'securityService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'amsSecurityService': Unsatisfied dependency expressed through field 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [security-service.xml]: Cannot resolve reference to bean 'amsAuthorizationRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'amsAuthorizationRealm': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl': Unsatisfied dependency expressed through field 'customerService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerServiceImpl': Unsatisfied dependency expressed through field 'metadataService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'defaultMetadataServiceImpl': Unsatisfied dependency expressed through field 'zxtbTask'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'zxtbTask': Unsatisfied dependency expressed through field 'redisDistributeLock'; nested exception is org.springframework.beans.f
最新发布
07-09
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值