AMP(Accelerated Mobile Page) form development in AEM 6.1 - java

I am trying to develop a AMP form in AEM 6.1 and trying to submit data to back end sling servlet to save the data into database.But I am getting error in return:
<body>
<form class="sample-form"
method="post"
action-xhr="/bin/rating.rest"
target="_top">
<input type="text"
name="name"
placeholder="Name..."
required>
<input type="email"
name="email"
placeholder="Email..."
required>
<input type="text"
name="title"
placeholder="Title..."
required>
<input type="textarea"
name="textarea"
placeholder="Feedback..."
required>
<fieldset class="rating">
<input name="rating" type="radio" id="rating5" value="5" on="change:rating.submit">
<label for="rating5" title="5 stars">☆</label>
<input name="rating" type="radio" id="rating4" value="4" on="change:rating.submit">
<label for="rating4" title="4 stars">☆</label>
<input name="rating" type="radio" id="rating3" value="3" on="change:rating.submit" checked="checked">
<label for="rating3" title="3 stars">☆</label>
<input name="rating" type="radio" id="rating2" value="2" on="change:rating.submit" >
<label for="rating2" title="2 stars">☆</label>
<input name="rating" type="radio" id="rating1" value="1" on="change:rating.submit">
<label for="rating1" title="1 stars">☆</label>
</fieldset>
<input type="submit"
value="Submit Feedback">
<div submit-success>
<template type="amp-mustache">
Success! Thanks {{name}} for trying the <code>amp-form</code> demo! Try to insert the word "error" as a name input in the form to see how <code>amp-form</code> handles errors.
</template>
</div>
<div submit-error>
<template type="amp-mustache">
Error! Thanks {{name}} for trying the <code>amp-form</code> demo with an error response.
</template>
</div>
</form>
</body>
Back End Code::::
#SlingServlet(paths="/bin/rating.rest", methods = "POST", metatype=true)
public class AmpRatingActionServlet extends SlingAllMethodsServlet {
protected void doPost(SlingHttpServletRequest request,SlingHttpServletResponse response) throws ServletException,
IOException {
String jsonData = null;
String name;
String email;
String title;
String textarea;
String rating;
try
{
name = request.getParameter("name");
email = request.getParameter("email");
title = request.getParameter("title");
textarea = request.getParameter("textarea");
rating = request.getParameter("rating");
log.info(CLASSNAME+"::Inside Try Block:::::::name::::"+name+":::::email:::::"+email+":::::title:::::"+title+":::::textarea:::::"+textarea+":::::rating:::::"+rating);
}
}catch(Exception e) {
log.error(Error occurred in Servlet", e);
}
}
500
Message
javax.jcr.nodetype.ConstraintViolationException: No matching property definition: name = Test

Related

Request method 'POST' not supported- Spring:Bind

I have two Models-
Customer and Address
I passed both of the objects to the getMethod-
#RestController
public class NewCustomerController {
#Autowired
NewCustomerService newCustomerService;
#GetMapping(value = "newCustomer")
public ModelAndView newCustomer(){
ModelAndView modelAndView=new ModelAndView("views/customer/newCustomer");
modelAndView.addObject("customer",new Customer());
modelAndView.addObject("address",new Address());
return modelAndView;
}
After submitting a form i want to store these objects into my db-
My JSP Page-
<body class="container-fluid">
<jsp:include page="/navbar.jsp" />
<article>
<form action="newCustomer" method="post">
<spring:bind path="customer.customerCode">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.firstName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.lastName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.dateOfBirth">
<input type="date" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.nationality">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.occupationType">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.totalWorkExperience">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="customer.organizationName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<h2>ADDRESS</h2>
<spring:bind path="address.addressId">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.houseNo">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.city">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.state">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.country">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="address.pincode">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<input type="submit" value="Create"/>
</form>
</article>
</body>
Here is a post method i want to call on clicking the create button-
continue after get method...
#PostMapping(value = "newCustomer")
public ModelAndView addCustomer(#ModelAttribute("customer") Customer customer, BindingResult resultCustomer,#ModelAttribute("address") Address address,BindingResult resultAddress){
newCustomerService.createNewCustomer(customer);
newCustomerService.createNewAddress(address);
ModelAndView modelAndView=new ModelAndView("views/loanapplication/loanApplication");
return modelAndView;
}
}
After clicking on create button-
I am getting this error-
Request method 'POST' not supported
For reference i am showing the urls after before clicking create button-
before click-
http://127.0.0.1:8080/Project/newCustomer
After click-
http://127.0.0.1:8080/Project/newCustomer
Are you using spring security? Check the csrf setting of spring security.
By default, csrf defense is enabled to enable spring security. At this point, the solution is the same.
You can send csrf token value in form.
<input type = "hidden" name = "$ {_ csrf.parameterName}" value = "$ {_ csrf.token}"/>
If you want to ignore csrf, you can set a class that inherits
WebSecurityConfigurerAdapter class to ignore certain URLs
#EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
#Value("${security.enable-csrf}")
private boolean csrfEnabled;
#Override
protected void configure(HttpSecurity http) throws Exception {
if (!csrfEnabled) {
http.csrf().disable();
}
}
}

If equals condition in mustache

In my application I have a database with users. User have String field named Gender. I want to make a form, where user can edit his profile. It's should be filled with existing data.
I have such post method in java code:
#GetMapping("/edit/profile")
public ModelAndView editProfile(Map<String, Object> model){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userRepository.findByUsername(auth.getName());
model.put("name", user.getName());
model.put("last_name", user.getLastName());
model.put("company", user.getCompany());
model.put("address", user.getAddress());
model.put("gender", user.getGender());
model.put("birth_date", user.getBirthDate());
return new ModelAndView("edit_profile", model);
}
And this is my mustache edit_profile template:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>To do list profile editing</title>
</head>
<body>
<p>Profile editing</p>
<form action="/api/users/update" method="post">
<div><label> Name : <input type="text" name="name" value="{{name}}" /> </label></div>
<div><label> Last Name : <input type="text" name="lastName" value="{{last_name}}" /> </label></div>
<div><label> Gender : <br>
{{#gender}}
{{#"male"}}
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female
{{/"male"}}
{{#"female"}}
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female" checked> Female
{{/"female"}}
{{/gender}}
{{^gender}}
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female
{{/gender}}
</label></div>
<div><label> Company : <input type="text" name="company" value="{{company}}" /> </label></div>
<div><label> Birth Date : <input type="date" name="birthDate" value="{{birth_date}}" /> </label></div>
<div><label> Address : <input type="text" name="address" value="{{address}}" /> </label></div>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<div><input type="submit" value="Submit"/></div>
</form>
</body>
</html>
I want to realise logic where:
if(gender)
if(gender.equals("male"))
male radio button checked
if(gender.equals("female"))
female radio button checked
else
no radio buttons checked
Now it doesn't work correctly, please tell me how i can make if equals conditions in mustache?
Ok, the best way to use boolean in model i guess.
java:
if(!user.getGender().isEmpty()) {
if(user.getGender().equals("male"))
model.put("gender", false);
else if(user.getGender().equals("female"))
model.put("gender", true);
}
mustache:
{{#gender}}
<input type="radio" name="gender" value="male" > Male<br>
<input type="radio" name="gender" value="female" checked> Female
{{/gender}}
{{^gender}}
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female
{{/gender}}

How to pass multiple value as same name using HttpServletRequest(Spring Freamework)?

I have two input field in view
<input name="test[]" type="text" value="one">
<input name="test[]" type="text" value="two">
in controller
public String store(#Context HttpServletRequest request) {
// now i get only last value
String[] array = request.getPerameter("test");
}
in PHP i can value as array using same way.
you can use request.getParameterValues(test)
Please check oracle doc for more info and here is an example
<form name="myForm" th:action="#{/demo}" method="post"
class="stdform" id="triggerform">
<div class="form-group">
<label for="usr">test:</label>
<input name="test" type="text" class="form-control" />
<input name="test" type="text" class="form-control" />
<input name="test" type="text" class="form-control" />
<input name="test" type="text" class="form-control" />
<input name="test" type="text" class="form-control" />
<input name="test" type="text" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Get Started</button>
</form>
#RequestMapping(value = "/demo", method = RequestMethod.POST)
public void getInboxMessage(HttpServletRequest request,Model model, #RequestParam("test") List<String> test) {
try {
logger.info("Welcome to getInboxMessage Method inside the MessageController ");
System.out.println(test);
}
catch(Exception e)
{
logger.info(e.getMessage());
}
}
This would be spring way of doing it .hope it helps

Request parameters become null

My code was working perfectly fine a while ago until my classmate sent a modified HTML file and every single parameter is now null. I don't really know what happened. I'm transferring the information from the form to the servlet and from the servlet, I'm transferring it to the database. Here's the code for the form:
<form method="post" action="informationTransfer">
<div class='row'>
<div class='col-md-6'>
<label for="username">User Name</label>
<input type="text" class="form-control" id="username" placeholder="User Name" name='username' required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" placeholder="Last Name" name='LastName' required>
</div>
<div class='col-md-6'>
<label for="firstName">Name</label>
<input type="text" class="form-control" id="firstName" placeholder="First Name" name='FirstName' required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for="lastName">E-Mail</label>
<input type="email" class="form-control" id="email_1" placeholder="E-Mail Address" name='Email' required>
</div>
<div class='col-md-6'>
<label for="firstName">Confirm E-Mail</label>
<input type="email" class="form-control" id="email_2" placeholder="Confirm E-Mail Address" required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for="lastName">Password</label>
<input type="password" class="form-control" id="password_1" placeholder="Password" name='Password' required>
</div>
<div class='col-md-6'>
<label for="firstName">Confirm Password</label>
<input type="password" class="form-control" id="password_2" placeholder="Confirm Password" required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for='birthDate'>Birthday</label>
<div class="bfh-datepicker" data-max="today" data-close="false" data-date="today" data-format="y-m-d">
<input id="birthDate" type="text" data-name="birthDate" name='Birthdate' style='background-color:white;'>
</div>
</div>
<div class='col-md-6'>
<label for='gender'>Gender</label>
<select class='form-control' name='gender'>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-4'>
<label for="countries_selectors">Country</label>
<select id="countries_selectors" class="form-control bfh-countries" data-country="PH" name='country' required></select>
</div>
<div class='col-md-4'>
<label for="State">State</label>
<select class="form-control bfh-states" data-country="countries_selectors" id='State' name='State' required></select>
</div>
<div class='col-md-4'>
<label for="zip">Zip Code</label>
<input type="zip" class="form-control" id="zip" placeholder="Zip Code" name='zipcode' required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-12'>
<label for="address">Home Address</label>
<input type="text" class="form-control" id="address" placeholder="Last Name" name='Address' required>
</select>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-10'>
<label for="phone">Contact Number</label>
<input type="text" class="form-control bfh-phone" data-country="countries_selectors" id="phone" name='PhoneNumber'>
</div>
<div class='col-md-2'>
<label for="signup_b"><br /></label>
<button type="submit" class="btn btn-default center-block" name='signup_b'>Sign Up!</button>
</div>
</div>
</form>
Here's the code for the servlet:
#WebServlet(description = "transfers contents of bean to database", urlPatterns = { "/informationTransfer" })
public class transferInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
toDatabase(request, response);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
toDatabase(request, response);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
private void toDatabase(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/FoundationSystem","root","!Qaz2wsx");
con.setAutoCommit(false);
try
{
PreparedStatement stmt1, stmt2, stmt3;
stmt1 = con.prepareStatement("INSERT INTO AddressInformation (AddressID, Country, ZipCode, State, Address) VALUES (null,?,?,?,?)");
stmt1.setString(1, request.getParameter("country"));
stmt1.setString(2, request.getParameter("zipCode"));
stmt1.setString(3, request.getParameter("state"));
stmt1.setString(4, request.getParameter("address"));
stmt1.executeUpdate();
stmt2 = con.prepareStatement("INSERT INTO AccountDetails VALUES (?,?,?,?,?)");
stmt2.setString(1, request.getParameter("username"));
stmt2.setString(2, request.getParameter("password"));
stmt2.setString(3, null);
stmt2.setString(4, null);
stmt2.setInt(5, 3);
stmt2.executeUpdate();
stmt3 = con.prepareStatement("INSERT INTO PersonalInformation VALUES (?,?,?,?,?,?,?,?)");
Statement address = con.createStatement();
ResultSet result = address.executeQuery("SELECT max(AddressID) FROM AddressInformation");
result.next();
stmt3.setString(1, request.getParameter("userName"));
stmt3.setString(2, request.getParameter("lastName"));
stmt3.setString(3, request.getParameter("firstName"));
stmt3.setString(4, request.getParameter("gender"));
stmt3.setString(5, request.getParameter("birthdate"));
stmt3.setInt(6, result.getInt(1));
stmt3.setString(7, request.getParameter("email"));
stmt3.setString(8, request.getParameter("phoneNumber"));
stmt3.executeUpdate();
con.commit();
//response.sendRedirect();
}
catch (Exception e)
{
con.rollback();
System.out.println(e);
}
}
}
Take care of case here. For eg.
<input type="zip" class="form-control" id="zip" placeholder="Zip Code" name='zipcode' required>
you get this data by
stmt1.setString(2, request.getParameter("zipcode"));
and not
stmt1.setString(2, request.getParameter("zipCode")); // C is capital
name of the input tag in your form should match the parameter name you use in getParameter() method.
Seems name case problem. Match parameter name of your input fields in html file and request.getParameter("fieldName") in your servlet

Getting "Assertion failed: (anonymous function)" on Safari with application

I am creating an application for an ipad and i am doing it using Java. JavaScript. HTML and Rest. I have a list of countries that i want to display in a drop list on one of the page in the application am im trying to use rest to populate this list but when i run the application i am getting nothing in the droplist and safari is giving the error
Assertion failed: (anonymous function) :449
i am gettin this error 8 times with different numbers at the end
here is some of the code that i am using
main.html
<div id="wrapper">
<div id="mainBackground">
<div id="stflogo"><img src="images/logo.png" width="200" height="186" alt="MyLogo logo" /></div>
<div id="formContainer">
<h1>Register Your Card</h1>
<form id="AccountDetailsForm" method="post" data-ajax="false">
<input id="tfscCardNumber" type="hidden" name="tfscCardNumber" class="readonly" minlength="2" maxlength="20" readonly="readonly" disabled="disabled"/>
<p><label id="firstNameLabel" for="firstName" class="displayBlockLabel RequiredField">First Name </label>
<input id="firstName" type="text" name="firstName" class="required" minlength="2" maxlength="20"/></p>
<p><label id="lastNameLabel" for="lastName" class="displayBlockLabel RequiredField"> Last Name </label>
<input id="lastName" type="text" name="lastName" class="required" minlength="2" maxlength="25"/></p>
<p><label id="address1Label" for="address1" class="displayBlockLabel RequiredField">Address 1 </label>
<input id="address1" type="text" name="address1" class="required" minlength="2" maxlength="40"/></p>
<p><label id="address2Label" for="address2" class="displayBlockLabel">Address 2</label>
<input id="address2" type="text" name="address2" maxlength="40"/></p>
<p><label id="cityLabel" for="city" class="displayBlockLabel RequiredField">Town / City </label>
<input id="city" type="text" name="city" class="required" minlength="2" maxlength="40"/></p>
<p> <label id="countyLabel" for="county" class="displayBlockLabel RequiredField">County / State </label>
<input id="county" type="text" name="county" class="required" minlength="2" maxlength="40"/> </p>
<p> <label id="postcodeLabel" for="postcode" class="displayBlockLabel RequiredField">Postcode / Zip </label>
<input id="postcode" type="text" name="postcode" class="required" minlength="2" maxlength="11"/> </p>
<p> <label id="countrySelectionLabel" for="countrySelection" class="displayBlockLabel RequiredField">Country </label>
<select id="countrySelection" class="required">
</select> </p>
<p><label id="telephoneLabel" for="telephone" class="displayBlockLabel RequiredField">Tel Number </label>
<input id="telephone" type="tel" name="telephone" class="tel number required" minlength="2" maxlength="12"/></p>
<p><label id="emailLabel" for="email" class="displayBlockLabel RequiredField">Email </label>
<input id="email" type="email" name="email" class="email required" minlength="2" maxlength="100"/></p>
<p><label id="confirmEmailLabel" for="confirmEmail" class="displayBlockLabel RequiredField">Confirm Email </label>
<input id="confirmEmail" type="email" name="confirmEmail" class="email required" minlength="5" maxlength="100"/></p>
<p><label id="passportNumberLabel" for="passportNumber" class="displayBlockLabel RequiredField">Passport Number </label>
<input id="passportNumber" type="text" name="passportNumber" class="required" minlength="3" maxlength="20"/></p>
<p class="tandcnotice">Please Ensure that you have read the Terms & Conditions and Privacy & security Policy</p>
<p class="tandcCheckbox">
<input type="checkbox" name="accepttandc" id="accepttandc" class="checkbox" />
<label for="checkbox" class="accepttandc">I have read the Terms & Conditions</label>
<p>
<input class="button" type="submit" value="Submit" data-role="button" data-theme="redbutton"/>
</form>
</div><!-- END OF FORM CONTAINER -->
</div>
</div>
....
appForm.js
$('#wrapper').live("pageshow", function() {
if ( $('#countrySelection')[0].length < 1){
$.mobile.loadingMessage = "Retrieving Countries";
$.mobile.showPageLoadingMsg();
Repository.load('details/countries/all', function(countries){
$.each(countries, function() {
$('#countrySelection').append('<option value="' + this.id + '">' + this.name + '</option>').selectmenu('refresh');
});
$.mobile.hidePageLoadingMsg();
});
}
});
$('#wrapper').live("pagecreate", function() {
$('#AccountDetailsForm select, #AccountDetailsForm input[type!=submit]').focus(function (){
focusScroller(this);
});
$('#AccountDetailsForm select, #AccountDetailsForm input[type!=submit]').blur(function (){
if ( $('#accountFormScrollView').data().scrolllistview._sy < $('#accountFormScrollView').data().scrolllistview._maxY){
$('#accountFormScrollView').data().scrolllistview.scrollTo(0, $('#accountFormScrollView').data().scrolllistview._maxY, 0);
}
});
});
$(window).resize(function (){
// Android Resize Event needed for the keyboard
});
var focusScroller = function(formElement){
$(window).scrollTop(0);
var elementLabel = "#" + formElement.id + "Label";
var offSetPosition = $(elementLabel)[0].offsetTop;
if(formElement.labels === undefined && formElement.id === "countrySelection"){
// ios4 quirk for select elements
offSetPosition = 100;
}
scrollTo(0,0,0);
$('#accountFormScrollView').data().scrolllistview.scrollTo(0, offSetPosition * -1, 0);
}
$('#wrapper"').live("pageshow", function() {
if (getTfscCardNumber() === ''){
$('#passportNumberLabel').css('display', 'none');
$('#passportNumber').css('display', 'none');
$('#passportNumber').attr("disabled", true);
}else{
$('#passportNumberLabel').css('display', 'block');
$('#passportNumber').css('display', 'block');
$('#passportNumber').attr("disabled", false);
}
loadForm($('#AccountDetailsForm')[0]);
});
i can put up more code if needed but im sure the rest of the code is ok but if anyone wants to look at any other pieces of code just ask
what does this error mean and can anyone see what is going wrong?
This is a bug with Safari and its handling of inputs with type="tel". I wouldn't worry about it.
I was having the same problem and then I found this: https://github.com/jquery/jquery-mobile/issues/2341

Categories