编写身份验证过滤器

本文案例是在过滤器中完成身份验证。大致流程是:先在过滤器类中检查用户提供的密码,如果给定的密码是admin,将请求转发到AdminServlet,否则将显示错误消息。

1 编写登录表单

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>一点教程网-过滤器完成用户权限验证</title>
    <meta http-equiv="content-type" content="text/html" charset="UTF-8">
</head>
<body>
<form action="servlet1" method="post">
    用户名:<input type="text" name="name"/><br/>
    密码:<input type="password" name="password"/><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

2 编写AdminServlet

AdminServlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class AdminServlet extends HttpServlet{

    public void doPost(HttpServletRequest req,HttpServletResponse res)
            throws ServletException,IOException
    {
        res.setContentType("text/html;charset=utf-8");
        PrintWriter out = res.getWriter();

        out.print("欢迎你,管理员");
        out.close();
    }

}

3 编写AuthFilter

AuthFilter:

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *一点教程网 - http://www.yiidian.com
 */
public class AuthFilter implements Filter {

    public void init(FilterConfig arg0) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {

        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out=resp.getWriter();

        String password=req.getParameter("password");
        if(password.equals("admin")){
            chain.doFilter(req, resp);//sends request to next resource
        }
        else{
            out.print("用户名或密码错误!");
            RequestDispatcher rd=req.getRequestDispatcher("index.jsp");
            rd.include(req, resp);
        }
    }

    public void destroy() {

    }
}

4 配置web.xml

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_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>AdminServlet</servlet-name>
        <servlet-class>AdminServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>AdminServlet</servlet-name>
        <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>AuthFilter</filter-name>
        <filter-class>AuthFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>AuthFilter</filter-name>
        <url-pattern>/servlet1</url-pattern>
    </filter-mapping>
</web-app>

5 运行测试

输入正确密码(admin),显示如下:

输入错误密码,显示如下:

热门文章

优秀文章