I'm trying to put a simple login form to my application. Im still learning so I'm starting from the simplest.. The login is working perfectly, however I want to get some of the user info to my jsp using JSTL..
example in the username is ABC and password is abc123... I want to pass the data/info of ABC like his role and name to my jsp page.
LoginServlet.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package source;
/**
*
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
UserBean bean = new UserBean();
bean.setUserName(request.getParameter("un"));
bean.setPassword(request.getParameter("pw"));
bean = UserDAO.login(bean);
if (bean.isValid())
{
HttpSession session = request.getSession(true);
session.setAttribute("users",bean);
response.sendRedirect("dd1"); //logged-in page
}
else
response.sendRedirect("invalidLogin.jsp"); //error page
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
UserDAO
package source;
/**
*
*/
import java.sql.*;
public class UserDAO
{
static Connection currentCon = null;
static ResultSet rs = null;
public static UserBean login(UserBean bean) {
//preparing some objects for connection
Statement stmt = null;
String username = bean.getUsername();
String password = bean.getPassword();
String searchQuery = "select * from ifs_userrole where username='"+ username+ "' AND password = md5('"+ password +"')";
try
{
//connect to DB
currentCon = ConnectionManager.getConnection();
stmt=currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
// if user does not exist set the isValid variable to false
if (!more)
{
System.out.println("Sorry, you are not a registered user! Please sign up first");
bean.setValid(false);
}
//if user exists set the isValid variable to true
else if (more)
{
String name = rs.getString("name");
String role = rs.getString("role");
System.out.println("Welcome " + name+ role);
bean.setName(name);
bean.setRole(role);
bean.setValid(true);
}
}
catch (Exception ex)
{
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
//some exception handling
finally
{
if (rs != null) {
try {
rs.close();
} catch (Exception e) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {}
stmt = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
}