我们有时候做的网站需要身份验证,需要登录以后才能访问网站内部资源;但是地址栏里会显示你访问网站的地址,如果没有登录就直接输入该网址也会直接进入到该网页;这个时候我们还是需要做一个过滤器,当外部访问网站内部资源时,先要经过这个这个过滤器,过滤器判断你的session里面是否存在你这个用户,如果有就跳转成功,如果没有就跳转回登陆页面。
以下是代码和配置过程:
过滤器代码:
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 config) throws ServletException {
}
}
登录以后的处理:
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,然后在拦截器中判断
session.setAttribute(Global.USER, user);
request.getRequestDispatcher("/admin/main.jsp").forward(request, response);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
}
}
两个类的配置过程:
<filter>
<filter-name>isLogin</filter-name>
<filter-class>com.bx.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.bx.course.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
下面试一下登录和未登录两种情况下的处理结果:
未登录情况:
已登录情况:
这个过滤器就能把未登录而想进入admin目录里面的main.jsp的用户给阻止了。