过滤器的实现

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("/*")//所有的方法执行都必须使用该过滤器
public class FilterEncoding implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

        在这里我们只需要实现Filter接口重写里面的doFilter()方法,就可以实现字符编码的过滤器了。

3.防止盗链接

        当然我们也可以通过过滤器来实现防止盗链接



import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/user/*")//user文件夹下的文件执行此方法
public class FilterLogin implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        /*由于ServletRequest是HttpServletRequest
        的父类所以在这里要实现他们的子类
        */ 
        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 {

    }

}

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月与清酒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值