Loading

Java之Filter

MVC三层架构

什么是MVC?

Model View Controller 模型 视图 控制器

模型:可理解为实体类与表中对应的字段

视图:比如jsp页面

控制器:Servlet控制页面跳转与request和response处理

Filter过滤器

Filter:过滤网站数据,如登录验证,中文乱码处理等

Filter开发步骤:1、导包。2、编写过滤器。3、web.xml配置Filter

Filter接口为import javax.servlet.*;包下的。implents接口需要实现三个方法

//初始化
public void init(FilterConfig filterConfig) throws ServletException {

}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

}

//销毁
public void destroy() {

}

编写Filter

1、过滤器中所有代码在过滤特定请求时都会执行

2、必须要让过滤器filterChain.doFilter()将req和resp转交给后面的过滤器,继续通行

3、filterChain.doFilter(servletRequest,servletResponse); //让我们的请求继续走,如果不写,程序到这里就被拦截停止。后面还有其他过滤器,需要把这次的req和resp传给后面的Filter

public class CharacterEncodingFilter implements Filter {

    /*
    1、过滤器中所有代码在过滤特定请求时都会执行
    2、必须要让过滤器filterChain.doFilter()将req和resp转交给后面的过滤器,继续通行
     */
    //初始化:web服务器启动就进行了初始化
public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncodingFilter Init..."); }

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletRequest.setCharacterEncoding("UTF-8");
    servletResponse.setCharacterEncoding("UTF-8");
    System.out.println("Filter run start......");
    filterChain.doFilter(servletRequest,servletResponse);   //让我们的请求继续走,如果不写,程序到这里就被拦截停止。后面还有其他过滤器,需要把这次的req和resp传给后面的Filter
    System.out.println("Filter run stop......");

}

//销毁:web服务器关闭时,Filter销毁
public void destroy() { System.out.println("CharacterEncodingFilter Destmroy..."); }
}

注册Filter

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.zh1z3ven.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
<!--        在此设定的路由下的请求都会经过Filter处理-->
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>

下面简单测试下,创建两个路由,一个走过滤器,一个不走过滤器

servlet

public class ShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("你好,世界");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Web.xml

<servlet>
    <servlet-name>show</servlet-name>
    <servlet-class>com.zh1z3ven.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>show</servlet-name>
    <url-pattern>/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>show</servlet-name>
    <url-pattern>/servlet/show</url-pattern>
</servlet-mapping>

Filter实现权限拦截

Jsp中实现过滤

<%--在jsp中实现鉴权。如果用户未携带session就跳转到login页面--%>
<%
    Object user_session = request.getSession().getAttribute("USER_SESSION");
    if (user_session==null){
        response.sendRedirect("/login.jsp");
    }
%>

但是这样success.jsp和error.jsp都要写一遍,代码写的就很臃肿,不如Filter来实现比较方便和易于管理

主要实现用户登录之后,判断是否存在session,若有才可以进入/sys/success页面。若不存在则跳到error界面。

Login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<h2>登录</h2>
<form action="/servlet/login" method="post" >
    <input name="username" type="text">
    <input name="submit" type="submit">
</form>

</body>
</html>

error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>error</title>
</head>
<body>
<h2>error</h2>
<h2><a href="/login.jsp">返回首页</a> </h2>
</body>
</html>

/sys/success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
<h2>success</h2>
<p><a href="/servlet/logout" name="logout">logout</a> </p>
</body>
</html>

LoginServlet

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");

        if ("admin".equals(username)){
            req.getSession().setAttribute(Contant.USER_SESSION,req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else {
            resp.sendRedirect("/error.jsp");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

LogoutServlet

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Object user_session = req.getSession().getAttribute(Contant.USER_SESSION);

        if (user_session!=null){
            req.getSession().removeAttribute(Contant.USER_SESSION);
            resp.sendRedirect("/login.jsp");
        }else {
            resp.sendRedirect("/login.jsp");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

SysFilter

public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest Req = (HttpServletRequest) servletRequest;
        HttpServletResponse Resp = (HttpServletResponse) servletResponse;

        if (Req.getSession().getAttribute(Contant.USER_SESSION)==null){
            Resp.sendRedirect("/error.jsp");
        }


        filterChain.doFilter(Req,Resp);
    }

    public void destroy() {

    }
}

/util/Contant.java 将session处理为常量,便于编写和修改代码

public class Contant {
    public final static String USER_SESSION = "USER_SESSION";
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.zh1z3ven.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/servlet/login</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>logout</servlet-name>
        <servlet-class>com.zh1z3ven.servlet.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>logout</servlet-name>
        <url-pattern>/servlet/logout</url-pattern>
    </servlet-mapping>
  
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.zh1z3ven.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/sys/*</url-pattern>
    </filter-mapping>

</web-app>
posted @ 2021-08-05 00:24  Zh1z3ven  阅读(368)  评论(0编辑  收藏  举报