• Filter过滤器问题


    SSH框架一般在登录时,都有过滤器Filter,防止在未登录的情况下访问不该访问的页面

    1、首先写一下Filter的类来实现Filter接口

    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.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import com.lovecar.entity.Admin;

    public class LoginFilter extends HttpServlet implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
    HttpServletRequest servletRequest = (HttpServletRequest) request;
    HttpServletResponse servletResponse = (HttpServletResponse) response;
    HttpSession session = servletRequest.getSession();
    //获得用户请求的URI
    String path = servletRequest.getRequestURI();
    Admin admin = (Admin) session.getAttribute("admin");

    //无需过滤的页面
    if(path.indexOf("adminlogin.jsp") > -1){
    chain.doFilter(servletRequest, servletResponse);
    return ;
    }

    if(admin == null || "".equals(admin)){
    //跳转到登陆页面,这里使用了绝对路径
    servletResponse.sendRedirect(servletRequest.getContextPath()+"/adminlogin.jsp");
    }else{
    chain.doFilter(request, response);
    }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    // TODO Auto-generated method stub

    }

    }

    2、web.xml里配置需要登录权限验证

    <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.lovecar.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    作者:战旗 内容声明: 本内容属自己学习使用 ,若有抄袭情邮件(zhanqi3712@qq.com)告知 ,本人会尽快删除
  • 相关阅读:
    Python基础(三)
    离线部署k8s集群
    linux安装python3
    vue elementui table 内按钮跳转页面
    js 正则表达式 验证数字或字母
    ps2020 将图片中的字清除 并且不损坏背景图
    css 背景图片铺满
    ps 缩放快捷键
    css 字体阴影和边框阴影
    ps 修改图片图层大小
  • 原文地址:https://www.cnblogs.com/liuyun-10/p/6386860.html
Copyright © 2020-2023  润新知