Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

Cannot get FORM Data

Avatar

Level 3

I have created a form in aem using core form container and have defined two fields username and password.I want to get this data inside a servlet.

 

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException{
String groupName="Janhavi";
String userName = request.getRequestParameter("userName").getString();
String password= request.getRequestParameter("password").getString();
 
this is my function to get username and password. When I am creating static user and password the code works fine but when I use the above mentioned function I am not able to get data from the Form.
 
is there any issue in request.getRequestParameter or is there any other method to retrive Form Data?
 
Thank you in advance
15 Replies

Avatar

Community Advisor

Hi @janhavi_singh ,

 

Have you tried request.getParameter() method ?

String userName = request.getParameter("userName");
String password = request.getParameter("password");

we usually use getParamter() only, could you please check?

Avatar

Level 3
package com.ranosys.website.core.servlets;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.PropertyType;
import javax.jcr.ValueFactory;
import org.apache.sling.api.resource.ResourceResolverFactory;
@Component(service = Servlet.class, property = {
Constants.SERVICE_DESCRIPTION + "=HTTP servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths=" + "/bin/servlets/registration-form"
})
public class RegistrationForm extends SlingAllMethodsServlet {
 
private static final long serialVersionUID = 1L;
@Reference
ResourceResolverFactory resolverFactory;


/**
* Logger
*/
private static final Logger log = LoggerFactory.getLogger(RegistrationForm.class);
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException{
String groupName="Janhavi";
String userName = request.getParameter("userName");
String password= request.getParameter("password");

 
 
Session session = null;
ResourceResolver resourceResolver = null;
 
try {
log.info("Servlet running");
resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
session = resourceResolver.adaptTo(Session.class);
final UserManager userManager= resourceResolver.adaptTo(UserManager.class);
Group group = null;
if (userManager.getAuthorizable(groupName) == null) {
group = userManager.createGroup(groupName);

ValueFactory valueFactory = session.getValueFactory();
Value groupNameValue = valueFactory.createValue(groupName, PropertyType.STRING);
group.setProperty("./profile/givenName", groupNameValue);
session.save();
log.info("---> {} Group successfully created.", group.getID());
} else {
log.info("---> Group already exist..");
}
// Create a User
User user = null;
if (userManager.getAuthorizable(userName) == null) {
user = userManager.createUser(userName, password);

ValueFactory valueFactory = session.getValueFactory();
Value firstNameValue = valueFactory.createValue("Arpit", PropertyType.STRING);
user.setProperty("./profile/givenName", firstNameValue);

Value lastNameValue = valueFactory.createValue("Bora", PropertyType.STRING);
user.setProperty("./profile/familyName", lastNameValue);

Value emailValue = valueFactory.createValue("arpit.p.bora@gmail.com", PropertyType.STRING);
user.setProperty("./profile/email", emailValue);
session.save();

// Add User to Group
Group addUserToGroup = (Group) (userManager.getAuthorizable(groupName));
addUserToGroup.addMember(userManager.getAuthorizable(userName));
session.save();
}
}
catch (Exception e) {
log.error("exception is >>>>>>>" +e.getMessage());
} finally {
if (session != null && session.isLive()) {
session.logout();
}
if (resourceResolver != null)
resourceResolver.close();
}
response.getWriter().write("------Registration Successful---------");
}
}
 
Here it is
 

Avatar

Level 3

@janhavi_singh ,

 

Can you please tell me how are you passing the form data to the servlet call?

Avatar

Level 3

I have created a form which looks like this and have passed the endpoint for the servlet in the core form container Screenshot from 2022-06-07 18-50-24.png

Avatar

Level 3

@janhavi_singh ,

 

Please check the name in the form field dialog as shown in the below image is matching with your request parameter name or not. This might be a reason for this.

 

sravs_0-1654611749976.png

If this is also not the case, then check for the servlet call while submitting the form in network tab from developer console and see what is the payload for that.

 

Regards,

Sravani

 

Avatar

Level 3

I think this method is valid only for the adaptive forms and not the core form container component of AEM

Avatar

Community Advisor

Can you check if the input fields has the values and name attribute when form is submitted 



<div class="container responsivegrid">
  <form method="POST" action="/content/core-components-examples/library/core-form/form-text.html" id="new_form" name="new_form" enctype="multipart/form-data" class="cmp-form aem-Grid aem-Grid--12 aem-Grid--default--12">
    <input type="hidden" name=":formstart" value="/content/core-components-examples/library/core-form/form-text/jcr:content/root/responsivegrid/demo/component/container">
    <input type="hidden" name="_charset_" value="utf-8">
    <div class="text aem-GridColumn aem-GridColumn--default--12">
      <div class="cmp-form-text">
        <label for="form-text-991299145">Name</label>
        <input class="cmp-form-text__text" data-cmp-hook-form-text="input" type="text" id="form-text-991299145" placeholder="Please enter your name" name="firstName">
      </div>
    </div>
    <div class="text aem-GridColumn aem-GridColumn--default--12">
      <div class="cmp-form-text" data-cmp-required-message="You need to add your email to log in">
        <label for="form-text-2014401237">E-Mail</label>
        <input class="cmp-form-text__text" data-cmp-hook-form-text="input" type="email" id="form-text-2014401237" placeholder="Please enter your E-Mail" name="email" required="">
      </div>
    </div>
    <div class="text aem-GridColumn aem-GridColumn--default--12">
      <div class="cmp-form-text">
        <label for="form-text-1948726228">Message</label>
        <textarea class="cmp-form-text__textarea" data-cmp-hook-form-text="input" id="form-text-1948726228" placeholder="Please enter your message" name="textarea" rows="2"></textarea>
      </div>
    </div>
  </form>
</div>

Avatar

Community Advisor

Hi @janhavi_singh,

By default Core Form Container is not supporting any additional servlets to handle POST request. It is handled by com.adobe.cq.wcm.core.components.internal.servlets.CoreFormHandlingServlet.

I am assuming that your custom servlet is never called, when you are submit your form. If you want to use your custom servlet registered under specific path, you will need to customize /apps/core/wcm/components/form/container/v2/container and do some modification in container.html. By some modification, I mean to set attribute action to point to your servlet path, e.g.

<!--/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ~ Copyright 2016 Adobe
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/-->
<form data-sly-use.container="com.adobe.cq.wcm.core.components.models.form.Container"
      data-sly-use.grid="com.day.cq.wcm.foundation.model.responsivegrid.ResponsiveGrid"
      method="${container.method}" action="/bin/servlets/registration-form" id="${container.id}" name="${container.name}"
      enctype="${container.enctype}"
      class="cmp-form ${grid.cssClass}">
    <div data-sly-test="${container.errorMessages}"
         data-sly-list.item="${container.errorMessages}"
         class="cmp-form-error">
        <p class="cmp-form-error__item">${item}</p>
    </div>
    <input type="hidden" name=":formstart" value="${resource.path}"/>
    <input type="hidden" name="_charset_" value="utf-8"/>
    <input data-sly-test="${container.redirect}" type="hidden" name=":redirect" value="${container.redirect @ extension='html'}"/>
    <sly data-sly-repeat.paragraph="${grid.paragraphs}"
         data-sly-resource="${paragraph.path @ resourceType=paragraph.resourceType, decorationTagName='div', cssClassName=paragraph.cssClass}"></sly>
    <sly data-sly-resource="${resource.path @ resourceType=container.resourceTypeForDropArea, appendPath='/*', decorationTagName='div', cssClassName='new section aem-Grid-newComponent'}"
         data-sly-test="${wcmmode.edit || wcmmode.preview}"></sly>
</form>

In below thread I have described step by step 2 scenarios how to extend Form Core Container:

  1. Creating custom action - this is correct way, because you are not changing any existing mechanism you will use extension points provided by Form Core Container.
  2. Utilize custom servlet (I am using resource type/selector approach but for path it will be very similar) - this is more destructive option - but of course still possible.

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/form-core-component-submis...

I think you should consider to create your own form container component in case you do not want to use OOTB servlet and it's functionalities. It will be much simpler to control entire form flow.

Avatar

Level 3

I have created custom action using the above link and even tried changing the action to "bin/servlet/registration-form", still no success, could you please tell  how to call servlet in the post.POST.jsp file as the getServlet method is deprecated now.