pass the post variable to another method - spring

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.

Related

spring model is sometimes empty

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?

How do I post more than one parameter using spring #requestparam/#requestbody annotation in json format

I want to upload an item object with it's image is it possible that i pass a complete object of my Item along with it's image from my Controller if yes then how may i Do it? and I need a Json Pattern also which will be coming from client side.
What would be the Json pattern for my following Item Object.
Class Item{
String ItemID;
String ItemName;
String CategoryID;
List<Image> imagesList;
}
Class Image{
String imageId;
String imageTitle;
byte[] image;
}
and one more thing. Please tell me how can I pass two parameters in my Controller. e.g. if I want to pass Item object in the Request Body along with an extra parameter say String UserID. HOw may I write the following code.
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public void add(#RequestBody Item myItem, String UserID)
{ ...... }
and please tell me what if I pass in the Request in Json format. What will be it looks like?
{ "Item" : { "ItemID": "1", ......}, "UserID" : "hello"}
will it be like this or what? because i tried it i'm getting the Object and string as Null. I also tried it with #RequestParam but same got NULL while debugging.
Currently i'm dealing with this by this.
Class ItemUserPost{
Item item;
String UserID;
}
I'm storing this object in MongoDB. Will be my whole collection of Item will stored along with the images? or i have to use a MultiPart and GridFS API for this. Kindly please refer if related question already posted.
Please Help Urgent.
Thanks in Advance.
The Request Body it's just ONE body. You cannot pass multiple objects or parameters in the same body.
There is 2 turnovers for this:
If you're using REST, you can put the UserID on #RequestMapping(value = "{userId}") and get it from the URL. Or, you can simply put the UserId as query parameter on your url.
Keep using your ItemUserPost object.
--
And for the second question:
Yes, It will store your collection with the images.

Spring MVC: How to retrieve data apart from the Model submitted to a view

I have the following requirement. I submit a Model object to a view as follows...
#RequestMapping(value ="/addItem", method = RequestMethod.GET)
public ModelAndView showContacts() {
ModelAndView modelAndView = new ModelAndView("addItem", "command", new Item());
return modelAndView;
}
But on post, I need to retrieve a value apart from the "Item" object (model) that is returned to me. I can't have this variable be a part of the Item model object because it does not belong there. But I need it returned in order to act on that value. How can I get about doing this ?
I.e. In my JSP file, I have the following fields...
<form:input type="text" path="val1"/>
<form:input type="text" path="val2"/>
<form:input type="text" path="val3"/>
Out of the above, only fields val1 and val2 have mappings to the Item object, where as val3 does not. Nevertheless, I need the value of val3 passed back to my controller as well. The code I have right now to handle the POST is as follows, but I can't figure out how to get the value for val3. The code does not compile right now because it says that there is no field or appropriate getter method in the Item class for val3.
#RequestMapping(value = "/postItem", method = RequestMethod.POST)
public String postItem(#ModelAttribute("item") Item item , BindingResult result) {
logger.info("Post Item:");
return "home";
}
How can I modify the above code to suite my requirement ?
Some guidance on this matter will be highly appreciated.
You can pass a map as the model, and include all sorts of different things in there. You are not limited to a single domain object, that constructor is there as a convenience, it is not the only way to do it. There is a variation of the constructor:
public ModelAndView(Object view,
Map model)
Create a new ModelAndView given a View object and a model.
Parameters:
view - View object to render (usually a Servlet MVC View object)
model - Map of model names (Strings) to model objects (Objects).
Model entries may not be null, but the model Map may be null if
there is no model data.

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!

Can #RequestParam be used on non GET requests?

Spring documentation says:
Use the #RequestParam annotation to bind request parameters to a
method parameter in your controller.
AFAIK, request parameters are variables retrieved from query strings if the request method is GET. They are also the variables retrieved from the form values when the request method is POST. I've verified this using a simple JSP that displays request parameters through method request.getParameter("key").
But it seems to me that #RequestParam only works on GET method requests. It can only get values from query strings.
Is this a bug in the documentation? Can someone please cite me some documentation that describes exactly what #RequestParam is used for, what it cannot be used for, and how it gets populated?
Can I use #RequestParam for POST methods to get the form values? If I can't use #RequestParam, what else can I use? I'm trying to avoid calling request.getParameter("key").
It works with posts too. Can you post your method body and you html?
Yes it works perfectly with post method too. you can mention the method attribute of #RequestParam as RequestMethod=POST. Here is the code snippet
#RequestMapping(value="/register",method = RequestMethod.POST)
public void doRegister
(
#RequestParam("fname") String firstName,
#RequestParam("lname")String lastName,
#RequestParam("email")String email,
#RequestParam("password")String password
)
Instead of #RequestParam which binds to a single form value, you can use #ModelAttribute annotation and bind to the whole object. But it should be used in conjunction with form or bind Spring's JSTL.
Example:
- controller that calls JSP-page, it should add objects to a Model:
#RequestMapping(value="/uploadForm", method=RequestMethod.GET)
public String showUploadForm(Model model) {
Artist artist = new Artist();
Track track = new Track();
model.addAttribute("artist", artist);
model.addAttribute("track", track);
return "uploadForm";
}
JSP might look something like that:
Track Title *:
Controller that processes form submission;
#RequestMapping(value="/uploadToServer", method=RequestMethod.POST)
public String uploadToServer(#ModelAttribute("artist") Artist artist, #ModelAttribute("track") Track track) { .... }
Here I found a good explanation of using #ModelAttribute annotation - krams915.blogspot.ca

Resources