Java40Filter过滤器:登录案例

Posted 码农编程录

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java40Filter过滤器:登录案例相关的知识,希望对你有一定的参考价值。


1.入门案例:域对象都写在Servlet中

组件像java中类和接口,域对象像前面类和接口的方法和属性。Listener在spring中,Filter和Servlet是平级关系,不像request和response被包含在Servlet的service方法里。
在这里插入图片描述
New-Project-Java Enterprise-用模板,src文件夹里new-Servlet。

package com.itheima01.hello;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/HelloServlet")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("servlet被访问了");
    }
}
package com.itheima01.hello;
import javax.servlet.*;
import java.io.IOException;

public class HelloFilter implements Filter { //javax.servlet包下的Filter 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException { 
        System.out.println("过滤器被访问了: 请求进来了"); //上行doFilter方法相当于service方法
        filterChain.doFilter(servletRequest,servletResponse); //将请求继续往后发送(允许通行)
    }
    @Override
    public void destroy() {
    }
}
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
           version="3.1">
    <filter>
        <filter-name>HelloFilter01</filter-name>
        <filter-class>com.itheima01.hello.HelloFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HelloFilter01</filter-name>
        <url-pattern>/HelloServlet</url-pattern> <!-- 要拦截的地址,url中 -->
    </filter-mapping>


    <filter>
        <filter-name>LifeFilter</filter-name>
        <filter-class>com.itheima02.life.LifeFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>LifeFilter</filter-name>
        <url-pattern>/LifeServlet</url-pattern>
    </filter-mapping>
</web-app>

在这里插入图片描述
在这里插入图片描述

2.生命周期:注解也要导包

package com.itheima02.life;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/LifeServlet")
public class LifeServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("servlet init");
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("servlet service");
    }
    @Override
    public void destroy() {
        System.out.println("servlet destroy");
    }
}
package com.itheima02.life;
import javax.servlet.*;
import java.io.IOException;

public class LifeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter doFilter before");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("Filter doFilter after");
    }
    @Override
    public void destroy() {
        System.out.println("Filter destroy");
    }
}

还没有访问,服务器点乌龟运行时idea就打印如下。
在这里插入图片描述
在这里插入图片描述
如下servlet init只打印一次。
在这里插入图片描述
如下点击红色方块关闭服务器。
在这里插入图片描述
上面New-Serlvet都是有模板注解,New-Filter也可以设置模板,用注解替换web.xml。
在这里插入图片描述

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
@javax.servlet.annotation.WebFilter(urlPatterns = "/")
public class ${Class_Name} implements javax.servlet.Filter {   
    public void init(javax.servlet.FilterConfig config) throws javax.servlet.ServletException {
    }
    public void doFilter(javax.servlet.ServletRequest req, javax.servlet.ServletResponse resp, javax.servlet.FilterChain chain) throws javax.servlet.ServletException, java.io.IOException {
        chain.doFilter(req, resp);
    }
    public void destroy() {
    }
}

在这里插入图片描述

3.案例:登录案例最后改进

在这里插入图片描述

//index.jsp
<%-- Created by IntelliJ IDEA. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>
            <form action="/Servlet01" method="post">
                <input type="text" name="msg" value="这是信息1"> <br>
                <input type="submit">
            </form>
            <hr>
            
            <form action="/Servlet02" method="post">
              <input type="text" name="msg" value="这是信息2"> <br>
              <input type="submit">
            </form>
            <hr>
            
            <a href="/AServlet">/AServlet</a> <br>
            <a href="/BServlet">/BServlet</a> <br>
  </body>
</html>
package com.itheima04.post;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/Servlet01")
public class Servlet01 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = request.getParameter("msg");
        System.out.println("servlet01:" + msg);
    }
}
package com.itheima04.post;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/Servlet02")
public class Servlet02 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = request.getParameter("msg");
        System.out.println("servlet02:" + msg);
    }
}

在这里插入图片描述
在这里插入图片描述

package com.itheima04.post;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class PostFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {        
        HttpServletRequest request = (HttpServletRequest) req; //基于http协议的请求
        String method = request.getMethod();
        if("post".equalsIgnoreCase(method)){
            request.setCharacterEncoding("utf-8");   //请求
        }            
        resp.setContentType("text/html;charset=utf-8");   //响应体中文乱码
        chain.doFilter(req, resp); //引用数据类型,req和request指向同一个地址
    }
    public void destroy() {
    }
}

在这里插入图片描述
如下是登陆案例的权限过滤,如上c:if里可以注释了。

package com.itheima.login.web;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//@WebFilter(urlPatterns = "/success.jsp") //urlPatterns是一个string数组,String[] urlPatterns() default {};
@WebFilter(urlPatterns = {"/success.jsp","/buycar.jsp","*.do"})  //多个,{}不能省略
public class PrivilegeFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String name = (String) request.getSession().getAttribute("name");
        if(name == null){
            request.setAttribute("errorMsg","请先登录!!!");
            request.getRequestDispatcher("/login.jsp").forward(request,resp);
        }

        chain.doFilter(req, resp);
    }

    public void destroy() {
    }
}

在这里插入图片描述

4.多过滤器:先执行小ASCII

在这里插入图片描述

package com.itheima05.multi;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/AServlet")
public class AServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

以上是关于Java40Filter过滤器:登录案例的主要内容,如果未能解决你的问题,请参考以下文章

JAVAWEB学习笔记24_filter实现自动登录和解决全局的编码问题

ServletJava Servet Filter 过滤器

JavaWeb之Filter&Listener

java---servlet与filter的联系与区别

关于java,过滤html请求的Filter中跳转页面的问题。

过滤器与监听器 ----javaweb-10