JavaWeb实现过滤器验证登录

偏执的太偏执、 2022-06-13 14:41 375阅读 0赞
  1. **今天正好学到过滤器,就想着用博客记录下来,方便以后查找,也供大家参考,由于刚学,所以不足之处也请大家见谅。**
  2. 1、写一个类实现Filter接口:
  3. public class Login implements Filter{
  4. public void init(FilterConfig config) throws ServletException{
  5. }
  6. public void doFilter(ServletRequest request,
  7. ServletResponse response,
  8. FilterChain chain) throws IOException,ServletException{
  9. HttpServletRequest req = (HttpServletRequest) request;
  10. HttpServletResponse resp = (HttpServletResponse) response;
  11. HttpSession session = req.getSession();
  12. //用来判断是否是从登录页登录,一些文章是直接判断是否有session,但这样如果登录成功后退回登录页重新登录,如果密码错误也会登录成功,因为此时session还在,就直接跳过验证登录成功了,所以这里我采用这种方法,直接判断是否是从登录页登录的。
  13. String loginName = request.getParameter("loginName");//获取登录页的用户名和密码
  14. String password = request.getParameter("password");
  15. if(loginName!=null && password!=null){ //可以取到表单的信息,说明正在登录页验证登录
  16. if("admin".equals(loginName) && "123456".equals(password)){
  17. //验证通过
  18. session.setAttribute("loginUser",loginName);
  19. chain.doFilter(request, response);
  20. }
  21. else{ //用户名或密码错误
  22. request.getRequestDispatcher("/index.html").forward(request, response);
  23. }
  24. }
  25. else if(session.getAttribute("loginUser")!=null){
  26. //不是从登录页进去的,但存在已登录过的标志,所以可以进去
  27. chain.doFilter(request, response);
  28. }
  29. else {
  30. //没有经过登录验证
  31. request.getRequestDispatcher("/index.html").forward(request, response);
  32. }
  33. }
  34. public void destroy() {
  35. // TODO Auto-generated method stub
  36. }
  37. }
  38. **这里需要注意的是,session本身是属于HTTP协议的范畴,但是doFilter()方法中定义的是ServletRequest类型的对象,那么要想取得session,则必须进行向下转型,将ServletRequest变为HttpServletRequest接口对象,才能通过getSession()方法取得session对象。**

2、配置文件web.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  3. <display-name>过滤器简单验证登录</display-name>
  4. <welcome-file-list>
  5. <welcome-file>index.html</welcome-file>
  6. <welcome-file>index.htm</welcome-file>
  7. <welcome-file>index.jsp</welcome-file>
  8. <welcome-file>default.html</welcome-file>
  9. <welcome-file>default.htm</welcome-file>
  10. <welcome-file>default.jsp</welcome-file>
  11. </welcome-file-list>
  12. <filter>
  13. <filter-name>Login</filter-name>
  14. <filter-class>cn.login.Login</filter-class><!-- 类所在的位置 -->
  15. </filter>
  16. <filter-mapping>
  17. <filter-name>Login</filter-name>
  18. <url-pattern>/*</url-pattern>
  19. </filter-mapping>
  20. </web-app>

发表评论

表情:
评论列表 (有 0 条评论,375人围观)

还没有评论,来说两句吧...

相关阅读