对于前几天写的一个简单的学生管理系统,想要实现对于用户登陆检查的功能,就上网自学了filter知识
第一步先在项目目录中创建包filter,在此包下面创建filter名为LoginFilter,代码如下
- package com.student.filter;
-
- import com.student.entity.Users;
- import com.sun.deploy.net.HttpRequest;
-
- import javax.servlet.*;
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
- import java.io.PrintWriter;
-
- /**
- * @Description
- * @Author 单继重
- * @Date 2016/10/24 10:19
- */
- @WebFilter(filterName = "LoginFilter")
- public class LoginFilter implements Filter {
- public void destroy() {
- }
-
- public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
- //chain.doFilter(req, resp);
- HttpServletRequest request = (HttpServletRequest)req;
- HttpServletResponse response = (HttpServletResponse)resp;
- request.setCharacterEncoding("UTF-8");
- response.setContentType("text/html;charset=UTF-8");
- HttpSession session = request.getSession();
- PrintWriter out = response.getWriter();
- Users user = (Users)session.getAttribute("user");
- if(user != null){
- chain.doFilter(request,response);
- } else{
- out.println("您还未登陆,三秒钟后跳转至登录页面");
- //out.println("<script language='javascript'>alert('你还未登录');");
- response.setHeader("refresh","3;/pages/users/login.jsp");
- //response.sendRedirect("/pages/users/login.jsp");
- //request.getRequestDispatcher("/pages/users/login.jsp").forward(request,response);
- }
- }
-
- public void init(FilterConfig config) throws ServletException {
-
- }
-
- }
待解决问题:JS的alert方法无法实现,不知道原因。
未登录跳页使用response.setHeader实现定时跳页功能。
第二步在web.xml文件中配置相应文件,部分代码如下
<filter> <filter-name>LoginFilter</filter-name> <filter-class>com.student.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/pages/student/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/pages/users/update.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/servlet/StudentServlet</url-pattern> </filter-mapping>
然后在以上配置中的所有页面检查session中是否有登陆后存入的信息,如果没有,则跳转至登录页面