SpringBoot reject all request if some header parms are not there even if we don't include them in specific requests - spring-boot

An example of that is below. I am not using associateId, firstName, lastName and galleryId but I want this request to be rejected if they are not present (Below code works for this). But is there a common place where we can set it for all request by default and not have to repeat the below code for all request?
#ApiOperation("Delete Project")
#DeleteMapping(value = "{projectId}")
public void deleteProject(
#ApiParam(value = "Project Id to be deleted", required = true) #PathVariable String projectId,
#RequestHeader("associateId") String associateId,
#RequestHeader("associateFirstName") String firstName,
#RequestHeader("associateLastName") String lastName,
#RequestHeader("galleryId") String galleryId) {
pjs.deleteProject(projectId);
}
I have lot of endpoints and only few use all 4 header variables but I want all request to have access to them even if they are not using them.

Related

Spring Multiple RequestParams vs RequestBody, which is Preferred?

I am new to Spring Rest. While Doing POST, we have 2 options either #RequestBody or #RequestParams.
My query is not what they are. I am pretty well know what they are.
Normally we use #RequestParams for form-urlencoded and #RequestBody for JSON/XML.
I have a scenario as below:
class EmployeeDTO {
long id;
String name;
String age;
String address;
String salary;
//Getters and Setters
}
For POST, I can directly use as void doSomething(#RequestBody EmployeeDTO){ }
and also I can do same thing but using 5 RequestParams
void doSomething(#RequestParam(id) long id, #RequestParam(name) String name, #RequestParam(age) String age, #RequestParam(address) String address, #RequestParam(salary) String salary){ }
I have seen some good sites like Stripe, they following only #RequestParam in their REST Api.
I actually got to understand that we use RequestBody for Complex Input and#RequestParam for simple parameters.
So, my actual query is: In above class, had only 5 parameters, I am thinking its okay going with #RequestParam, But what if there are like 7 or 10 input params, then should I chose RequestBody or (7 or 10) REquestParam?
EDIT:
class Orders {
String id;
Employee employee;
}
It is not really a choice based on "number of data I have to push on server".
Historically and in general the use of the query string is, as the name implies, to query data. And so request param would be the preferred choice when you want to "pull" data HTTP GET
Here if the goal is to "push" data on the server (for instance "to create an employee") you should prefer sending this data in request body.
Moreover the query string is part of the URL, and it can be read by everyone sitting between the clients and the API, so we shouldn’t put sensitive data like passwords into the query string.
you can mimic the format of query string in your body by using the mime type application/x-www-form-urlencoded. Here request body uses the same format as the query string.
parameter=value&parameter2=another

Thymeleaf add multiple parameters to URL in one go

Given I have MVC endpoint with mapping:
#RequestMapping
public String eventHistory(final Model model,
#PageableDefault(sort = {"id"}, direction = DESC) final Pageable pageable,
final EventHistoryFilter eventHistoryFilter) {
...
model.addAttribute("eventHistoryFilter", eventHistoryFilter);
}
where EventHistoryFilter is:
final class EventHistoryFilter {
private Long eventId;
private String eventType;
private String eventDateFrom;
private String eventDateTo;
...
}
and in thymeleaf template I would like to construct URL with parameters, e.g.:
th:href="#{/event-history(page=${page.number-1},eventId=${eventHistoryFilter.eventId},eventType=${eventHistoryFilter.eventType},eventDateFrom=${eventHistoryFilter.eventDateFrom},eventDateTo=${eventHistoryFilter.eventDateTo})}"
How can I add multiple parameters into URL in one go?
I didn't find it here: https://www.thymeleaf.org/doc/articles/standardurlsyntax.html#adding-parameters
I'd like to avoid specifying each parameter one by one.
EDIT:
I tried to use https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#building-uris-to-controllers
String url = MvcUriComponentsBuilder.fromMappingName("EHE#eventHistory").arg(2, eventHistoryFilter).build();
but resolved URL doesn't contain any request parameters.
and thymeleaf counterpart:
th:href="${#mvc.url('EHE#eventHistory').arg(2,__${eventHistoryFilter}__).build()}"
fails during evaluation.

Send email with multiple attachments in Spring boot

I'm creating an api for sending email in Spring Boot. I can successfully send an attachment in email using the following api
#PostMapping("/send")
public void sendMail(#RequestParam(value = "receiver") String receiver,
#RequestParam(value = "subject") String subject, #RequestParam(value = "content") String content,
#RequestParam(value = "file", required = false) MultipartFile file) {
mailService.send(receiver, subject, content, file);
}
But an email can have multiple attachments. So, using this link as the reference, I updated my code to
#PostMapping("/send")
public void sendMail(#RequestParam(value = "receiver") String receiver,
#RequestParam(value = "subject") String subject, #RequestParam(value = "content") String content,
#RequestParam(value = "files", required = false) MultipartFile[] files) {
mailService.send(receiver, subject, content, files);
}
With this in place, I can add multiple images from the Swagger UI
Update:
I get the following form in Swagger from which I can upload images
But when I submit the form, I found that the value in files is now null instead of an array of files.
What am I missing?
As #MebinJoe mentioned, it was an issue with swagger. Couldn't solve the issue with swagger but ended up using Postman for testing the above piece of code. Multiple files were successfully attached and sent in email.

Multipartfile parameter order precedence causing error

Basically, I am sending two parameters , one a String and the other a file to my controller in Spring Boot . In the action, when I receive the file first and then the String next, like so
#RequestMapping(value = "/updatemedia", method = RequestMethod.PATCH,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> updateMedia(#RequestParam(value ="file") MultipartFile fileToUpload , #RequestParam(value = "keyId") String keyId )
everything is fine and I am able to access the String and the file correctly.
But when I change the order of the parameters , like so
#RequestMapping(value = "/updatemedia", method = RequestMethod.PATCH,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> updateMedia( #RequestParam(value = "keyId") String keyId , #RequestParam(value ="file") MultipartFile fileToUpload )
and send the params through Postman, I am hitting the below error
I researched a lot but am not able to understand this behaviour.
Because you send keyId in body while it's declared as #RequestParam
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html .
#RequestParam has nothing to deal with request body, it's passed in request url.
What about your example, the first approach works, because your method expects one #RequestPart, the others are ignored.

Passing URL parameters to Controller but NOT displayed in URL

I have a search page where I search for list of employees based on some criteria and once the employee list is displayed, I click on one of the Employee name to view the employee details.The search result is displayed in a tabular format and includes Employee Name(only the first name),Employee Id and Full Name of the employee.Employee ID and Full Name are read only.
In my code, when i click on the Employee Name, I should get additional details of the employee via the employee id as shown below:
employee.jsp
Employee Name
EmployeeDetailController.java
#RequestMapping(value = "/employeeDetail.do", method = RequestMethod.GET)
public ModelAndView employeeDetail(#RequestParam(value = "employeeID") final String employeeID,
#RequestParam(value = "fullName") final String fullName, final HttpServletRequest request,
final HttpServletResponse response, final ModelMap modelMap) throws Exception {
As a part of security test, i need to remove the employeeID and fullName from the URL as it exposes the employee data.
Can anybody suggest how to pass the request parameters to the controller class in such a way that the parameters are not visible in URL i:e expected URL should be ${ctx}/employeeProfile/employeeDetail.do?
Thanks in advance.

Resources