Redirect to another controller with a #PathVariable - java

How do I redirect to another controller with a path variable in the redirect.
I tried it the following way but get this error:
java.lang.IllegalArgumentException: Model has no value for key 'formId'
How I implemented it:
Long formId = drugType.getFormId();
view = "redirect:/pub/req/customForm/view/{formId}";
And received by the controller:
#RequestMapping(method = RequestMethod.POST, value = "/pub/req/customForm/view/{formId}")
String completeCustomForm(#PathVariable Long formId,
#Valid #ModelAttribute CustomFormLayout customFormLayout,
BindingResult errors, HttpServletRequest request, Model model,
RedirectAttributes attr) {
Any ideas how I can redirect to this controller with the formId value?

Try applying the parameter:
Long formId = drugType.getFormId();
view = "redirect:/pub/req/customForm/view/"+formId;

You could either build the redirect address string:
return "redirect:/pub/req/customForm/view/" + drugType.getFormId();
Or add a model attribute named as your path variable ("formId") and use it in your view name (this is what the error message is telling you)
model.addAttribute("formId", drugType.getFormId());
return "redirect:/pub/req/customForm/view/{formId}";

Related

Spring Controller mapping using regex

I am getting a following GET request
http://localhost:8080/flamingo-json/en/web/Mobile/our-program/Tiers-recognition-Redesigned/rewards-program-new.html
For the above url I have defined the following Mapping in spring rest controller
#GetMapping(value = "/flamingo-json/{language}/{platform}/{page:.+}")
#ResponseBody
public String getAboutUs(#PathVariable(value = "language", required = false) String language,#PathVariable String platform,
#PathVariable String page){
logger.info("Serving " + page + " page for the request");
return aboutUsService.getPageFromDb(page, language, platform);
but I am unable to get "Mobile/our-program/Tiers-recognition-Redesigned/rewards-program-new.html" value in the Path variable 'page' and I am getting 404.
if you want to jump to other page, delete the annotation #ResponseBody;if you want to get the value(like json) from this request,change the annotation to #PostMapping. hope the ans works.

How to set a multipartfile parameter as "not required" in java with spring boot?

my problem is that I have a controller developed in Java with Spring Boot in which I edit "Portfolio" entities. Here I get the different attributes to edit this entity and also an image. My idea is that if I receive the empty parameters, it will reassign to the entity the values it had before and only modify the attributes that were sent in the form with some value.
This works correctly when I test in Postman, but when I send the image attribute as "undefined" or as "null" from the form in angular, my controller in the back end shows me an error that says: Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
My idea is to make the "file" attribute which is a MultipartFile can be empty and have no problems.
My controller is as follows:
#PutMapping("/portfolio/edit-data")
public Portfolio editPortfolio (#RequestParam("image")MultipartFile image,
#ModelAttribute("port") Portfolio port,
BindingResult result){
Portfolio portOriginal = portServ.buscarPortfolio(Long.valueOf(1));
if(!image.isEmpty()){
String rutaAbsoluta = "C:\\Users\\Paul";
try{
byte[] bytesImg = image.getBytes();
Path fullPath = Paths.get(absolutePath + "//" + image.getOriginalFilename());
Files.write(fullPath, bytesImg);
port.setImage(image.getOriginalFilename());
}catch (IOException e){
}
}else{
port.setImage(portOriginal.getImagen());
}
if("".equals(port.getName())){
port.setName(portOriginal.getName());
}
if("".equals(port.getTitle())){
port.setTitle(portOriginal.getTitle());
}
if("".equals(port.getIntroduction())){
port.setIntroduction(portOriginal.getIntroduction());
}
if("".equals(port.getFooter())){
port.setFooter(portOriginal.getFooter());
}
return portServ.editarPortfolio(port, Long.valueOf(1));
}
The following query is correct in Postman. So it would be useful to be able to submit an empty file in a form from angular.
Postman request
Try #RequestParam(required = false) (no need for the name to be specified with the value param, because spring takes the variable name by default and in your case they're the same)
You're method definition would look like this:
#PutMapping("/portfolio/edit-data")
public Portfolio editPortfolio (#RequestParam(required = false) MultipartFile image,
#ModelAttribute Portfolio port,
BindingResult result)

Spring mvc - send xml text string to controller

I'm working on a java spring mvc application. I need to send an xml string to my controller, and get this xml as a simple text string inside controller. But can not find any solution yet. I tried this way:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(String post, HttpServletRequest request, HttpServletResponse response){
System.out.println("post: " + post);
}
and I have contentType: 'text/xml' in my ajax config. But the variable post always printed as null.
Also I tried consumes = MediaType.APPLICATION_XML_VALUE and consumes = MediaType.TEXT_XML_VALUE in my method, but returns me HTTP Status 415 – Unsupported Media Type. What is the problem? How can I send simple xml text to my controller?
You can read your string using RequestParam:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(
#RequestParam(value="post") String post, Model model){
...
}

How to pass the model attribute object values one controller to another controller by rediect url

Using the redirectAttributes.addFlashAttribute("object",objectvalue);
Like this way it is successfully redirecting the object value to the next controller, but when we returned the view in the next controller it display the result in html page in browser. Then the problem starts when we refresh or reload the page then values disappears.
My code is
#RequestMapping(value = "/addRoom", method = RequestMethod.POST)
public String saveRoom(Room room,
ModelMap model, RedirectAttributes ra) {
amenitiesService.saveRoom(room);
Floor floor = amenitiesService.getFloorInfo(room.getFloorId());
String floorName = floor.getFloorName();
ra.addFlashAttribute(room);
ra.addFlashAttribute("floorName", floorName);
ra.addFlashAttribute("message","Room information is saved successfully.");
return "redirect:/redirectedUrl";
}
#RequestMapping(value = "/redirectedUrl")
public String redirecturl(Room room, ModelMap model) {
return ADMIN_VIEW + SAVE_ROOM;
}
please any one suggest me how to redirect the object values to next controller with permanent not temporary visible like flash attributes
use this it may be work
#RequestMapping(value = "/redirectedUrl")
public String redirecturl(Room room, ModelMap model, RedirectAttributes re) {
String name=(String)re.getFlashAttributes("floorName");
return ADMIN_VIEW + SAVE_ROOM;
}

How to pass errors in Spring Controller/Model to a view file

How do I pass errors to a view file from a Controller implemented using Spring MVC? These errors are not form errors. Just business logic errors that will be shown inside a div in the "JSP" view.
Here is the controller action I have:
#RequestMapping(method = RequestMethod.POST)
public String processLoginForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, #SuppressWarnings("rawtypes") Map model)
{
loginForm = (LoginForm) model.get("loginForm");
String gotoURL = request.getParameter("gotoURL");
if (gotoURL == null || gotoURL == "")
{
String errorMessage = "No Redirect URL Specified";
return "loginerror";//loginerror is the view file I want to pass my error to.
}
model.put("loginForm", loginForm);
return "loginsuccess";
}
Thanks,
Change your method signature :
public String processLoginForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, ModelMap model)
You can put the error message in the ModelMap and forward it to the loginerror page.
if (gotoURL == null || "".equals(gotoURL))
{
final String errorMessage = "No Redirect URL Specified";
modelMap.addAttribute("errorMessage ", errorMessage);
return "loginerror";//loginerror is the view file I want to pass my error to.
}
You can fetch that in the div using EL.
<div>${errorMessage}</div>
Your method is
public String processLoginForm(HttpServletRequest request, LoginForm
loginForm, BindingResult result, #SuppressWarnings("rawtypes") Map
model)
The method #The New Idiot explained is
public String processLoginForm(HttpServletRequest request, LoginForm
loginForm,
BindingResult result, ModelMap model)
See that the Map model is replaced with ModelMap model
If you use this method, then you can use model.addAttribute to add error messages
You can use Spring support for exception handling..
HandlerExceptionResolver or #ExceptionHandler
#adarshr
Link
Hope it will be of some use.

Categories