This is an extremely bad practice. You really shouldn't pass the username and password plain vanilla around through requests. Make use of sessions, in JSP/Servlet there you have the HttpSession
for. There is really also no need to hit the DB again and again on every request. That's unnecessarily expensive. Just put User
in session and use the Filter
to check its presence on every request.
Start with a login.jsp
:
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit"> ${error}
</form>
Then, create a LoginServlet
which is mapped on url-pattern
of /login
and has the doPost()
implemented as follows:
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.
}
Then, create a LoginFilter
which is mapped on url-pattern
of /secured/*
(you can choose your own however, e.g. /protected/*
, /restricted/*
, /users/*
, etc, but this must at least cover all secured pages, you also need to put the JSP's in the appropriate folder in WebContent) and has the doFilter()
implemented as follows:
if (((HttpServletRequest) request).getSession().getAttribute("user") != null) {
chain.doFilter(request, response); // User is logged in, just continue request.
} else {
((HttpServletResponse) response).sendRedirect("/login.jsp"); // Not logged in, show login page. You can eventually show the error page instead.
}
That should be it. Hope this helps.
To get the idea how an UserDAO
would look like, you may find this article useful. It also covers how to use PreparedStatement
to save your webapp from SQL injections.