过滤器的实现

过滤器的实现,第1张

过滤器的实现

1.过滤器的概念

        用于拦截客户端和服务器之间的消息,并且过滤二者之间的传递的数据,在项目中我们常常实现Filter接口并且重写其中的doFilter()方法来创建一个过滤器。

2.字符编码过滤器

在这之前我们经常使用的字符编码转换是在每个servlet中的post方法写入

resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");

  代码,而用过滤器的话,我们不需要每次都写入这两行代码,字符编码过滤器如下所示:

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(" 
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;
        String name = (String) request.getSession().getAttribute("name");
        //拿到登录页面存储的name值,并对其进行判断
        if (name!=null){
            chain.doFilter(req, resp);//程序接着进行
        }else {
            response.sendRedirect("../index.jsp");
        //程序重定向到index.jsp页面 ../的意思是返回上一级目录
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}

这样就可以实现防止盗链接了。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5684844.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-18
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存