JavaWeb Servlet中Filter过滤器的详解(java过滤器怎么写)奔走相告

随心笔谈1年前 (2023)发布 admin
99 0



package com.baidu.web;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyFilter implements Filter{

@Override
public void destroy() {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//对请求request进行处理
HttpServletResponse resp=(HttpServletResponse)response;
HttpServletRequest req=(HttpServletRequest) request;
String username=(String) req.getSession().getAttribute(“username”);
if(req.getRequestURI().contains(“Buy”) || req.getRequestURI().contains(“collect”)){
if(username==null || username.equals(“”)){ //满足过滤要求,进行处理
req.getRequestDispatcher(“/login.jsp”).forward(req, resp);
return;
}
}
chain.doFilter(req, resp);
//对相应response进行处理
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
//filterConfig,通过filterConfig的getServletContext() 方法可以获得 ServletContext
}
}

© 版权声明

相关文章