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.
Related
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)
I have this rest controller method in springboot
#GetMapping("/cghsHcoSearchText/cityId/{cityId}/hcoName/{hcoName}/treatmentName/{treatmentName}")
public String cghsHcoSearchText(#PathVariable String cityId, #RequestParam(name = "hcoName", required = false) String hcoName,
#RequestParam(name = "treatmentName", required = false) String treatmentName) {
return "Some Text";
}
It has one PathVariable and 2 optional Request parameter.
Now when I hit this url with treatmentName = null i get Whitelabel Error Page
http://localhost:8082/cghs/cghsHcoSearchText/cityId/011?hcoName=Guru?
Any help will be appreciated.
We should not specify request param as a placeholder in URL mapping. Only the path params should be mentioned in placeholder. Sharing a code snippet and corresponding URL which will help out in understanding this
#GetMapping("hello/{id}")
public ResponseEntity<Void> printInfo(#PathVariable("id") String id,
#RequestParam(required = false, name = "name") String name) {
System.out.println(id + " " + name);
return new ResponseEntity<>(HttpStatus.OK);
}
Here id comes as a path param and name as a request param which is not mentioned in mapping annotation.
URL would look like
http://localhost:8080/hello/234?name=pappi
I have a weird situation that may be because I missed something that I didn't realized or know.
I am creating a simple login UI using Angular and call the Web API created in java.
The java web API function is as follows
#RequestMapping(value = "/logon", method = RequestMethod.POST, produces = {"application/json"})
#ResponseBody
public String logon(
#RequestParam(value = "userID", required = true) String userID,
#RequestParam(value = "password", required = true) String password,
HttpServletRequest request)
Now if I use the http.post as follows
login(username: string, password: string) {
return this.http.post(this.url+"/security/logon/",
JSON.stringify({ userID: username, password: password }) )
Then I get the following error in the Google Chrome browser:
POST http://localhost:8080/logon/ 400 (Required String parameter 'userID' is not present)
But if I change the code as follows:
login(username: string, password: string) {
var usrpwd = "userID=" + username + "&password=" + password;
return this.http.post(this.url+"/security/logon?"+usrpwd, usrpwd )
It work perfectly.
Am I missing something? Why the second parameter of http.post that should be the parameter passed not seems to be working?
Thanks in advance for any reply or feedback.
You are defining your endpoint url with two mandatory parameters, and such parameters must be in the url (check here), so when you make a request to your endpoint, the url must be :
http://localhost:8080/logon?userID=yourUserId&password=yourUserPassword
In the first implementation you are not adding the query parameters to the url so the request is made to the url http://localhost:8080/logon/ as it doesn't have the required parameters, your web tier is returning the 400 http code, which implies a bad request (because again, your url doesn't contains the required parameters).
constructor(private http:HttpClient){
}
login(usrName,usrPwd){
let body = {userName:usrName, userPwd:usrPwd};
this.http.post("http://localhost:5000/security/login", body)
.subscribe(
res => console.log(res),
error => console.log(error)
)
}
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}";
I am trying to get my controller to forward a POST request to another controller with some parameters:
#RequestMapping(method=RequestMethod.POST)
public String processSubmit(#Valid Voter voter, BindingResult result,
//...
request.setAttribute("firstName", voter.getFirstName());
request.setAttribute("lastName", voter.getLastName());
request.setAttribute("ssn", voter.getSsn());
logger.info("VoterID exists, forwarding to /question/prepare");
return "forward:/question/prepare";
The problem that I am facing is that /question/prepare points to a Controller method that handles only HTTP GET requests.
#RequestMapping(value="/prepare", method=RequestMethod.GET)
public String prepareVoterBean(#RequestParam String firstName,
#RequestParam String lastName, #RequestParam String ssn, Model model) {
logger.info("QuestionController got GET REQUEST for " + firstName + lastName + ssn);
VoterBean bean = new VoterBean();
bean.setFirstName(firstName);
bean.setLastName(lastName);
bean.setSsn(ssn);
model.addAttribute("questions",bean);
return "questionPage";
}
Is there a way to forward the request to prepareVoterBean as a HTTP GET request? Thanks.
Is there a way to forward the request to prepareVoterBean as a HTTP
GET request?
Try using redirect: prefix.
return "forward:/question/prepare";
This is not POST. The following link might be useful: "22.5.3 Redirecting to views" section.
#Midnight Blue...
Change return type to return "forward:/prepare";