String sql="select * from reg where username='"+user+"' and pass='"+pwd+"'"; rs=st.executeQuery(sql); if(rs.next()) { chain.doFilter(request,response); } else sc.getRequestDispatcher("/error.html").forward(request,response);
String sql=”select * from reg where username='”+user+”‘ and pass='”+pwd+”‘”;
这是一个非常糟糕的做法.这种方法要求用户名和密码都通过请求传递普通香草.而且,你有一个SQL注入攻击漏洞.
利用会话,在JSP / Servlet中你有HttpSession
.实际上也没有必要在使用过滤器的每个请求上一次又一次地命中数据库.这是不必要的昂贵.只需使用Servlet将User置于会话中,并使用Filter检查每个请求的存在.
从/login.jsp开始:
<form action="login" method="post"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit"> ${error} </form>
然后,创建一个LoginServlet,它映射到/ login的url-pattern上,并按如下方式实现doPost():
String username = request.getParameter("username"); String password = request.getParameter("password"); User user = userDAO.find(username, password); if (user != null) { request.getSession().setAttribute("user", user); // Put user in session. response.sendRedirect("/secured/home.jsp"); // Go to some start page. } else { request.setAttribute("error", "Unknown login, try again"); // Set error msg for ${error} request.getRequestDispatcher("/login.jsp").forward(request, response); // Go back to login page. }
然后,创建一个映射在/ secured / *的url-pattern上的LoginFilter(你可以选择你自己的,例如/ protected / *,/ restricted / *,/ users / *等,但这必须至少涵盖所有安全页面,您还需要将JSP放在WebContent中的相应文件夹中)并具有如下实现的doFilter():
HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); String loginURI = request.getContextPath() + "/login.jsp"; boolean loggedIn = session != null && session.getAttribute("user") != null; boolean loginRequest = request.getRequestURI().equals(loginURI); if (loggedIn || loginRequest) { chain.doFilter(request, response); // User is logged in, just continue request. } else { response.sendRedirect(loginURI); // Not logged in, show login page. }
那应该是它.希望这可以帮助.
要了解UserDAO的外观,您可能会发现this article很有用.它还介绍了如何使用PreparedStatement
保存您的Web应用程序免受SQL注入攻击.
也可以看看:
> How to redirect to Login page when Session is expired in Java web application?
> Authentication filter and servlet for login
> How to handle authentication/authorization with users in a database?