spring web application - html button - post method outside form - 404 ERROR - java

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>

Related

Parameter request not returning actual value

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

Getting selected option value from controller in Spring MVC

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.

form:errors does not display error message when value is rejected

the complete code is in github:
https://github.com/cuipengfei/MPJSP/tree/master/tmp
in the controller, there is a method that handles the submit:
#RequestMapping(value = "/home", method = RequestMethod.POST)
public void handleSubmit(Customer model, BindingResult result) {
System.out.println(model.getUserName());
result.rejectValue("userName", "required.userName", "user name invalid");
}
and in jsp, there is a form like this:
<form:form method="POST" action="home" modelAttribute="Customer">
<table>
<tr>
<td>Username :</td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
the controllers just rejects value every time, but the error message is not displayed.
the complete code can be found here:
https://github.com/cuipengfei/MPJSP/tree/master/tmp
try to set commandName attribute in your form tag
<form:form method="POST" action="home" commandName="Customer">

Spring MVC Request Param

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

With Fields and File uploading

I have a form which contains fields and file upload elements while submitting the form it is throwing a null pointer exception, when i logged the form object all fields are getting null and when i am removing the form enctype="multipart/form-data"1 then i get all fields but the file object is getting null.
Form Code :
<form:form method="post" id="form" name="frm" action="${action}" enctype="multipart/form-data">
<table>
<tr>
<td><form:label path="productName">Product Name: </form:label></td>
<td>
<form:input path="productName"/>
</td>
</tr>
<tr>
<td><form:label path="rfile">Receipt File</form:label></td>
<td><form:input path="rfile" id="receiptFile" type="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Upload Receipt" /></td>
</tr>
</table>
</form:form>
COntroller Code:
#RequestMapping(value="/test.do", method = RequestMethod.POST)
public ModelAndView testReceipt(#ModelAttribute("frm") ReceiptForm form, BindingResult result, HttpServletRequest request){
System.out.println("---"+form.getProductName());
System.out.println("---"+form.getRfile());
}
Please note file is a type of: CommonsMultipartFile
Use FileUpload library to parse the request from the client.

Categories