有些网站需要登录以后才能访问网站内部资源,这就需要我们做一个过滤器,当用户访问网站内部资源时,要先经过过滤器,过滤器判断是否有这个用户,有则跳转进入网站内部页面,没有则返回登录页面。
过滤器代码:
package com.dr.course;
import java.io.IOException;
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.HttpSession;
import com.dr.common.Global;
import com.dr.vo.User;
public class IsLoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
System.out.println("every request pass here");
HttpServletRequest hrequest=(HttpServletRequest)request;
HttpSession session=hrequest.getSession();
User user = (User)session.getAttribute(Global.USER);
if(user == null){
//跳转到登陆页面
hrequest.getRequestDispatcher("/index.jsp").forward(request,response);
}
filterChain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
LoginServlet类,进行登录之后的处理:
package com.dr.course;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.dr.common.Global;
import com.dr.vo.User;
public class LoginServlet extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
String userName=request.getParameter("username");
String passWord=request.getParameter("password");
System.out.println("userName | " + userName);
System.out.println("passWord | " + passWord);
User user = new User();
user.setUserName(userName);
user.setPassWord(passWord);
HttpSession session = request.getSession();
//登录成功,把User放到session,然后在拦截器中判断
//key--value
session.setAttribute(Global.USER, user);
request.getRequestDispatcher("/admin/main.jsp").forward(request, response);
}
}
web.xml中配置如下:
- <filter>
<filter-name>isLogin</filter-name>
<filter-class>com.dr.course.IsLoginFilter</filter-class>
</filter>
- <filter-mapping>
<filter-name>isLogin</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
- <servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.dr.course.LoginServlet</servlet-class>
</servlet>
- <servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
未登录界面:
成功登录的界面: