I am creating an AJAX form using spring 3.1 MVC. I am confused and have searched the internet and stackoverflow for a solution to my problem but have been unsuccessful so far. I am Also using Tiles 2.2.2
I am getting a WARNING: Request method 'POST' not supported
The Controller methods
#RequestMapping(value="/createProject", method=RequestMethod.POST,headers ="Accept:*/*")
public #ResponseBody Project createProject(#RequestBody Project project){
try {
projectBusiness.createProject(project);
} catch (Exception e) {
e.printStackTrace();
}
return project;
}
#RequestMapping(value="/createProject", method=RequestMethod.GET)
public ModelAndView displayCreateProjectForm(){
ModelAndView mav = new ModelAndView("createProject");
mav.addObject("project", new Project());
return mav;
}
My JSP
$(function() {
var url = $('#myForm').attr('action'); //http://localhost:7001/ProjectPortfolioTracker/app/projects/createProject
$('#submitForm').click(function(e){
console.log("hello");
e.preventDefault();
var formData = $('#myForm').serialize();
alert(formData);
console.log('in form click');
$.ajax({
type: 'POST',
url: url,
data:formData,
success: function(){
alert('success');
},error: function(){
alert('failure');
},
}).done(function() {
alert("ajax post completed");
});
});
});
<body>
<h1>Create a Project</h1>
<table>
<form method="post" action="${pageContext.request.contextPath}/app/projects/createProject" id="myForm">
<tr>
<td>Description: </td><td><textarea id="description" name="description" ></textarea></td>
</tr>
<tr>
<td>Category:</td>
<td>
<select name="category">
<option value="marketing">Marketing</option>
<option value="sales">Sales</option>
<option value="accounting">Accounting</option>
</select>
</td>
</tr>
<tr>
<td>Estimated Duration:(in days)</td><td><input id="durationSlider" type="range" min="1" max="90" step="1" value="1"/></td><td><input type="text" id="durationValue" name="estimatedduration" readonly/></td>
</tr>
<tr>
<td>Estimated Cost:(in 100's of dollars)</td><td><input id="costSlider" type="range" min="1" max="500" step="1" value="1" /></td><td><input type="text" id="costValue" name="estimatedcost"readonly/></td>
</tr>
<tr>
<td>Objective:</td><td><textarea id="objective" name="objective"></textarea></td>
</tr>
<tr>
<td>Resources:</td><td><input id="resources" type="number" value="0" name="resources"/> </td>
</tr>
<tr>
<td>Status:</td>
<td>
<select name="status">
<option value="design">Design Stage</option>
<option value="working">Work in Progress</option>
<option value="finished">Finished</option>
<option value="publishing">Publishing</option>
</select>
</td>
</tr>
<tr>
<td>Supports:</td><td><textarea id="supports" name="supports"></textarea></td>
</tr>
<tr>
<td>ManagerID</td><td><input type="number" value="0" id="managerid" name="managerid"/></td>
</tr>
<tr>
<td><button type="submit" id="submitForm">Submit</button></td>
</tr>
</form>
</table>
I Should also mention I got the actual information to post through the ajax but I was not handling the controller code in an ajax way meaning i was still returing a view at the end of the method, since the change to using #ResponseBody and #RequestBody is when the problem started to happen
Forgive my horrible formatting I am still learning.
So The issue was the Headers paramenter of the #RequestMapping it didn't like the Accept:/ which I assumed to be to accepting anything when i changed it to Accept:"application/json" it started to work properly Thanks to all who commented trying to help
Related
I have a table that does not live in a form, but I want the button in each row to correlate and to delete the contact from that table row when it's clicked. I could do an ajax call but I was hoping to just handle it through a spring boot controller method. This is how I set it up.
#RequestMapping(value="/removeContact")
public String removeContact(final CarrierAppointment carrierAppointment, final HttpServletRequest req, Model model){
final Integer rowId = Integer.valueOf(req.getParameter("trashContact"));
carrierAppointment.getContactList().remove(rowId.intValue());
model.addAttribute("carrierAppointment", carrierAppointment);
return "redirect:/carrierAppointment/details/"+carrierAppointment.getId();
}
<table class="table table-striped" data-classes="table-no-bordered" data-striped="true" data-show-columns="true" >
<thead>
<tr>
<th>Contact Type</th>
<th>Contact Name</th>
<th>Contact's Email</th>
<th>Contact's Phone</th>
<th></th>
<th th:if="${role.isCarrierAdmin}" class="text-right"><a class="trigger-add-contact btn btn-default" id="addCommercialContact" name="addCommercialContact"><span class="fa fa-plus"></span></a></th>
</tr>
</thead>
<tbody>
<tr th:each="contact,stat : *{carrier.contactList}" th:if="*{carrier.contactList[__${stat.index}__].contactTable}=='Commercial Lines'">
<td>
<select class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactType}">
<option value="Account Manager">Account Manager</option>
<option value="Marketing Manager">Marketing Manager</option>
<option value="Underwriter">Underwriter</option>
</select>
</td>
<td> <input type="text" class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactName}"/></td>
<td> <input type="text" class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactEmail}"/></td>
<td><input type="text" class="form-control" th:field="*{carrier.contactList[__${stat.index}__].contactPhone}"/></td>
<td> <input type="hidden" value='Commercial Lines' th:field="*{carrier.contactList[__${stat.index}__].contactTable}"/></td>
<td class="text-right" th:if="${role.isCarrierAdmin}"> <button type="button" name="trashContact" th:value="${stat.index}" th:onclick="'window.location.href=\'/removeContact\''" class="btn btn-danger "><span class="fa fa-trash"></span></button></td>
</tr>
</tbody>
</table>
The line of code that is requesting the parameter and getting the value is where my code is getting hung up. It is returning null instead of a value. Any idea how to adjust this line of code so it actually gets the value that exists?
Maybe the way I have the onclick set up, it's not actually sending the row value through to the controller method?
This is exactly where in the code it is getting hung up:
public String getParameter(String name) {
this.handleQueryParameters();
ArrayList<String> values = (ArrayList)this.paramHashValues.get(name);
if (values != null) {
return values.size() == 0 ? "" : (String)values.get(0);
} else {
return null;
}
}
I`m trying to send post request from JSP view to Controller by Button "onClick" method but i getting 404 Error that the RequestMapping is not sign, why is that?
HomeController:
#RequestMapping(value = "/showSelectedRequest/{id}", method = RequestMethod.POST)
public String loadRequestProducts(#PathVariable("id") int id, Model model) {
logger.debug("HomeController.RequestIdSelected() - Start");
logger.debug("HomeController.RequestIdSelected: id: " + id);
model.addAttribute("RequestIdSelected", id);
logger.debug("HomeController.RequestIdSelected() - Done");
return "/home";
}
Home.jsp:
<form action="${contextPath}/requestlist" method="post">
<table class="table table-sm">
<thead class="thead-inverse">
<tr>
<th>
Id
</th>
<th>
Name
</th>
<th>
Show request
</th>
</tr>
</thead>
<c:forEach items="${requestDTOList}" var="requestDTO">
<tr>
<td>
${requestDTO.getId()}
</td>
<td>
${requestDTO.getName()}
</td>
<td>
<button class="btn btn-info" onclick="post(/showSelectedRequest/${requestDTO.getId()})">Query</button>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</td>
</tr>
</c:forEach>
</table>
</form>
When you have a form, the action field is what will be executed when you will click on the input of type "submit".
As a solution you can modify your code as follow:
<form action="${contextPath}/showSelectedRequest/${requestDTO.getId()}" method="post">
// Form elements ...
<input type="submit" value="Query" />
</form>
I'm making a Spring MVC project, and I have this form in my .jsp
JSP
<form:form action="/admin/assign/add" modelAttribute="cafeTable">
<table>
<tr>
<td>
<form:label path="tableNumber">
<spring:message text="Table's Number"/>
</form:label>
</td>
<td>
<form:select path="tableNumber" action = "select">
<form:options items="${tableNumbers}"></form:options>
</form:select>
</td>
</tr>
<tr>
<td>
<form:label path="${user.fullName}">
<spring:message text="Waiter's name"/>
</form:label>
</td>
<td>
<form:select path="${user.fullName}" action = "select">
<c:forEach items="${listUser}" var="user">
<option value="${user.fullName}">${user.fullName}</option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
<br>
<input type="submit" name="assign"
value="<spring:message text="Assign"/>"/>
</form:form>
So I have User and CafeTable models, but my model attribute is CafeTable.
With the submit button I need to get both selected values in my controller:
#RequestMapping(value = "/admin/assign/add", params = "assign", method = RequestMethod.POST)
public String assign(#ModelAttribute("cafeTable") CafeTable cafeTable) {
//set cafeTable's UserID field matching selected fullName value
tableService.addTable(cafeTable);
return "admin";
}
How can I do this?
<form:form action="/admin/assign/add" modelAttribute="cafeTable">
<table>
<tr>
<td>
<form:label path="tableNumber">
<spring:message text="Table's Number"/>
</form:label>
</td>
<td>
<input type="hidden" value="${user.fullName}" name="fullname">
<form:select path="tableNumber" action = "select">
<form:options items="${tableNumbers}"></form:options>
</form:select>
</td>
</tr>
<tr>
<td>
<form:label path="${user.fullName}">
<spring:message text="Waiter's name"/>
</form:label>
</td>
<td>
<form:select path="${user.fullName}" action = "select">
<c:forEach items="${listUser}" var="user">
<option value="${user.fullName}">${user.fullName}</option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
<br>
<input type="submit" name="assign"
value="<spring:message text="Assign"/>"/>
</form:form>
If you don't have fullname property in CafeTable try to add a hidden field inside form:form like
<input type="hidden" value="${user.fullName}" name="fullname">
and add a optional request parameter into your controller like below
#RequestMapping(value = "/admin/assign/add", method = RequestMethod.POST)
public String save(#RequestParam("fullname") String fullname,#Valid #ModelAttribute("cafeTable") CafeTable cafeTable) {
//now you can access full name from fullname variable here
....
}
I haven't tested this code.
How do i create a jsp page wherein, i have 3 option in my html dropdown (using 'option' option), and when i choose each option, a different table has to be displayed depending on the option.
my html code is:
<html>
<title>
customer info
</title>
<body>
<center>CUSTOMER INFORMATION</center>
Customer Name: <input type="text" name="name"/>
<br>Customer Segment/Type:
<select>
<option value="prepaid">prepaid</option>
<option value="postpaid">postpaid</option>
</select>
<br>Circle:
<select>
<option value="Tamil Nadu">Tamil Nadu</option>
<option value="Gujarat">gujarat</option>
<option value="Maharashtra">Maharashtra</option>
</select>
<CENTER>SERVICE INFORMATION</CENTER>
select package:
<select>
<option value="silver">silver</option>
<option value="gold">gold</option>
<option value="platinum">platinum</option>
</select>
<form action="my_package">
<input type="submit" value="show package" name="Submit" />
</form>
</html>
for each type of package, a different table has to be displayed describing the package.
You need to bind the hide/show to the change function of the select tag,
<select id="myselection">
<option id="si" selected>SI</option>
<option id="iu">IU</option>
</select>
<script>
$('#myselection').bind('change', function(){
if($('#myselection option:selected').attr('id') == "si"){
$('#si_table').show();
$('#iu_table').hide();
}
else if($('#myselection option:selected').attr('id') == "iu"){
$('#si_table').hide();
$('#iu_table').show();
}
});
</script>
$('#myselection').on('change', function() {
if ($('#myselection option:selected').attr('id') == "si") {
$('#si_table').show();
$('#iu_table').hide();
} else if ($('#myselection option:selected').attr('id') == "iu") {
$('#si_table').hide();
$('#iu_table').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Your drop down</label>
<select id="myselection">
<option id="si" selected>SI</option>
<option id="iu">IU</option>
</select>
<div id="si_table">
<p>First Table</p>
<table border=1>
<thead>
<tr>
<th>Lorem</th>
<th>Ipsum</th>
<th>Dolor</th>
<th>Sit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sit</td>
<td>Dolor</td>
<td>Ipsum</td>
<td>Lorem</td>
</tr>
<tr>
<td>Sit</td>
<td>Dolor</td>
<td>Ipsum</td>
<td>Lorem</td>
</tr>
</tbody>
</table>
</div>
<div id="iu_table">
<p>Second Table</p>
<table>
<thead>
<tr>
<th>Lorem</th>
<th>Ipsum</th>
<th>Dolor</th>
<th>Sit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sit</td>
<td>Dolor</td>
<td>Ipsum</td>
<td>Lorem</td>
</tr>
<tr>
<td>Sit</td>
<td>Dolor</td>
<td>Ipsum</td>
<td>Lorem</td>
</tr>
</tbody>
</table>
</div>
I have a login page with form action of j_security_check. As of now this form just have two fields namely username
and password. I want to add a new dropdown to this form and collect the selected value in controller using
#RequestParam. For some reason I am not able to pass this dropdown value from JSP to my controller as its throwing the
exception: MissingServletRequestParameterException (Which occurs anytime a request param is missing).
In the code below I added the Visuals dropdown. Do I need to use Spring:Bind tag here?
Also on successful login, the control is directed to a controller with request mapping /controller1.html and this is where
I am trying to collect the dropdown value.
<form name="appLogin" action="j_security_check" method="POST">
<table width="100%">
<tr>
<td align="center">
<table>
<tr>
<td>Username: </td>
<td><input id="userName" name="j_username" value=""/></td>
</tr>
<tr>
<td>Password: </td>
<td><input name="j_password" type="password" value="" /></td>
</tr>
<tr>
<td>Visual: </td>
<td><Select name="visuals" id="visuals"/>
<option value="S1">S1</option>
<option value="S2">S2</option>
<option value="S3">S3</option>
<option value="S4">S4</option>
</Select>
</td>
</tr>
</table>
<table>
<tr>
<td>
<button type="submit" name="submit" value="Sign In">Sign In</button>
<input type="submit"/>
</td>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</form>
Controller Code:
#RequestMapping( value = " /controller1.html", method = RequestMethod.GET )
public String setupForm( #RequestParam(value = "visuals", required=false) String visuals,
ModelMap model )
{
List<String> studentNames = new ArrayList<String>();
List<String> teacherNames = new ArrayList<String>();
model.addAttribute("someData", teacherNames);
model.addAttribute("anotherData", studentNames);
model.addAttribute("visuals", visuals);
log.info("Role from Dropdown: " + visuals);
return "school/classTen";
}
You need to create yyour own Filter by extending AbstractAuthenticationProcessingFilter
I don't have the entire code in front of my eyes, but the following article could help you:
http://mark.koli.ch/2010/07/spring-3-and-spring-security-setting-your-own-custom-j-spring-security-check-filter-processes-url.html