Expand my Community achievements bar.

SOLVED

I have created aem forms as login form and connected with database through servlet but i m getting logger printed for both if and else.first time value is printed and second time is null.Please answer

Avatar

Level 3

Hi , below is the code I have created login page through adaptive forms and uploaded json file through datasource and created data integrations.Now , i created and api and when i m trying to login the page both if and else is getting printed. First time its printing value and second time its printing value as null for both email and password. Can anyone tell why this is happening? 

 

@Component(
service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=LoginUserPassword Servlet",
"sling.servlet.methods={GET,POST}",
"sling.servlet.paths=" + "/bin/userPasswordLogin",
"sling.servlet.extensions=" + "json"
}
)

 

public class JdbcExternalServiceImpl extends SlingAllMethodsServlet {
private static final Logger log = LoggerFactory.getLogger(JdbcExternalServiceImpl.class);

 

@Reference
private DataSourcePool dataSourcePool;

 

// The datasource.name value of the OSGi configuration containing the connection this OSGi component will use.
private static final String DATA_SOURCE_NAME = "emailPassword-mysql";

 

private final Logger logger = LoggerFactory.getLogger(getClass());

 

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
String email = request.getParameter("email");
session.setAttribute("email", email);
String password = request.getParameter("password");
session.setAttribute("password", password);

 

logger.info("Login successful for email: {} {}", email, password);

 

try {
DataSource dataSource = (DataSource) dataSourcePool.getDataSource(DATA_SOURCE_NAME);
 
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM signUpForm WHERE email=? AND password=?")) {
 
statement.setString(1, email);
statement.setString(2, password);
 
try (ResultSet rs = statement.executeQuery()) {
 
if (rs.next()) {
// Successful login
logger.info("Login successful for email: {}", email);
 
} else {
// Failed login
logger.info("Login failed for email: {}", password);
 
}
}
} catch (SQLException e) {
log.error("Unable to validate SQL connection for [ {} ]", DATA_SOURCE_NAME, e);
// You can send an error message to the client.
}
} catch (DataSourceNotFoundException e) {
log.error("Unable to establish a connection with the JDBC data source [ {} ]", DATA_SOURCE_NAME, e);
// You can send an error message to the client.
}
}
 
 
image.png
 
1 Accepted Solution

Avatar

Correct answer by
Community Advisor

You can try something like below:

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    //Get the email
    String email = request.getParameter("email");
    //Get the password
    String password = request.getParameter("password");

    if (StringUtils.isNotBlank(email) && StringUtils.isNotBlank(password)) {
       
        logger.info("Login attempt for email: {}", email);

        try {
            DataSource dataSource = (DataSource) dataSourcePool.getDataSource(DATA_SOURCE_NAME);

            try (Connection connection = dataSource.getConnection();
                 PreparedStatement statement = connection.prepareStatement("SELECT * FROM signUpForm WHERE email=? AND password=?")) {

                statement.setString(1, email);
                statement.setString(2, password);

                try (ResultSet rs = statement.executeQuery()) {

                    if (rs.next()) {
                        // Successful login
                        logger.info("Login successful for email: {}", email);
                        // You can perform further actions for successful login here.

                    } else {
                        // Failed login
                        logger.info("Login failed for email: {}", email);
                        // You can handle failed login (e.g., send an error response) here.
                    }
                }
            } catch (SQLException e) {
                log.error("Unable to validate SQL connection for [ {} ]", DATA_SOURCE_NAME, e);
                // You can send an error message to the client.
            }
        } catch (DataSourceNotFoundException e) {
            log.error("Unable to establish a connection with the JDBC data source [ {} ]", DATA_SOURCE_NAME, e);
            // You can send an error message to the client.
        }
    } else {
        logger.error("Invalid email or password parameters.");
        // Handle the case of invalid input parameters (e.g., send an error response).
    }
}


But again, the key is how you are invoking the servlet, please follow this which explains when request.getParameter() will work, (based on the encoded used) thread https://stackoverflow.com/questions/3831680/httpservletrequest-get-json-post-data . Remember that you can inspect how the form is invoking the servlet using the debugger tools from the browser.



Esteban Bustamante

View solution in original post

4 Replies

Avatar

Community Advisor

The problem is clearly that you are not passing the "email" and "password" parameters correctly. The first time, the values are attached to the request, but the second time, these values are no longer attached to the request, resulting in an error. Therefore, this class is not the issue (although you could improve your class by adding an initial check to validate if the parameters are present; if not, do not execute anything. This will clearly indicate that the issue is related to the parameters not being sent).

 

Please verify how you are accessing this servlet, especially how you are sending the parameters, as that appears to be the root cause of the problem.



Esteban Bustamante

Avatar

Level 3

I need to check by printing the content of SlingHttpServletRequest request. i tried this but not working

Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
logger.info("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}

Below is the json flow of email and password.I need to get Paramter according to this json currently i am getting null in log for both email and password.Can any one check how to get parameter correctly?

{"afData":{"afUnboundData":{"data":{}},"afBoundData":{"data":{"UserPasswordLoginTest":{"email":"a","password":"a"}}},"afSubmissionInfo":{"lastFocusItem":"guide[0].guide1[0].guideRootPanel[0].afJsonSchemaRoot[0]","stateOverrides":{},"signers":{}}}}

 

 

 

Avatar

Correct answer by
Community Advisor

You can try something like below:

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    //Get the email
    String email = request.getParameter("email");
    //Get the password
    String password = request.getParameter("password");

    if (StringUtils.isNotBlank(email) && StringUtils.isNotBlank(password)) {
       
        logger.info("Login attempt for email: {}", email);

        try {
            DataSource dataSource = (DataSource) dataSourcePool.getDataSource(DATA_SOURCE_NAME);

            try (Connection connection = dataSource.getConnection();
                 PreparedStatement statement = connection.prepareStatement("SELECT * FROM signUpForm WHERE email=? AND password=?")) {

                statement.setString(1, email);
                statement.setString(2, password);

                try (ResultSet rs = statement.executeQuery()) {

                    if (rs.next()) {
                        // Successful login
                        logger.info("Login successful for email: {}", email);
                        // You can perform further actions for successful login here.

                    } else {
                        // Failed login
                        logger.info("Login failed for email: {}", email);
                        // You can handle failed login (e.g., send an error response) here.
                    }
                }
            } catch (SQLException e) {
                log.error("Unable to validate SQL connection for [ {} ]", DATA_SOURCE_NAME, e);
                // You can send an error message to the client.
            }
        } catch (DataSourceNotFoundException e) {
            log.error("Unable to establish a connection with the JDBC data source [ {} ]", DATA_SOURCE_NAME, e);
            // You can send an error message to the client.
        }
    } else {
        logger.error("Invalid email or password parameters.");
        // Handle the case of invalid input parameters (e.g., send an error response).
    }
}


But again, the key is how you are invoking the servlet, please follow this which explains when request.getParameter() will work, (based on the encoded used) thread https://stackoverflow.com/questions/3831680/httpservletrequest-get-json-post-data . Remember that you can inspect how the form is invoking the servlet using the debugger tools from the browser.



Esteban Bustamante

Avatar

Administrator

@MunmunBo Did you find the suggestions from users helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.

 



Kautuk Sahni