Conditional object population - java

Hy guys, I've turning around a problem using Struts2.
Basically I've a form that the user can submit filling different fields. I would like to populate conditionally the right object with the properties insert by the user.
So for example, if the user fill the form in a intermediary way I would like to use the properties for to create an Intermediary object, instead if the user fill the request in entity way, i'll use the properties for to create the Entity object, ecc...
These object share the same interface Request.
Is there any way to use polimorphically properties for to create Intermediary or Entity object?
Suppose this is my two POJO:
public class Intermediary implements Request{
private String name;
private String surname;
private String code;
private String FiscalCode;
private String address;
...
/*Getters and setters */
....
}
public class Entity implements Request{
private String name;
private String surname;
private String code;
....
/*Getters and setters */
....
}
This could be my form into the jsp page:
<s:form action="fillRequest" id="formRichiesta" name="formRichiesta" method="post">
<s:radio id="tipoRichiedente" name="tipoRichiedente" list="richiedenti">
<label>Name</label><s:textfield name="name"/>
<label>Surname</label><s:textfield name="surname"/>
<label>code</label><s:textfield name="code"/>
<label>Adress</label><s:textfield name="adress"/>
<label>Fiscal Code</label><s:textfield name="fiscalCode"/>
</s:form>
<s:submit>
Basically my problem is that I can discover the kind of request the the user trying to fill only ofter submission and watching at the radiobutton state.
Is there any way to mapping the properties into the right object directly instead of creating one big object with all the form properties and then create the right implementation? for to map properties could I use the interface reference?
For example image my action:
public class RequestAction {
private Request request;
....
}
So in my jsp could I use:
<label>Name</label><s:textfield name="request.name"/>
Thanks in advance.

Related

How to map a List<ObjectDTO> to Entity inside of a Bean with Model Mapper?

I have a 1:N relationship where a Victim might have lots of EmergencyContacts.
I've created a DTO called VictimDTO and inside of it there's a List and I'm using ModelMapper to convert my DTO into an Entity.
When I get rid of the list just for testing purposes, it works fine placing this code snippet inside of the insert "POST" method in the Controller layer in Java:
VictimEntity victimEntity = modelMapper.map(victimDTO, VictimEntity.class);
But now I've placed this List inside of my VictimDTO and I'm getting an Exception when trying to use this code.
My DTO actual code is this one as it follows below:
public class VictimDTO {
private String name;
private int age;
private String email;
private String phone;
private List<ContactDTO> contactDTOList;
//getters and setters
}
How can I use ModelMapper to convert a POJO with a Collection (List) as an instance variable inside into an Entity?
Thank you for your help.
Best regards,
Lucas AbrĂ£o

Spring Boot action with composite class and array request

I would like to create a C# like composite class action with spring boot 2 with an array request.
My client will send the following:
Contet-Type: application/x-www-form-urlencoded
With body:
company[name]:qwe
company[size]:1
address[country]:asd
address[address]:zxc
My action should be something like this:
#PostMapping
public ResponseEntity<ResponseData<String>> action(CompanyCompositeRequest request)
{
...
}
And the classes that I'd like to fill automatically:
class CompanyCompositeRequest {
private Company company;
private Address address;
}
class Company {
private String name;
private int size;
}
class Address {
private String country;
private String address;
}
And I'd like to run the Validator from the javax.validation on the properties of the classes in the composite.
Is that even possible? I tried a lot of version, and didn't find a working version, but I saw similar solutions. If I need to change the sent data from the client it's possible, for example in a JSON raw data, or something like that.
Thanks!
It is possible by using the #RequestBody annotation in your controller method. It will make Spring automagically map the request body into your custom class.
See: http://websystique.com/springmvc/spring-mvc-requestbody-responsebody-example

Thymeleaf form can't handle org.bson.Document type

I have an entity class with fields of type org.bson.Document. These are values that I am not allowed to modify, but when using Spring Data I need to map them in my model class so that after saving the document back to Mongo these values won't be lost. So the document is fetched from Mongo, mapped to a User POJO and then passed to a Thymeleaf form. When I try to send Thymeleaf form back to the controller I get 400 Bad Request "Validation failed for object..." error and I know it's because of these two additional Document fields. How can I pass these fields to Thymeleaf and then back to the controller? They aren't modified in the form, just appear as hidden inputs:
<input id="resetPassword" th:field="${user.resetPassword}" type="hidden"/>
<input id="consents" th:field="${user.consents}" type="hidden"/>
And my User class:
#Data
#Document(collection = "users")
#NoArgsConstructor
public class User {
#Id
private ObjectId id;
private String email;
private String name;
private String surname;
private String phone;
private String password;
private String country;
private SecurityLevel securityLevel = SecurityLevel.LOW;
private Timestamp created = Timestamp.from(Instant.now());
private Boolean blocked = false;
private org.bson.Document resetPassword;
private org.bson.Document consents;
}
It sounds like the object is being successfully injected into the Thymeleaf template, but not parsed correctly in Spring when the form is returned.
You should examine the representation in the web page (expecting json?) and then ensure that you have a handler defined in Spring that can successfully deserialise the returned object.
If the Document type does not have a conventional constructor (no-args or all-args), or some of the fields are 'hidden' (without the standard getXxx and setXxx methods), then Spring will not be able to reconstruct the object when the form is submitted without a custom handler.
Similarly, if there are not getters for all of the fields (And sub fields) of the object, the Thymeleaf template will have an incomplete object embedded that will not upload correctly.
Take a look at this blog post for some further info: https://www.rainerhahnekamp.com/en/spring-mvc-json-serialization/
I solved it by creating a custom Formatter like that:
public class BsonDocumentFormatter implements Formatter<Document> {
#Override
public Document parse(String s, Locale locale) throws ParseException {
return Document.parse(s);
}
#Override
public String print(Document document, Locale locale) {
return document.toJson();
}
}
And then I registered it in my WebMvcConfigureruration:
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new BsonDocumentFormatter());
}

How to upload file to bean that is set in action class in Struts 2

I know how to upload a file into the action class but my requirement is different. I have a list of pojo-s where each pojo contains a field called file.
for example:-
public class Pojo{
private int pk;
private File file;
//setters and getters
}
In my action class:-
public class MyAction{
private List<Pojo> pojos;
//setter getter
}
from my jsp when i select a file and say upload it has to set to the Pojo "file" property. how do i do that? I have complete idea of how to upload directly to the action class but now it is different. the file has to go and sit in the Pojo class file property. How can i do this?
The details about uploading multiple files are described here.
When you upload one or more files, you can point to the property (single or collection) both in an action property, or in a property of an action's object .
The only part missing is the JSP, where you simply need to use the dot notation to specify the object hierarchy. Also don't forget all the getters and setters needed, and the contentType / fileName properties too.
POJO
public class Pojo{
private int pk;
private File file;
private String fileContentType;
private String fileFileName;
// Getters and Setters
}
Action
public class MyAction{
private List<Pojo> pojos; // Getter and Setter
}
JSP
<s:file name="pojos.file" multiple="multiple" />

Accessing object fields added to model map in jsp page

In my Spring web project, I have added a class object in to the model map. This is the class
public class ProjectDetailsBean {
private String title;
private String type;
private String addedBy;
private String status;
private String updatedOn;
private String relavantBranch;
// getters and setters are here
}
After setting all the attributes to a ProjectDetailsBean object instance, I add that to the model map in my controller class.
epb is that instance.
model.addAttribute("projectDetails", epb);
Now I need to access the fields of projectDetails in a jsp page. Those values need to be assigned to separate input fields. I cannot figure out how to do that. Could you please tell me how to do that.
Thank you!
You need to access through Expression language
${projectDetails.title}
${projectDetails.addedBy}
....... so on

Categories

Resources