#RequestMapping(value = "/Fin_AddCheckBook", method = RequestMethod.POST)
public #ResponseBody
JsonResponse addCoaCategory(
#RequestParam(value="checkbookNumber", required=true) String checkbookNumber,
#RequestParam(value="checkbookName", required=true) String checkbookName,
#RequestParam(value="startNumber", required=true) long startNumber,
#RequestParam(value="bankId", required=true) long bankId,
#RequestParam(value="currencyId", required=true) long currencyId,
#RequestParam(value="noOfLeves", required=true) int noOfLeves,
#RequestParam(value="alertAt", required=true) int alertAt,
#RequestParam(value="isActive", required=true) int isActive, Map map, Model model) {
I have two table in one form ! I want to receive first table elements by name by specifying #RequestParam(value="startNumber", required=true) long startNumber;
but
second table elements in Map i.e Map map
How to receive some parameter with name and all other element in map ?
Create your own objects :
public class MyMap {
private String myObject1; // dont forget that these names should be same as #RequestParam values
private Integer myObject2;
//setters and getters. they are must!!
}
public class MyMap2 {
private String my1;
private Integer my2;
//setters and getters. they are must!!
}
Now put this object as a parameter of your controller method.
#RequestMapping(value = "/Fin_AddCheckBook", method = RequestMethod.POST)
public #ResponseBody JsonResponse addCoaCategory(MyMap myMap, MyMap2 myMap2, BindingResult result) {
if (!result.hasErrors()) {
// work with myMap myMap2
}
}
Related
I am creating Spring Boot Web service and I have a Model Employee
public class Employee {
private String id;
private String name;
private String designation;
private int salary;
//Has Getters and Setters
}
I want to create a Get request which will fetching and filter the List of Employees based on the parameters given by user.
For example, if the user gives name of an employee and designation of employee, the get method should filter those result. For various combination of parameters it should work.
#Override
public List<Employee> getEmployees(Map<String, Object> parameters) {
if (parameters.size() == 0)
// code to return all employees;
List<Employee> selectedEmployees = new ArrayList<Employee>();
for(Employee currentEmployee: new ArrayList<Employee>(employee.values())) {
for(Map.Entry<String, Object> check: parameters.entrySet()) {
try {
if(check.getValue() instanceof Integer) {
int condition = (int) Employee.class.getMethod("get" + check.getKey()).invoke(currentEmployee);
if((int) check.getValue() == condition)
selectedEmployees.add(currentEmployee);
} else if (check.getValue() instanceof String) {
String condition = (String) Employee.class.getMethod("get" + check.getKey()).invoke(currentEmployee);
if (((String) check.getValue()).equals(condition))
selectedEmployees.add(currentEmployee);
}
} catch(Exception e){
e.printStackTrace();
}
}
}
return selectedEmployees;
}
In order to avoid multiple if else cases I am filtering list based on String and Integer above.
I think I am making an error in the below code which sending request in Controller.
#RequestMapping(value={"/employees","/{id}/{name}/{designation}/{salary}"})
public List<Employee> getEmployeeByProperty(EmployeeRequestParameters requestParams){
//Map for storing parameters to filter the List
Map<String, Object> filterParams = new HashMap<>();
if(requestParams.getIdParam().isEmpty()) {
filterParams.put("id", Integer.parseInt(requestParams.getIdParam()));
}
if(!requestParams.getNameParam().isEmpty()) {
filterParams.put("name", requestParams.getNameParam());
}
if(!requestParams.getDesignationParam().isEmpty()) {
filterParams.put("designation", requestParams.getDesignationParam());
}
if(requestParams.getSalaryParam().isEmpty()) {
filterParams.put("salary", Integer.parseInt(requestParams.getSalaryParam()));
}
return EmployeeService.getEmployeesByProperty(filterParams);
}
If {id} field is not full, {name} or {designation} or {salary} to be null.For {name} or {designation} or {salary} to be full Because should be {id} full.
#GetMapping("/employees")
public List<Employee> getEmployeeByProperty(#RequestParam(value = "id", required=false) String id,
#RequestParam(value = "name", required=false) String name,
#RequestParam(value = "designation", required=false) String designation,
#RequestParam(value = "salary", required=false) int salary) {
//Your codes
}
Even if {id} is empty, you can use others.
I am using Springfox and Swagger to generate swagger files. Right now I'm using #ModelAttribute to pull the variables from an object (NetworkCmd) to show as query params in the swagger doc.
I currently have the following controller:
#RequestMapping(value = "/{product_id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseHeader()
public ResponseEntity<?> networkResponse(
#RequestHeader HttpHeaders headers,
#PathVariable("product_id")String productId,
#Valid #ModelAttribute NetworkCmd cmd,
BindingResult result)
throws Exception {
...
}
And here is a sample of NetworkCmd:
#ItemId
#NotNull(message = "product cannot be null")
#ApiModelProperty(
value = "testing")
private String product_id;
#ApiModelProperty(
value = "key",
private String key;
#ApiModelProperty(
value = "parent")
private Boolean is_parent_id;
#Min(0)
#ApiModelProperty(
value = "radius")
private double radius = 10d;
One of the variables in this class is a custom domain object Nearby.
private Nearby nearby = null;
public Nearby getNearby() {
return nearby;
}
public void setNearby(String nearby) throws ParseException {
this.nearby = Nearby.parse(nearby);
}
This is kind of a special variable because it takes in a String, and then parses that string and turns it into the Nearby object.
My problem is that this Nearby variable isn't showing up on the generated swagger document through #ModelAttribute. I'm happy to provide any more information.
One way to get around this problem is to create an alternate type rule in your docket. This way anytime we encounter the nearby type we treat it as a string.
new Docket(...)
.directModelSubstitute(Nearby.class, String.class)
I have below API to be tested. Not getting solution to pass string array to requestors. Tried with comma seperated values, values with in [] etc.
#RequestMapping(value = "/v10/{user}/alerts/alertguids/{requestors}", method = RequestMethod.GET)
#ResponseBody
#ResponseStatus(HttpStatus.OK)
public String[] retrieveRunnableAlertGuidsByRequestors(#RequestParam(value = "productId") final String productId,
#PathVariable final String[] requestors)
I'm not sure with #PathVariable but you can use the #RequestParam.
eg:
#RequestMapping(value = "/v10/{user}/alerts/alertguids/{requestors}", method = RequestMethod.GET)
#ResponseBody
#ResponseStatus(HttpStatus.OK)
public String[] retrieveRunnableAlertGuidsByRequestors(#RequestParam(value = "productId") final String productId,
#RequestParam(value = "param[]") final String[] requestors)
Lets say I have a Category domain model object that follows a file tree structure. I want to be able to construct a RequestMapping annotation for the controller method so that
/category/art/macros
/category/people/weddings/2014/5-19
/category/sports/college/baseball/2014/5-19
can be handled by the minimum number of controller methods.
I already have one controller method defined:
#RequestMapping(value ={"/category/{category}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category){
model.addAttribute("message", category);
return "gallery";
}
This works for a single URL like
/category/sports
How can I adapt this to be more flexible?
The challenge is here that you can't make #PathVariable optional but you can have two or more controller methods which can call the same service code. So, for you three URL patterns you have to define three different controllers:
GET: /category/art/macros
#RequestMapping(value ={"/category/{category}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category){
model.addAttribute("message", category);
return "gallery";
}
GET: /category/people/weddings/2014/5-19
#RequestMapping(value ={"/category/{category}/{subcategory}/{year}/{date}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category,
#PathVariable(value = "subcategory") String subcategory,
#PathVariable(value = "year") String year,
#PathVariable(value = "date") String date
){
model.addAttribute("message", category, subcategory, year, date);
return "gallery";
}
GET: /category/sports/college/baseball/2014/5-19
#RequestMapping(value ={"/category/{category}/{subcategory}/{year}/{date}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category,
#PathVariable(value = "subcategory") String subcategory,
#PathVariable(value = "sub_sub_category") String sub_sub_category,
#PathVariable(value = "year") String year,
#PathVariable(value = "date") String date
){
model.addAttribute("message", category, subcategory, sub_sub_category, year, date);
return "gallery";
}
PS You can user #RequestParam which can be optional and reduce the number of controllers.
I have a Contact object that I put in the request, this object is modified in the
form and then get the modified object. I would like the object that is back is the same object that you send, you keep the value of the attributes that were not in the form.
class Contact{
private String name; // this attributes will be modified
private String lastName;
private Long id;
private Date created; // this atributes will not be modified
// getters and setters ....
}
#RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
public String updateContact(#PathVariable("id") Long id, Model model) {
Contact c = contactDao.get(id);
model.addAttribute("contact", c);
return "contact/form";
}
#RequestMapping(value = "/{id}/edit", method = RequestMethod.POST)
public String update(#PathVariable("id") Long id, #Valid #ModelAttribute Contact contact, BindingResult result, Model model) {
// The contact I get here I want to keep the original attributes of the
// object sent, and have the changes in the fields shown on the form. is that possible?
return "redirect:/contact";
}
<form:form action="${pageContext.servletContext.contextPath}/tags/create" commandName="contact">
<form:input path="name"/>
<form:errors path="name" cssClass="formError"/>
<form:input path="lastName"/>
</form:form>
I do not want to use hidden fields to maintain the value of the attributes that will not be changing
If you only want some of the fields to be handled in a form, make a new class - ContactDTO that contains only them, and then manually (or through reflection) copy them to the original Contact object (which you load by id from the DB)
I found the solution to the problem by stating the contact object as an object that lives in the session
#Controller
#RequestMapping("/contact")
#SessionAttributes("contact")
public class ContactController {
....
....
#RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
public String updateContact(#PathVariable("id") Long id, Model model) {
Contact c = contactDao.get(id);
model.addAttribute("contact", c);
return "contact/form";
}
#RequestMapping(value = "/{id}/edit", method = RequestMethod.POST)
public String update(#PathVariable("id") Long id, #Valid #ModelAttribute Contact contact, BindingResult result, Model model) {
contactDao.update(contact);
return "redirect:/contact";
}
}
What is your persistence framework? is it JPA or Hibernate? If so, annotate the field with #Column(updatable=false)