jeudi 5 novembre 2015

JSP to use data of the current user

So what I am trying to do is to let another JSP to get the information of the user that just logged in (e.g. to only show information of that particular user that has just logged in instead of showing everything from the database, something that has the same meaning of SELECT * FROM Users WHERE username= current user). Anyway, below is my code, thanks a lot!

<%  
    String userId = request.getParameter("user_id");
    String pwd = request.getParameter("password");
%>
<jsp:useBean id="db" class="ecom.DBConnection" scope="session" />
<jsp:useBean id="user" class="ecom.UserInfo" scope="session" />
<%
Connection conn = db.getConnection(); 

PreparedStatement pstmt = conn.prepareStatement(
    "select * from USERS where user_id=? and password=?");

pstmt.setString(1, userId);
pstmt.setString(2, pwd);    

ResultSet rs = pstmt.executeQuery();    


/* Comment  
    Set the user bean properties if login is successful */
if (rs.next()) {
    user.setLoggedIn(true);
    user.setUserId(rs.getString("user_id"));

} else {
    user.setLoggedIn(false);
}   

rs.close();
pstmt.close();


/* Comment 
    Forward the request to "home.jsp" if login is successful,
    otherwise forward to "error.jsp". */
String forwardURL = null;   
if (user.isLoggedIn()) {
    forwardURL = "home.jsp";
} else {
    forwardURL = "error.jsp";
} 
%>

<jsp:forward page="<%= forwardURL %>" />

Aucun commentaire:

Enregistrer un commentaire