📜  Servlet中的身份验证过滤器

📅  最后修改于: 2021-01-09 12:47:50             🧑  作者: Mango

认证过滤器

我们可以在过滤器中执行身份验证。在这里,我们将检查过滤器类中用户提供的密码,如果给定的密码是admin,它将把请求转发到WelcomeAdmin servlet,否则将显示错误消息。

使用过滤器验证用户的示例

让我们看一下使用过滤器验证用户身份的简单示例。

  • index.html
  • MyFilter.java
  • AdminServlet.java
  • web.xml
Name:
Password:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException {}
    
public void doFilter(ServletRequest req, ServletResponse resp,
        FilterChain chain) throws IOException, ServletException {
        
    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("username or password error!");
    RequestDispatcher rd=req.getRequestDispatcher("index.html");
    rd.include(req, resp);
    }
        
}
    public void destroy() {}

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

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class AdminServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        out.print("welcome ADMIN");
        out.close();
    }
}

 
    AdminServlet
    AdminServlet
  

  
    AdminServlet
    /servlet1
  
  
 
  f1
  MyFilter
  
  
  f1
  /servlet1