过滤器的简单使用

下面的代码为设置页面的编码问题

package Filter;

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

/**
 * 设置所有页面的编码
 */
@WebFilter("/*")
public class setEnCoding implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest request =  servletRequest;
        ServletResponse response =  servletResponse;
        //设编
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

下面的代码设置的是指定特定的servlet通过和加了防跳墙等

package Filter;

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

@WebFilter("/*") //拦截所有
public class StopUser implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转化类型,要使用到路径
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
        //路径 得到请求行的资源名称
        String requestURI = servletRequest1.getRequestURI();
        //防跳墙
        HttpSession session = servletRequest1.getSession();
        //如果是登录界面,验证码,Login(处理表单)注册 处理注册 这五个直接放走
        if (requestURI.endsWith("/login.jsp") || requestURI.endsWith("/Code") || requestURI.endsWith("/Login") || requestURI.endsWith("/register.jsp") || requestURI.endsWith("/register")){
            //放行走
            filterChain.doFilter(servletRequest,servletResponse);
        }else if (session == null || session.getAttribute("fangtiqoqiang") == null){
            servletResponse1.sendRedirect("login.jsp");
        }else if (session != null || session.getAttribute("fangtiaoqiao") != null){
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}

你可能感兴趣的:(tomcat,servlet)