java--过滤器

Posted xanlv

tags:

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

CharacterFilter

package cn.hncu.filter;

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;

/*
 * 过滤器开发:
 * 1.写一个类实现Filter接口
 * 2.配置web.xml (配置<filter>和<filter-mapping>两个元素)
 * 
 */

public class CharacterFilter implements Filter

    private String charset;
    //过滤器的init在服务器一启动时就会执行。
    //servlet如果配置了load-on-startup选项则也会在服务器启动
    //时就执行初始化,否则只有在第一次访问该servlet时才会执行。
    @Override
    public void init(FilterConfig filterConfig) throws ServletException 
        System.out.println("CharacterFilter-init...");
        this.charset=filterConfig.getInitParameter("charset");
    

    @Override//该方法在拦截到相应请求或响应时才会执行
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException 
        System.out.println("CharacterFilter-doFilter...拦截请求");//拦截请求
        //request.setCharacterEncoding("utf-8");//编码写死了
        request.setCharacterEncoding(charset);
        //编码写活,让用户可配置(在web.xml中修改参数)
        chain.doFilter(request, response);//放行
        System.out.println("CharacterFilter-doFilter...拦截响应");//拦截响应
        response.setContentType("text/html;charset="+charset);
    

    @Override
    public void destroy() 
        System.out.println("CharacterFilter-destory...");

    


LoginSecureFilter

package cn.hncu.filter;

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 LoginSecureFilter implements Filter

    @Override
    public void init(FilterConfig filterConfig) throws ServletException 
        System.out.println("LoginSecureFilter-init...");
    

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException 
        System.out.println("LoginSecureFilter-doFilter...拦截请求");//拦截请求
        HttpServletRequest req=(HttpServletRequest) request;
        String name=(String) req.getSession().getAttribute("name");

        if(name==null||name.trim().equals(""))
            //踢到登录页面
            //注意,重定向时路径中的第一个"/"是指Tomcat的根目录,因此这里必须加一个项目名。
            ((HttpServletResponse)response).sendRedirect(req.getContextPath()+"/index.jsp");
        
        chain.doFilter(request, response);//放行
        System.out.println("LoginSecureFilter-doFilter...拦截响应");//拦截响应
    

    @Override
    public void destroy() 

    


web.xml–配置Filter和Servlet

<?xml version="1.0" encoding="UTF-8"?>                          
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name></display-name>
  <!-- 过滤器链中,这一段的配置顺序决定init的执行顺序 -->



  <filter>
    <filter-name>login</filter-name>
    <filter-class>cn.hncu.filter.LoginSecureFilter</filter-class>
  </filter>
  <filter>
    <filter-name>three</filter-name>
    <filter-class>cn.hncu.filter.CharacterFilter</filter-class>
    <init-param>
        <param-name>charset</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
  </filter>

  <!-- 拦截路径设置说明:
      1.  “/*” 表示拦截所有资源
      2.  “*.jsp” 表示拦截所有jsp页面的请求与响应
      3.  “/jsps/*.jsp”  ※不能这样写,格式错误※
      4.  “/jsps/*” 表示拦截jsps目录下的所有资源 
      5.  “/LoginServlet” 表示只拦截映射路径为“/LoginServlet”的这一个servlet
      6.  “login” 表示只拦截名“login”的servlet(可以把jsp页面配置成serlvet)
   -->
  <!-- 过滤器链中,这一段的配置顺序决定拦截顺序(过滤器的过滤顺序) -->

  <filter-mapping>
    <filter-name>three</filter-name>
    <!-- 指定拦截访问后台的哪些资源(servlet,jsp,jpg文件等), '/*'代表所有资源 -->
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.hncu.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>BuyServlet1</servlet-name>
    <servlet-class>cn.hncu.servlet.BuyServlet1</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>BuyServlet2</servlet-name>
    <servlet-class>cn.hncu.servlet.BuyServlet2</servlet-class>
  </servlet>



  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>BuyServlet1</servlet-name>
    <url-pattern>/buy/buy1</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>BuyServlet2</servlet-name>
    <url-pattern>/buy/buy2</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

初始化顺序

主页面index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

  </head>

  <body>
    <h2>这是主页...OKOK</h2>
    <c:url value="/login"/>
    <form action='<c:url value="/login"/>' method="post">
        姓名:<input type="text" name="name"/><br/>
        <input type="submit" value="提交">
    </form>

    <a href='<c:url value="/buy/buy1"/>'>商品1</a>
    <a href='<c:url value="/buy/buy2"/>'>商品2</a>
    <a href='<c:url value="/jsps/a.jsp"/>'>欢迎</a>
  </body>
</html>

/jsps/wel.jsp–登录成功页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

  </head>

  <body>
  <h2>这是欢迎页面</h2>
        欢迎你,$name!
  </body>
</html>

/jsps/a.jsp–欢迎页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>

  <body>
    <h2>很多贵宾才能看到的商品</h2>
        欢迎你,$name! <br/>
        <img  src="<c:url value='/imgs/1.png'/>" />   
  </body>
</html>

LoginServlet–登录,未被LoginSecureFilter拦截

package cn.hncu.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet 

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 

        doPost(request, response);
    

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
        String name=request.getParameter("name");
        //....//省略若干行代码(调用service及dao层,到数据库中验证身份)
        request.getSession().setAttribute("name", name);//这里假设验证成功
        System.out.println(request.getContextPath()+"/jsps/wel.jsp");
        response.sendRedirect(request.getContextPath()+"/jsps/wel.jsp");
//      response.sendRedirect(request.getContextPath()+"/index.jsp");
    


BuyServlet1–BuyServlet2同(映射路径为”/buy/buy1”和“/buy/buy2”)

package cn.hncu.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BuyServlet1 extends HttpServlet 

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 

        doPost(request, response);
    

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 

        String name = request.getParameter("name");
        PrintWriter p=response.getWriter();
        p.print(name+"访问了buy1");
        p.print("进行购物---调用service层的相应逻辑");//要求必须登录过后才能访问该模块
    


第一次访问主页的filter拦截

未登录时访问超链接 欢迎

登陆

以上是关于java--过滤器的主要内容,如果未能解决你的问题,请参考以下文章

让 Indy call 与 Paypal IPN 合作发布“贵宾犬”更改

软件编程乐易贵宾VIP教程 - JS改写+网页操作系列教程

乐易贵宾VIP教程:百度贴吧 - QQ部落 - QQ空间 Post实战系列视频课程

VIP客户插队银行优先服务,有没有道理,你怎么看?

java 线程图解[基础篇]

Vue调试神器之Vue.js devTools