最近在做一个自动登录模块的时候遇到一个问题,在过滤器中调用service层方法时,注入的service为NULL,参考网上的几种解决方案web filter 注入service,用了其中的方法后还是无法解决,会报 No bean named 'AutoLoginFilter' is defined
最后参考https://www.cnblogs.com/chenying99/archive/2012/08/19/2646350.html发现问题应该是在Servlet Dispatcher中所初始化的Bean不能被以外的servlet或者filter使用了,参照上面的方法试着改了配置文件,即给DispatcherServlet单独的一个配置文件sprinvmvc-servlet.xml。配置如下
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<welcome-file-list>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/springmvc-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- <filter> -->
<!-- <filter-name>AutoLoginFilter</filter-name> -->
<!-- <filter-class>com.dh.filter.AutoLoginFilter</filter-class> -->
<!-- </filter> -->
<!-- <filter-mapping> -->
<!-- <filter-name>AutoLoginFilter</filter-name> -->
<!-- <url-pattern>/*</url-pattern> -->
<!-- </filter-mapping> -->
<filter>
<filter-name>UserLoginFilter</filter-name>
<filter-class>com.dh.filter.UserLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserLoginFilter</filter-name>
<url-pattern>/privilege/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>DelegatingFilterProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>AutoLoginFilter</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>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath*:jdbc.properties" ignore-unresolvable="true" />
<context:component-scan base-package="com.dh.*"></context:component-scan>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="AutoLoginFilter" class="com.dh.filter.AutoLoginFilter"></bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value=""></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- class="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory" -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${strDriver}"></property>
<property name="url"
value="${strURL}">
</property>
<property name="username" value="${strUser}"></property>
<property name="password" value="${strPwd}"></property>
</bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis配置文件 -->
<property name="configLocation" value="/WEB-INF/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- mabatis批量扫描,从mapper包中扫出mapper接口,自动创建代理对象并在spring中注册
遵循规范:mapper.java和mapper.xml文件名一致且在一个目录中
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描的包名 -->
<property name="basePackage" value="com.dh.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.dh.*"></context:component-scan>
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value=""></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
AutoLoginFilter
package com.dh.filter;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.OncePerRequestFilter;
import com.dh.model.User;
import com.dh.service.UserService;
@WebFilter
public class AutoLoginFilter extends OncePerRequestFilter {
@Autowired
private UserService userService;
@Override
public void destroy() {
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// TODO Auto-generated method stub
//强转成HttpServletRequest
HttpServletRequest req = (HttpServletRequest) request;
User user = (User) req.getSession().getAttribute("user");
if(user==null){
String cookie_username = null;
String cookie_password = null;
//获取携带用户名和密码cookie
Cookie[] cookies = req.getCookies();
//测试用 查看cookie
if(cookies!=null) {
for(Cookie cookie:cookies){
System.out.println(cookie.getName());
System.out.println(cookie.getValue());
}
}
if(cookies!=null){
for(Cookie cookie:cookies){
//获得想要的cookie
if("cookie_username".equals(cookie.getName())){
cookie_username = cookie.getValue();
}
if("cookie_password".equals(cookie.getName())){
cookie_password = cookie.getValue();
}
}
}
if(cookie_username!=null&&cookie_password!=null){
//去数据库校验该用户名和密码是否正确
System.out.println(cookie_username+"-------"+cookie_password);
user=userService.login(cookie_username, cookie_password);
//完成自动登录
req.getSession().setAttribute("user", user);
}
}
//放行
chain.doFilter(req, response);
}
}
这样配置后问题解决了,可以在filter中注入service了。
主要以后配置的时候要记得在Servlet Dispatcher中所初始化的Bean不能被以外的servlet或者filter使用了。这样就要分开配置,不能都写在一个配置文件里。
另外在servlet中使用Autowired报空指针可采用下面配置
public void init(ServletConfig config) throws ServletException
{
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
总结一下就是servlet和filter是不受spring容器管理的,毕竟spring有自己的一套东西。
最后,可以参考这篇文章,了解一下是怎么回事。