spring model is sometimes empty - spring

i am confused about availibility from data within spring-model.
Example:
#RequestMapping("myAbosolutPathAAA.action")
public String myHandlerONE(#RequestParam(required = false) String date, Model model){
ArryList<Car> myCars = carsDAO.findAll(); //retrieve all cars from DB.
model.addAttribute(CARS, myCars);
return "page1.action";
}
Now i can handle my car-list on frontend.
At next i navigate on next controler-handler, where i need myCars-list again.
So i dont want to retrieve database anymore. I want to retrieve my spring-model:
#RequestMapping("myAbosolutPathBBB.action")
public String myHandlerTWO(#RequestParam String name, Model model){
ArryList<Car> myCars = model.asMap().get(CARS); //retrieve spring-model and not db .
//do somethings with car list....
return "page2.action";
}
But when i want to retrieve spring-model, my car-list is null.
Sometimes it works. I can not finde any explanation on spring-reference.
Can's anybody explain, when can i retrieve spring-model and when not?

Related

Insert images in database

I'm making a real estate app in spring boot - thymeleaf and I really need to ask you how to store images. I was thinking about making a table just for images and anotate it manyToOne, and insert it into Property entity because one property can have 10,15,20 images and that is the part I know how to do.
But I'm not sure how to handle the rest of the code. How to make file upload in the /add method?
And also howadd and show them in thymeleaf?
This is my /properties/add method without the option of inserting images:
#RequestMapping("/add")
public String add(Model theModel) {
Property theProperty = new Property();
User theUser = new User();
theProperty.setUser(theUser);
List<User> userList = userService.findAll();
Address theAddress = new Address();
theProperty.setAddress(theAddress);
List<Address> addressList = addressService.findAll();
theModel.addAttribute("property", theProperty);
theModel.addAttribute("user", userList);
theModel.addAttribute("address", addressList);
return "properties/property-form";
}
I don't expect you to type it but maybe somebody know the most similar project
I don't think you wanna store the images directly to the database but having a table as a reference to the image itself.
You can do it the same way as you are doing with the userList.
theProperty.addAttribute("images", imageList);

Spring REST ResponseEntity how to return response when we have two objects

1. For example UserProfile which has 3 properties name,dob, age
2. And 2nd class let's say UserProfileResponse which has only "id"
public ResponseEntity<UserProfileResponse> createUserProfile(#RequestBody UserProfile userProfile)
{
UserProfileResponse userProfileResponse = new UserProfileResponse();
userProfileResponse.setId(??) // How do I set ID?
**createUserProfileData(userProfile) /// This is used to create DB record**
return new ResponseEntity<UserProfileResponse>(userProfileResponse,HTTPStatus.OK);
}
So for this userProfileResponse.setId(??) how can I set the ID value?
can I directly do like this userProfileResponse.setId(userProfileResponse.getId());
Or I can Pass one more request body like this
ResponseEntity<UserProfileResponse> createUserProfile(#RequestBody UserProfile userProfile, #RequestBody ID)
Thanks in advance.
You can call createUserProfileData method and return the id of the newly inserted object from it.
In createUserProfileData method, you can call saveAndFlush method of the repository which will save the userProfile Object.
This will return the id of the newly inserted object.
Finally your code will look like below:
public ResponseEntity<UserProfileResponse> createUserProfile(#RequestBody UserProfile userProfile)
{
UserProfileResponse userProfileResponse = new UserProfileResponse();
int id = createUserProfileData(userProfile)
userProfileResponse.setId(id)
return new ResponseEntity<UserProfileResponse>(userProfileResponse,HTTPStatus.OK);
}
If you want to get a value from the RequestBody UserProfile which it didn't contain it actually.Sorry it's impossible.
And we only could receive one requestBody at one time,so we need to use some other ways to collect the info.There is some other solutions:
Use #PathVariable to get ID from url
Use #RequestParam to get Id from requestParam
Add a new field named Id into your UserProfile
Use other way that that could get your Id,this depend how you persistent or generate the Id.
In your case,I'm not sure what you are going to do with the id.
If the "createUserProfileData" method means you need to offer an id first for persistence.
Well,I dont know which database and what kind of framework you are using.As I know,most of framework and database has the ability to generate the id automatically.But if you insist to generate id by your self,I recommend you UUID.
If the "createUserProfileData" method is saving the UserProfile to the database literally and the id is generated by the database itself,then you just do it and put the Id represent the record you just saved to UserProfileResponse.
As to how to get the id represent the record you just saved?It's up to the framework you're using and precisely how the code is written.

Manipulate WebAPi POST

I have a WebAPI POST controller like the one below:
[ResponseType(typeof(Product))]
public async Task<IHttpActionResult> PostProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
}
To be valid, it expects several values, lets say Name, Price, URL, ManufactureID, StatusID.
However, the POST will not always contain a value for StatusID for example, and therefore the above will fail, as i cannot be null.
But when the value is not sent by the POST, i want to 'intercept' and set the value in code. Let say to int 1.
How would i go about this?
I have been using DTOes for extraxting data from the API, in a nice and viewable way. Can DToes be used in POST also? If so, how? Or any other approach, to setting data, if it does not excist in the POST?
I would say create your Product request model which will be defined in your WebAPI models and there your can define your StatusID as a nullable. After your receive request you can map your Product request data to ProductDto and in that mapping you set your default values if you need them.
Altough you can intercept request on client side and update it but I'm not sure is that something that will work for you.
You should create a POST product class that is agnostic of the persistence. Don't use the generated Product class of your ORM. Using your example above, you should have a ProductModel class that will only contain the properties that the API client can update. Then do the mapping of the DTO to your product data model.
public async Task<IHttpActionResult> PostProduct(ProductModel model)
{
...
var product = db.Products.New();
//mapping here
product.Name = model.Name;
product.Price = model.Price;
}

pass the post variable to another method

i have code like this.
#RequestMapping(value="/persons",method=RequestMethod.POST)
public #ResponseBody String addUser(#RequestParam String name){
returnText=name;
//List<Person> personList = personService.getAllzonedetails(returnText);
System.out.println(returnText);
//model.addAttribute("personsajax", personList);
return **returnText**;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String getPersons(Model model) {
newvariable = returnText;
System.out.println(newvariable);
logger.debug("Received request to show all persons");
// Retrieve all persons by delegating the call to PersonService
List<Person> persons = personService.getAll();
List<Person> persons1 = personService.getAllzonedetails(newvariable);
// Attach persons to the Model
model.addAttribute("persons", persons);
model.addAttribute("personsajax", persons1);
// This will resolve to /WEB-INF/jsp/personspage.jsp
return "personspage";
}
i want to get the returnText post value in System.out.println(newvariable); in get method to pass the jsp page.
any other way to pass the post value in jsp.
Thanks...
I think what you are trying to do is when the user is added in the post method then you want to redirect to the GET method and on the persons list page you want to show the new added user's name.
What you have tried here is not proper. First of all you need to change the #ResponseBody annotation from the POST method and simple return the "redirect:/persons" string from that function. That will redirect to your GET method. Now to use the newly added user name in the GET method you need to use RedirectAttributes to return the name to the GET method.
For that in your post method signature add one more parameter, RedirectAttributes redirectAttributes. Then insert below line just before your return statement.
redirectAttributes.addFlashAttribute("newUserName", returnText);
Then you can access the value in your JSP using EL ${newUserName}.
I hope this will help you.

How to change the display name of a model in Spring MVC

I am working with a Spring MVC project and I can't figure out how to change the String representation of a Model in the Views.
I have a Customer model that has a ONE_TO_MANY relationship with a WorkOrder model. On the workorders/show.jspx the Customer is displayed as a String that is the first and last name, email address, and phone number concatenated.
How do I change this? I thought I could just change the toString method on the Customer, but that didn't work.
One solution would be to change/push-in show() to WorkOrderController to map a rendered-view-tag to what you would like to see.
#RequestMapping(value = "/{id}", produces = "text/html")
public String show(
#PathVariable("id") Long id,
Model uiModel)
{
final WorkOrder workOrder = WorkOrder.findWorkOrder(id);
uiModel.addAttribute("workOrder", workOrder);
uiModel.addAttribute("itemId", id);
// Everything but this next line is just ripped out from the aspectJ/roo stuff.
// Write a method that returns a formatted string for the customer name,
// and a customer accessor for WorkOrder.
uiModel.addAttribute("customerDisplay", workOrder.getCustomer().getDisplayName());
return "workorders/show";
}
Put/define a label in your i18n/application.properties file for customerDisplay.
Then in your show.jspx, you can access the mapping with something like... (The trick is similar for other views.)
<field:display field="customerDisplay" id="s_your_package_path_model_WorkOrder_customerDisplay" object="${workorder}" z="user-managed" />
I'm new to Roo, so I'd love to see a better answer.
We found a good solution. There are toString() methods for all the models in ApplicationConversionServiceFactoryBean_Roo_ConversionService.aj
You can just push the method for the Model you want into ApplicationConversionServiceFactoryBean.java and modify it. In my case I added this:
public Converter<Customer, String> getCustomerToStringConverter() {
return new org.springframework.core.convert.converter.Converter<com.eg.egmedia.bizapp.model.Customer, java.lang.String>() {
public String convert(Customer customer) {
return new StringBuilder().append(customer.getId()).append(' ').append(customer.getFirstName()).append(' ').append(customer.getLastName()).toString();
}
};
}
Spring uses this for all the view pages so this will change the String representation of your model across your whole app!

Resources