HTTP Status 400 - Required String parameter 'clientId' is not present - java

I have Spring MVC application with this controller method.
#RequestMapping(value = "/saveMe", method = RequestMethod.POST)
public #ResponseBody String saveMe(#RequestParam(value = "clientId") String strClientId,#RequestParam(value = "clientName") String strClientName,#RequestParam(value = "custBaseNo") String strCustBaseNo, #RequestParam(value = "category") String strCategory,#RequestParam(value = "clientCpt") String strClientCpt, #RequestParam(value = "pbk") String strPbk,#RequestParam(value = "prk") String strPrk,#RequestParam(value = "fileAct") int intFileAct, #RequestParam(value = "b2b") int intB2b,#RequestParam(value = "collection") int intCollection, #RequestParam(value = "primAccNo") String strPrimAccNo,#RequestParam(value = "accFromAcct") String strAccFromAcct,#RequestParam(value = "accToAcct") String strAccToAcct,#RequestParam(value = "intCount") int intCount,#RequestParam(value = "productId") String strProductId,HttpServletRequest request){
String strStatus ="";
System.out.println("strClientId is :::"+strClientId);
strStatus = sabService.saveDetails(strClientId,strClientName,strCustBaseNo,strCategory,strClientCpt,strPbk,strPrk,intFileAct,intB2b,intCollection,strPrimAccNo,strAccFromAcct,strAccToAcct,intCount,strProductId);
String[] strChkService = new String[intCount];
String[] strAccNO = new String[intCount];
int[] intTrnsLimit = new int[intCount];
String[] strProtcl = new String[intCount];
for(int j=1;j<=intCount;j++){
strChkService[j] = request.getParameter("chkService"+j)==null?"":request.getParameter("chkService"+j);
strAccNO[j] = request.getParameter("accountNo"+j)==null?"":request.getParameter("accountNo"+j);
intTrnsLimit[j] = Integer.parseInt(request.getParameter("transactionLimit"+j)==null?"0":request.getParameter("transactionLimit"+j));
strProtcl[j] = request.getParameter("protocol"+j)==null?"":request.getParameter("protocol"+j);
strStatus = sabService.saveServices(strClientId,strProductId,strChkService[j],strAccNO[j],intTrnsLimit[j], strProtcl[j] );
}
return "success";
}
While submitting the form I'm getting this error.
HTTP Status 400 - Required String parameter 'clientId' is not present
Can anyone please help me...Thanks in advance...
jquery-
$("#client-maint-form").attr("action","sabb/saveMe");
$("#client-maint-form").submit();
form-
<form id="client-maint-form" class="form-horizontal" enctype="multipart/form-data" method="POST">
i have also tried with GET ...but getting this error
HTTP Status 405 - Request method 'GET' not supported
Here is the form
<form id="client-maint-form" class="form-horizontal" enctype="multipart/form-data" method="POST">
<div class="box-body">
<div class="form-group">
<label for="client-id" class="col-sm-3 control-label">Client Id<a style="color: red">*</a></label>
<div class="col-xs-4">
<input class="form-control" name="clientId" id="client-id" required="true" placeholder="Client Id" type="text">
</div>
</div>
<div class="form-group" id="password-div-add-update">
<label for="client-name" class="col-sm-3 control-label">Client Name<a style="color: red">*</a></label>
<div class="col-xs-4">
<input class="form-control" name="clientName" id="client-name" required="true" placeholder="Client Name" type="text">
</div>
</div>
</form>

Related

How to sort data in spring jpa?

I am writing my first web-application project about rental a cars in java using Spring Boot, Hibernate and MySql.
In my app I want to have smth like sort methods. I made that by add in my view an input where users can type e.g type or model of car. I want to get result of query e.g type='sportcar' and from this result I want to sort data e.g by price DESC or ASC.
Here is my code of view
<body>
<form action="get" method="get">
<div class="form-group col-md-4">
<label for="inputState">Sort by</label>
<select name="sortMethod" id="inputState" class="form-control">
<option value="">Select sort method</option>
<option value="priceDESC">price desc</option>
<option value="priceASC">price asc</option>
</select>
<input type="submit" value="submit"/>
</div>
</form>
<form action="get" method="get">
Type: <input type="text" name="type">
<input type="submit" value="submit"/>
</form>
<form action="get" method="get">
Brand: <input type="text" name="brand"/>
<input type="submit" value="submit"/>
</form>
<form action="get" method="get">
Model: <input type="text" name="model"/>
<input type="submit" value="submit"/>
</form>
Here is my code of Controller
#GetMapping(path = "/get")
public String getAllCars(ModelMap modelMap) {
cars = carRepository.findAll();
modelMap.addAttribute("cars", cars);
return "car";
}
#GetMapping(path = "/get", params = "sortMethod")
public String getAllCars(#RequestParam(defaultValue = "priceASC", required = false) String sortMethod,
ModelMap modelMap) {
String parameterOfSort = "";
String wayOfSort = "";
char c;
for (int i = 0; i < sortMethod.length(); i++) {
c = sortMethod.charAt(i);
if (c >= 64 && c <= 90)
wayOfSort += c;
else if (c >= 97 && c <= 122)
parameterOfSort += c;
}
Sort.Direction sortType = Sort.Direction.valueOf(wayOfSort);
cars = carRepository.findAll(Sort.by(sortType, parameterOfSort));
modelMap.addAttribute("cars", cars);
return "car";
}
#GetMapping(path = "/get", params = "type")
public String getCarsByType(#RequestParam String type, ModelMap modelMap) {
cars = carRepository.findCarByType(type);
modelMap.addAttribute("cars", cars);
return "car";
}
I think that my approach isn't correct. How can I modify my code to get satisfying result and good approach for this situation?
Check the spring jpa doc, JPA support sort, in your case:
public interface CarRepository extend CrudRepository<Car, Long> {
List<Car> findByTypeOrderByPriceDesc(String type); //sportsCar, order by price desc
}

Spring boot email sending with attachment [duplicate]

This question already has an answer here:
Why I can't handle multipart upload in this Spring Boot application? I obtain "no matching editors or conversion strategy found"
(1 answer)
Closed 3 years ago.
Technology: Spring Boot
Hello Developers, Can sombody tell me what is wrong with my code?
Why i'm unable to send attachment in email?
Exception:
There was an unexpected error (type=Internal Server Error, status=500).
Failed to convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile': no matching editors or conversion strategy found
My jsp page
<pre>
<form:form modelAttribute="attachmentEmail" method="POST" action="/email-app/sendAttachmentEmail" cssClass="register-form"
id="register-form" enctype="multipart/form-data">
<div class="form-group">
<label for="fname"><i class="zmdi zmdi-account material-icons-name"></i></label>
<form:input path="name" name="name" id="name" placeholder="Name" required="required" />
<form:errors path="name" cssStyle="color:red;" cssClass="error" />
</div>
<div class="form-group">
<label for="phone"><i class="zmdi zmdi-phone"></i></label>
<form:input path="phone" name="phone" id="phone" placeholder="Phone" required="required" />
<form:errors path="phone" cssStyle="color:red;" cssClass="error" />
</div>
<div class="form-group">
<label for="email"><i class="zmdi zmdi-email"></i></label>
<form:input type="email" path="email" name="email" id="email" placeholder="Email" required="required" />
<form:errors path="email" cssStyle="color:red;" cssClass="error" />
</div>
<div class="form-group">
<label for="subject"><i class="zmdi zmdi-account material-icons-name"></i></label>
<form:input path="subject" name="subject" id="subject" placeholder="Subject" required="required" />
<form:errors path="subject" cssStyle="color:red;" cssClass="error" />
</div>
<div class="form-group">
<form:textarea path="comment" name="comment" id="comment" placeholder="Comment" rows="5" cols="35" required="required" />
<form:errors path="comment" cssStyle="color:red;" cssClass="error" />
</div>
<div class="form-group">
<label for="attachment"><i class="zmdi zmdi-file"></i></label>
<form:input path="attachment" type="file" name="attachment" id="attachment" required="required" />
<form:errors path="attachment" cssStyle="color:red;" cssClass="error" />
</div>
<div class="form-group form-button">
<input type="submit" id="signup" class="form-submit" value="Send" />
</div>
</form:form>
</pre>
My Contact.java & EmailController.java
<pre>
public class Contact {
#NotNull(message = "Name can't be blank.")
private String name;
#NotNull(message = "Name can't be blank.")
private String phone;
#NotNull(message = "Email can't be blank.")
private String email;
#NotNull(message = "Subject can't be blank.")
private String subject;
#NotNull(message = "Comment can't be blank.")
private String comment;
private CommonsMultipartFile attachment;
//getters
//setters
}
</pre>
My EmailController.java
<pre>
#RequestMapping(value ="/sendAttachmentEmail", consumes = "multipart/form-data", method = RequestMethod.POST)
public ModelAndView sendEmailWithAttachment(HttpServletRequest request, final #RequestParam("attachment") CommonsMultipartFile attachFile) throws MessagingException {
try {
ModelAndView mav =new ModelAndView("success");
log.info("Spring Boot - Sending Attachment Email...");
// reads form input
final String email = request.getParameter("mailTo");
final String phone = request.getParameter("phone");
final String name = request.getParameter("name");
final String subject = request.getParameter("subject");
final String comment = request.getParameter("comment");
log.info(name+" "+phone+" "+email+" "+subject+" "+comment);
if ((attachFile != null) && (attachFile.getSize() > 0) && (!attachFile.equals(""))) {
log.info("FileName====="+attachFile.getOriginalFilename());
} else {
log.info("FileName====="+attachFile.getOriginalFilename()+" "+attachFile);
}
Contact contact = new Contact();
contact.setName(name);
contact.setPhone(phone);
contact.setEmail(email);
contact.setSubject(subject);
contact.setComment(comment);
mav.addObject("name", contact.getName());
log.info("Sening Attachment Email...");
emailService.sendAttachmentEmail(contact, attachFile);
log.info("Done...");
return mav;
} catch (Exception e) {
log.error(e.getMessage());
return new ModelAndView("attachment-email");
}
}
</pre>
My EmailServiceImpl.java
<pre>
#Override
public void sendAttachmentEmail(Contact contact, CommonsMultipartFile attachfile) throws MessagingException {
emailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); // Enable the multipart flag!
String content = "Hi, <b>"+contact.getName()+"</b> Thank you for Contacting Us. PFB attachment.<br>";
helper.setSubject(contact.getSubject());
helper.setText(content+" <b>Comment:</b> "+ contact.getComment(), true);
helper.setTo(contact.getEmail());
helper.setFrom(env.getProperty("spring.mail.username"));
// Determine If There Is An File Upload. If Yes, Attach It To The Client Email
if ((attachfile != null) && (attachfile.getSize() > 0) && (!attachfile.equals(""))) {
System.out.println("\nAttachment Name?= " + attachfile.getOriginalFilename() + "\n");
helper.addAttachment(attachfile.getOriginalFilename(), new InputStreamSource() {
public InputStream getInputStream() throws IOException {
return attachfile.getInputStream();
}
});
} else {
System.out.println("No Attachment Is Selected By The User. Sending Text Email.");
}
}
});
}
</pre>
After submitting the button i am getting above mentioned error, Kindly help.
The essential is here: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile': no matching editors or conversion strategy found
By the other words try to change signature of your controller's method sendEmailWithAtachment on:
public ModelAndView sendEmailWithAttachment(HttpServletRequest request, final #RequestParam("attachment") StandardMultipartFile attachFile)

org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'text' is not present

I am trying to send a string and an image from the view to the controller, but I keep getting this error:
String parameter'text' is not present
I tried some of the solutions that I found online, but none of them solved my issue.
#RequestMapping(value = "/post-create", method = RequestMethod.POST)
#ResponseBody
public String[][] createPost(#RequestParam(value="text" ) String text,
#RequestParam(value = "photo") MultipartFile body) throws IOException {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = user.getUsername();
com.project.agro.entities.User user1 = userService.getUserByUsername(username);
Image image = new Image(body.getBytes());
imageService.addImage(image);
Post post = new Post();
post.setAuthor(user1);
post.setText(text);
post.setImage(image);
postService.addPost(post);
post = postService.addPost(post);
List<Post> posts = new ArrayList<>();
posts.add(post);
return utilsService.arrayFill(posts, user1);
}
JQuery
$("#create-post-button").click(function (e) {
e.preventDefault();
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: '/post-create',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
$("#posts-container").prepend(concatPost(data[0]));
$("#special-alert").remove();
$("#posts-container").append('' + special_alert_no_more_posts);
document.getElementById('create-post-form').reset();
$("#characters-number").text(5000);
from += 1;
$("#create-post-button").prop("disabled", true);
}
})
});
HTML
<div id="create-post-box" class="row">
<hr class=\ "middle\">
<a id="create-post-box-href"><span id="arrow-down"
class="fa fa-angle-down"></span><span id="arrow-up"
class="fa fa-angle-up hidden"></span></a>
<div id="create-post-form-div" class="hidden">
<form enctype="multipart/form-data" id="create-post-form" method="POST">
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control" maxlength="5000" rows="5" id="post-text" name="text"></textarea>
<div id="counter">
<p id="counter-line">
<span id="characters-number">5000</span> symbols left.
</p>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<label class="input-group-btn"> <span class="btn btn-primary"><span class="glyphicon glyphicon-picture"></span><input id="file" type="file" style="display: none;" name="photo" accept="image/x-png,image/gif,image/jpeg" multiple>
</span>
</label> <input type="text" class="form-control" readonly>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="button" id="create-post-button" class="btn btn-primary btn-md btn-block">Post it</button>
</div>
</div>
</form>
</div>
I tried
#RequestParam(value="text" ,required=false)
but then it shows:
String parameter'photo' is not present with Multipart
missingservletexception
Try using #RequestBody MultipartFile body instead of #RequestParam(value = "photo") MultipartFile body

JSTL Spring MVC Recursive Form JSP

I am trying to build a dynamic form generator getting a json as an input. The json comes from an AWS device shadow and I want to build a form which allows the user to manipulate the desired state of it.
The controller class looks like this:
#Controller
public class FormGeneratorController {
#RequestMapping(value = "/form/textfield", method = RequestMethod.GET, params = {"parentName", "propertyName", "propertyValue"})
public ModelAndView getTextField(#RequestParam(value = "parentName", required = false, defaultValue = "") String parentName,
#RequestParam(value = "propertyName", required = false, defaultValue = "") String propertyName,
#RequestParam(value = "propertyValue", required = false, defaultValue = "") String propertyValue) {
ModelAndView model = new ModelAndView("jsonConfigTextField");
model.addObject("parentName", parentName);
model.addObject("propertyName", propertyName);
model.addObject("propertyValue", propertyValue);
return model;
}
#RequestMapping(value = "/form/objectfield", method = RequestMethod.GET, params = {"parentName", "propertyName", "propertyValue"})
public ModelAndView getObjectField(#RequestParam(value = "parentName", required = false, defaultValue = "") String parentName,
#RequestParam(value = "propertyName", required = false, defaultValue = "") String propertyName,
#RequestParam(value = "propertyValue", required = false, defaultValue = "") String propertyValue) {
ModelAndView model = new ModelAndView("jsonConfigObjectField");
JSONObject settings = new JSONObject(propertyValue);
model.addObject("parentName", parentName);
model.addObject("propertyName", propertyName);
model.addObject("propertyValue", settings);
return model;
}
#RequestMapping(value = "/form", method = RequestMethod.GET)
public ModelAndView getForm() {
ModelAndView model = new ModelAndView("settingsForm");
model.addObject("parentName", "");
model.addObject("propertyName", "root");
model.addObject("propertyValue", "{\"light\":{\"test\":\"t\"}}");
return model;
}
}
settingsForm.jsp:
<form>
<c:import url="/form/objectfield?parentName=${parentName}&propertyName=${propertyName}&propertyValue=${propertyValue}"></c:import>
<input type="submit" value="Absenden">
</form>
jsonObjectField.jsp:
<c:forEach items="${propertyValue.keys()}" var="propertyKey">
<c:if test="${propertyValue.get(propertyKey).getClass().name == 'java.lang.String'}">
<c:import url="/form/textfield?parentName=${parentName}&propertyName=${propertyKey}&propertyValue=${propertyValue.getString(propertyKey)}" ></c:import>
</c:if>
<c:if test="${propertyValue.get(propertyKey).getClass().name == 'org.json.JSONObject'}">
<c:import url="/form/objectfield?parentName=${parentName}&propertyName=${propertyKey}&propertyValue=${propertyValue.getJSONObject(propertyKey)}" ></c:import>
</c:if>
</c:forEach>
jsonConfigTextField.jsp:
<div class="form-group">
<label for="<c:out value="${parentName}_${propertyName}"></c:out>"><c:out value="${parentName}_${propertyName}"></c:out></label>
<input type="text" class="form-control" id="${parentName}_${propertyName}" name="${parentName}_${propertyName}" value="${propertyValue}">
</div>
This produces:
<form>
<div class="form-group">
<label for=",,,_test,light,root">test,light,root</label>
<input type="text" class="form-control" id=",,,_test,light,root" name=",,,_test,light,root" value="t,{"test":"t"},{"light":{"test":"t"}}">
</div>
<input type="submit" value="Absenden">
</form>
But I want to generate a form like this:
<form>
<div class="form-group">
<label for="root_light_test">root_light_test</label>
<input type="text" class="form-control" id="root_light_test" name="root_light_test" value="t">
</div>
<input type="submit" value="Absenden">
</form>
It seems like there is a problem with the JSONObject within in a JSONObject where the recursion I thought I would be doing somehow goes wrong. I do not understand where all the commas in the output are comming from.
Since recreating the issue is pretty hard I created a repository for you to clone and test the thing for yourself: https://github.com/faxe1008/JSTLRecursiveForm
I really would appreciate any help on this, today I spent 4 hours trying to figure out the problem...
You should parse the JSON input in your controller, with Jackson for example, and add the data to simple objects. These you should pass to your model, which is available in your view. In you view simply iterate the created objects

Ajax call error in Spring MVC

I have a form where I add the customer's informations. This informations are passed to #Controller by an Ajax call.
Customer.java
public class Customer {
private String name;
private String fiscalCode;
private String vat;
private String telephone;
private String webSite;
private String sector;
private String address;
//Below there are constructor and getter/setter methods
Above the form there is:
<c:set var="serverUrl" value="${pageContext.servletContext.contextPath}"/>
<script>
var serverUrl = '${serverUrl}';
</script>
Form in the jsp
<form>
<div class="form-group">
<input id="nameCustomer" class="form-control" type="text" placeholder="Name customer">
</div>
<div class="form-group">
<input id="fiscalCode" class="form-control" type="text" placeholder="Fiscal code">
</div>
<div class="form-group">
<input id="vat" class="form-control" type="number" placeholder="VAT number (if available)">
</div>
<div class="form-group">
<input id="telephone" class="form-control" type="tel" placeholder="Phone number">
</div>
<div class="form-group">
<input id="website" class="form-control" type="email" placeholder="Customer's Website (if available)">
</div>
<div class="form-group">
<input id="address" class="form-control" type="text" placeholder="Customer's Address">
</div>
<div class="form-group">
<input id="sector" class="form-control" type="text" placeholder="Sector">
</div>
<button id="createCustomer" type="button" class="btn btn-success" style="text-align: center">Save</button>
</form>
Ajax call (the link to this ajax call code is below the form)
$("#createCustomer").click(function () {
alert("createCustomer");
alert(serverUrl);
var nameCustomer = $("#nameCustomer").val();
var fiscalCode = $("#fiscalCode").val();
var vat = $("#vat").val();
var telephone = $("#telephone").val();
var website = $("#website").val();
var address = $("#address").val();
var sector = $("#sector").val();
alert(address);
$.ajax({
url: serverUrl + "/addCustomer",
dataType: 'text',
data: {name: nameCustomer,
fiscalCode: fiscalCode,
vat: vat,
telephone: telephone,
webSite: website,
address: address,
sector: sector},
success: function (data) {
$("#customerAdded").modal('show');
},
error: function (xhr, error, exception) {
$("#errorCustomer").modal('show');
}
});
});
Controller
#Controller
public class CustomerController {
#RequestMapping("addCustomer")
public void addCustomer(#ModelAttribute Customer customer){
JOptionPane.showMessageDialog(null, customer.toString());
}
Chrome gives me this error:
http://localhost:8080/ReportVisitaWeb/addCustomer?name=gdg&fiscalCode=dfgdfg&vat=&telephone=dfgg&webSite=dfggf&address=dfgddf&sector=gdg Failed to load resource: the server responded with a status of 404 (Not Found)
Why?
You are not mapping the request "addCustomer" correctly. Edit your CustomerController as below:
#Controller
public class CustomerController {
#RequestMapping("/addCustomer")
public void addCustomer(#ModelAttribute Customer customer){
JOptionPane.showMessageDialog(null, customer.toString());
}
}

Categories