Request method 'POST' not supported- Spring:Bind - java

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();
}
}
}

Related

AMP(Accelerated Mobile Page) form development in AEM 6.1

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

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}}

Spring MVC: Unable to bind data to my modelAttribute when trying to edit the form

I am trying to edit a submitted form but I am facing difficulties in doing so the problem is when I am submitting the form after editing null is being sent.I have been trying to get rid of this by myself but alas I have not been able to so.Please help me out.
My controller(only significant part)
#RequestMapping(value = "/registerstudentProcess", method = RequestMethod.POST)
public ModelAndView addStudent(HttpServletRequest request, #ModelAttribute("add_student") Student user) {
userService.registerStudent(user, request.getParameter("password"));
ModelAndView mav = new ModelAndView("addedstudent");
mav.addObject("adminsession");
mav.addObject("user", user);
mav.addObject("success_msg", user.getId() + " has been successfully added as an Student");
return mav;
}
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
public ModelAndView editstud(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("editstudent");
// mav.addObject("upd", new Student());
mav.addObject("adminsession");
mav.addObject("olduser", userService.editStudent(Integer.parseInt(request.getParameter("nayastud"))));
mav.addObject("batches", userService.getAllBatches());
return mav;
}
#RequestMapping(value = "/updatestud", method = RequestMethod.POST)
public ModelAndView updatestud(HttpServletRequest request, #ModelAttribute("olduser") Student stup) {
ModelAndView mav = new ModelAndView("addedstudent");
mav.addObject("adminsession");
mav.addObject("user", userService.updateStudent(stup));
mav.addObject("success_msg", stup.getId() + " has been successfully added as an Student");
return mav;
}
Model:Student.java
package project.ams.model;
public class Student {
private Integer id;
private String email;
private String name;
private String batch;
private String session;
private String address;
private String contact;
private String status;
//with proper getters and setters
}
addedstudent.jsp
<table class="table table-bordered table-condensed" align="center">
<tr>
<th colspan="2" style="text-align: center;">DETAILS</th>
<tr>
<tr>
<td><label>Id</label></td>
<td>${user.id}</td>
</tr>
<tr>
<td><label>Name</label></td>
<td>${user.name}</td>
</tr>
<tr>
<td><label>Email</label></td>
<td>${user.email}</td>
</tr>
<tr>
<td><label>Batch</label></td>
<td>${user.batch}</td>
</tr>
<tr>
<td><label>Session</label></td>
<td>${user.session}</td>
</tr>
<tr>
<td><label>Address</label></td>
<td>${user.address}</td>
</tr>
<tr>
<td><label>Phone Number:</label></td>
<td>${user.contact}</td>
</tr>
</table>
<table class="table table-condensed" align="center">
<tr>
<td>
<form:form id="editForm" action="editstud" method="post">
<input type="hidden" name="nayastud" value="${user.id}"/>
<button name="register"
class="btn btn-default">Edit Details</button>
</form:form>
</td>
<td>
<button onclick="location.href='admhome'"
class="btn btn-default">Back To Home</button></td>
</tr>
</table>
editstudent.jsp
<form:form id="regForm" modelAttribute="olduser" action="updatestud"
method="post">
<div class="form-group">
<form:label path="id">Enrollment Number</form:label>
<form:input path="id" name="id" id="id" class="form-control"
value="${olduser.id}" disabled="true" />
</div>
<div class="form-group">
<form:label path="name">Name</form:label>
<form:input path="name" name="name" id="name" class="form-control"
value="${olduser.name}" />
</div>
<div class="form-group">
<form:label path="email">Email</form:label>
<form:input path="email" name="email" id="email"
class="form-control" value="${olduser.email}" />
</div>
<div class="form-group">
<form:label path="batch">Batch</form:label>
<form:select path="batch" name="batch" id="batch"
class="form-control">
<option value="${olduser.batch}" selected></option>
<c:forEach var="bat" items="${batches}">
<form:option path="batch" value="${bat}">${bat}</form:option>
</c:forEach>
</form:select>
</div>
<div class="form-group">
<form:label path="session">Session</form:label>
<form:input path="session" name="session" id="session"
class="form-control" value="${olduser.session}" />
</div>
<div class="form-group">
<form:label path="address">Address</form:label>
<form:input path="address" name="address" id="address"
class="form-control" value="${olduser.address}" />
</div>
<div class="form-group">
<form:label path="contact">Phone</form:label>
<form:input path="contact" name="contact" id="contact"
class="form-control" value="${olduser.contact}" />
</div>
<div class="form-group">
<input type="hidden" name="password" value="Hello#123" />
<form:input type="hidden" path="status" name="status" value="a" />
</div>
<button id="register" name="register" class="btn btn-default">Update</button>
</form:form>
Edit 1
Added Screenshots(Sorry not able to post more screenshots due to reputation issues.)
Here I am changing the address and trying to update its value in the db.
Editing Student Info
Error here.Getting null object back from the edit page
when you are sending get request to fetch edit_student then you are passing value through request param and you should access this value using #PathVariable
or #RequestParam ..
<form:form id="editForm" action="editstud" method="post">
Expects a post handler
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
is defined to accept only GET requests.
Try changing edit student method to
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
public ModelAndView editstud(#RequestParam String nayastud) {
ModelAndView mav = new ModelAndView("editstudent");
mav.addObject("adminsession");
mav.addObject("olduser", userService.editStudent(Integer.parseInt(request.getParameter("nayastud"))));
mav.addObject("batches", userService.getAllBatches());
return mav;
}

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

Spring MVC Multiple ModelAttribute On the Same Form

I have a form with two ModelAttributes one is citizens and the other is punishment. The two objects are separated by jquery tabs. I am having problems in getting the items on the form to display properly some are being displayed and some are not. I mean the html elements.
I am not sure how the Controller would look when there is multiple ModleAttributes on the page. Under is a sample of the code:
Page
<title>Citizen Registration</title>
</head>
<body>
<div id="tabs">
<ul>
<li>Citizen Registration</li>
<li>Punishment</li>
</ul>
<div id="tab1">
<form:form id="citizenRegistration" name ="citizenRegistration" method="post" modelAttribute="citizens" action="citizen_registration.htm">
<div id="divRight" class="mainDiv">
<div class="divGroup" id="divCharInfo">
<fieldset>
<legend>Characteristics Info</legend>
<ol>
<li><form:label for="photo" path="photo">Select Photo</form:label>
<form:input path="photo" type="file" id="photo" title="Upload a photo"/><form:errors path="photo" id="errors"/></li>
<li>
<label>Select Gender</label>
<form:select path="genderId" id="genderId" title="Select Your Gender">
<form:options items = "${gender.genderList}" itemValue="genderId" itemLabel="genderDesc" />
</form:select>
<form:errors path="genderId" class="errors"/>
</li>
<li><form:label for="weight" path="weight">Enter Weight <i>(lbs)</i></form:label>
<form:input path="weight" id="weight" title="Enter Weight"/><form:errors path="weight" id="errors"/>
</li>
<li><form:label for="height" path="height">Enter Height <i>(feet)</i></form:label>
<form:input path="height" id="height" title="Enter Height"/><form:errors path="height" id="errors"/>
</li>
.......................
<div id="tab2">
<form:form id="punishmentRegistration" name ="punishmentRegistration" method="post" modelAttribute="punishment" action="punishment_registration.htm">
<ol>
<li>
<form:label for ="punishmentId" path="punishmentId">Punishment Number</form:label>
<form:input path="punishmentId" id="punishmentId"/><form:errors path="punishmentId" id="errors"/>
</li>
<li>
<form:label for="crimeRecNo" path="crimeRecNo">Select Crime</form:label>
<form:select path="crimeRecNo" id="CrimeRecNo" title="Select Crime">
<form:options items = "${crime.crimeList}" itemValue="crimeRecNo" itemLabel="crimeRecNo" title="crimeDesc"/>
</form:select>
<form:errors path="crimeRecNo" id="errors"/>
</li>
<li>
<form:label for ="monitoringStDate" path="monitoringStDate"> Start Date </form:label>
<form:input path="monitoringStDate" id="monitoringStDate"/><form:errors path="monitoringStDate" id="errors"/>
</li>
<li>
<form:label for ="monitoringEnDate" path="monitoringEnDate"> End Date </form:label>
<form:input path="monitoringEnDate" id="monitoringEnDate"/><form:errors path="monitoringEnDate" id="errors"/>
</li>
</ol>
</form:form>
</div>
</div>
</body>
</html>
Controller
#RequestMapping(value="citizen_registration.htm", method = RequestMethod.GET)
public ModelAndView loadPage(HttpServletRequest request,
HttpServletResponse response,
#ModelAttribute Citizens citizens, #ModelAttribute Punishment punishment,
BindingResult result,
ModelMap m, Model model) throws Exception {
//code here
return new ModelAndView("citizen_registration");
This is my code however when i run it nothing in tab2 is displayed andnot all elements in tab1 is shown.
I don't think so if you can bind multiple models using the Spring form. In fact you should take a look in the spring binding form.
http://static.springsource.org/spring/docs/1.1.5/taglib/tag/BindTag.html
Take a look in the sample code. I have not tested the code. Let know in case of any issues.
Model
public class User{
private String username;
private String password;
..Setter and Getters
}
public class UserProfile{
private String firstName;
private String lastName;
setter and getter
}
Controller
#Controller
public class MyController{
#RequestMapping(....)
public String newAccountForm(ModelMap map){
User user = new User(); //Would recommend using spring container to create objects
UserProfile profile = new UserProfile();
map.addAttribute('user', user);
map.addAttribute('profile', profile);
return "form"
}
#RequestMapping(....)
public String newAccountForm(#ModelAttrbite('User')User user, BindingResult resultUser, #ModelAttribute('UserProfile')UserProfile userProfile, BindingResult resultProfile){
//Check the binding result for each model. If not valid return the form page again
//Further processing as required.
}
}
JSP
<%#taglib uri="http://www.springframework.org/tags" prefix="spring">
<form action="" method="post">
<spring:bind path="user.username">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="user.password">
<input type="password" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="profile.firstName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="profile.lastName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<input type="submit" value="Create"/>
</form>
I already gave alternate approach in this link here
<form:form method="POST" modelAttribute="applicationGeneralInformation">
<div class="section2">
<h2>General Informaion</h2>
<form:input type="hidden" path="id" id="id"/>
<label for="app_version">Version</label>: <form:input type="text" id="app_version" path="version"/><br/>
<label for="app_func_desc">Description</label>: <form:input type="text" id="app_func_desc"
path="functionalDescription"/><br/>
<label for="app_sec_func">Functions</label>: <form:input type="text" id="app_sec_func"
path="securityFunctions"/><br/>
</div>
<div class="section2">
<h2>Application Content</h2>
<form:form method="POST" modelAttribute="applicationContent">
<div>
<h3>CIA Rating</h3>
<label for="CIARating">CIA Rating</label>: <form:select type="text" id="CIARating" path="CIARating">
<form:option value="1">1</form:option>
<form:option value="2">2</form:option>
<form:option value="3">3</form:option>
<form:option value="4">4</form:option>
</form:select><br/><br/>
</div>
<div>
<h3>Business Continuity and Disaster Recovery</h3>
<div>
<h4>RTO</h4>
<label for="RTO">RTO</label>: <form:select type="text" id="RTO" path="RTO">
<form:option value="1">< 2<sub>Hrs</sub></form:option>
<form:option value="2">2<sub>Hrs</sub>-4<sub>Hrs</sub> </form:option>
<form:option value="3">4<sub>Hrs</sub>-48<sub>Hrs</sub></form:option>
<form:option value="4">> 48<sub>Hrs</sub></form:option>
</form:select><br/>
</div>
<div>
<h4>RPO</h4>
<label for="RPO">RPO</label>: <form:input type="text" id="RPO" path="RPO"/><br/>
</div>
</div>
</form:form>
<input type="submit" value="Submit">
</div>
</form:form>
<script type="text/javascript">
$(document).ready(
function() {
$("#userAttendance").submit(
function(e) {
e.preventDefault();
jQuery.ajaxSetup({
async : false
});
var a = "${pageContext.request.contextPath}";
alert(a);
$.post($(this).attr("action"), $(this).serialize(),
function(response) {
$("#showTableByDate").html(response);
jQuery.ajaxSetup({
async : true
});
});
});
//Date picker
$('#datepicker').datepicker({
autoclose : true
});
});

Categories