Servlet认证过滤器介绍和用法详解

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

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

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

在这里, 我们创建了4个文件:

  • index.html
  • MyFilter.java
  • AdminServlet.java
  • web.xml

index.html

<form action="servlet1">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>

<input type="submit" value="login">

</form>

MyFilter.java

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() {}

}

AdminServlet.java

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();
	}
}

web.xml

<web-app>
 <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>f1</filter-name>
  <filter-class>MyFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>f1</filter-name>
  <url-pattern>/servlet1</url-pattern>
  </filter-mapping>
  
</web-app>

下载此示例(使用Myeclipse IDE开发)

下载此示例(使用Eclipse IDE开发)

下载此示例(使用Netbeans IDE开发)

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?