package com.mnsn.common.filter;import java.io.IOException;
import java.io.Serializable;import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mnsn.hibernate.pojo.BgUser;
import com.mnsn.system.blog.user.database.service.UserServiceImpl;public class FilterLogin implements Filter {
private UserServiceImpl service;
public UserServiceImpl getService() {
return service;
}
public void setService(UserServiceImpl service) {
this.service = service;
} public void destroy() {
} public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String requestURI=request.getRequestURL().toString();
System.out.println(request.getParameter("userid")+"------->");
if(requestURI.toLowerCase().indexOf("blog")!=-1){
try{
if(request.getParameter("userid")!=null){
Long id = Long.parseLong(request.getParameter("userid"));
BgUser user = (BgUser)this.service.findById(id);
if(user!=null){
request.getSession().setAttribute("user", user);
}
}
chain.doFilter(req, res);
}catch(Exception ex){
ex.printStackTrace();
}
}else {
chain.doFilter(req, res);
}
} public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}} 我在浏览器输入
http://localhost:8080/pp/login.jsp?userid=1 System.out.println(request.getParameter("userid")+"------->");
输出为空!
奇怪了!
竟然获不到值!这是什么原因?
UserServiceImpl service;
我通过spring注入实例, 但service对像也为空?
不知道可以在过滤中通过spring注入实例么?
还望高手多指点!
Filter 在spring定义,第一次听说,应该不可能吧
名字记得不是特别清楚,你去查询下ApplicationContext的实现类
然后在过滤器中调用业务层方法
不知道怎样获得IOC容器的实例,调用业务层方法!
filter是web容器执行的,而经过Spring托管后,就会成为代理类,其中的request、response对象从哪儿来?解决办法:
首先在xml中去掉filter注入。
然后在filter中用
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);UserServiceImpl service = (UserServiceImpl)ctx.getBean("xxx");这样就可以了,如果application对象取不到,也可以:
if(ctx == null) ctx = (WebApplicationContext)new ClassPathXmlApplicationContext("xml文件");这样连容器都能拿到,service就不可能为空。我想楼主System.out.println(request.getParameter("userid")+"------->")输出为空!
可能是根spring容器有关,经过Spring代理反射后,Web容器(Tomcat)就无法再反射了,从而导致request、response对象为空。
如果用我提出的这种方法,filter完全脱离在Spring容器,问题应该可以解决。
还是输出为空,request,response 不为空,就是获取不到浏览器传过来的userid参数值!