PostMapping annotation causes a whitelabel error page in SpringBoot - java

I'm new to Java and react web development and I'm having an issue with my postBody method. After sending a post request, the console prints the data posted from my frontend correctly, but it shows a whitelabel error page that says (type=Not Found, status=404) in localhost:8080/api and (type=Method Not Allowed, status=405) in localhost:8080/api/data. Below is the HelloController code.
package com.java.java.practice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
#RestController
#RequestMapping("/api")
public class HelloController {
//this performes a post and get request
#CrossOrigin(origins = "http://localhost:3000/api")
#PostMapping(value="/n", consumes = MediaType.APPLICATION_JSON_VALUE)
public String postBody(#RequestBody String fullName) {
System.out.println(fullName);
return "Hello " + fullName; //returns response
}
}
Below is the main application
package com.java.java.practice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages="com.java.java.practice")
public class PracticeApplication {
public static void main(String[] args) {
SpringApplication.run(PracticeApplication.class, args);
}
}
The weird thing is, when I replace my HelloController code with the one posted underneath, the whitelabel page goes away and shows text on the screen.
package com.java.java.practice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
#RestController
public class HelloController {
//this performes a post and get request
#CrossOrigin(origins = "http://localhost:3000/api")
#RequestMapping("/api")
public String postBody() {
return "Hello"; //returns response
}
}
Any help would be much appreciated.

I can see a few issues as below,
When you try to call via a web browser it's always calling as HTTP GET. But in your RestController, there is no GET method. It only has a POST method. Try to use Postman or CURL to call post method instead of GET.
Your URL is wrong. Since you appending /n for the PostMapping annotation it should be (http://localhost:3000/api/n)
Only you want fullName as request body try to use PathVariable instead. No point to use RequestBody only for 1 parameter. Sample code as below.
#PostMapping(value="/{fullName}", consumes = MediaType.APPLICATION_JSON_VALUE)
public String postBody(#PathVariable String fullName) {
System.out.println(fullName);
return "Hello " + fullName; //returns response
}

Related

Upload an image with Postman, working on the desktop app but not on the browser

I'm building an app, that including service to upload images to S3 AWS, important to say that the bucket "NOT PUBLIC".
When I'm sending the request through the Postman desktop app, I'm getting 200OK...
BUT, when I'm sending the request through the Postman browser, I'm getting 500 error.
I tried with all the types of "Content-type", and I also tried to unmark the content type, it doesn't work...
Errors:
1)
"message": "Failed to parse multipart servlet request; nested exception is javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json"
(If I unmark the "Content type")
"message": "Content type 'application/octet-stream' not supported"
If I'm inserting "multipart/fromdata"
"message": "Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
Yes, and also tried with the boundary in the content type :)
Here is the code of the controller:
package com.package
import com.package.ImageDTO;
import com.package.model.DeletedImageDTO;
import com.package.service.ImageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Control's endPoints for authentication
*/
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/api")
#RequiredArgsConstructor
#Slf4j
public class ImageController extends ValidationExceptionHandler {
private final ImageService imageService;
#GetMapping("/user/image")
public ResponseEntity<List<ImageDTO>> getUserImages() {
final List<ImagesDTO> allUserImages = imageService.getAllUserImages();
return ResponseEntity.status(HttpStatus.OK).body(allUserImages);
}
#PostMapping(value = "/user/images", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<List<ImageDTO>> saveUserImages(#RequestPart(name = "imageDTOS") ImageDTO[] imageDTOS,
#RequestPart(name = "deletedImageDTOs") DeletedImageDTO[] deletedImageDTOs,
MultipartHttpServletRequest request) throws IOException {
final List<ImageDTO> imageDTOSResponse = imageService.saveUserImages(Arrays.stream(imageDTOS).toList(),
Arrays.stream(deletedImageDTOs).toList(), request);
return ResponseEntity.status(HttpStatus.OK).body(imageDTOSResponse);
}
#DeleteMapping("/user/images/{id}")
public ResponseEntity<Void> deleteUserImage(#PathVariable(name = "id") final Long id) {
imageService.deleteImages(id);
return ResponseEntity.noContent().build();
}
}
The language of the backend is: Java, Spring boot
Everything has been mentioned above.

Angular and Spring boot -> POST Request response 403

I have a problem with Spring boot and Angular. I make a POST request which works on POSTMAN and locally but which gives me a 403 in production on tomcat with apache as reverse proxy. But it's working when I am with the embedded tomcat.
I have to try everything soon.
All the solutions I've seen say to disable CSFR but I have no authentication to access my webservice and therefore no spring-security dependency.
I tried anyway but the problem is still there. And in some cases it required me to log in which I don't want to do
import ch.megahertz.swissqrbillsgeneratorapi.properties.FileStorageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication(scanBasePackages = {"ch.megahertz.swissqrbillsgeneratorapi.*"})
#EnableConfigurationProperties({
FileStorageProperties.class
})
public class SwissQrBillsGeneratorApiApplication extends SpringBootServletInitializer {
static Logger logger = LoggerFactory.getLogger(SwissQrBillsGeneratorApiApplication.class);
public static void main(String[] args) {
logger.info("Run application");
SpringApplication.run(SwissQrBillsGeneratorApiApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SwissQrBillsGeneratorApiApplication.class);
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class WebMvcConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedHeaders("*")
.allowedOrigins("*")
.allowCredentials(false)
.maxAge(-1);
}
}
import ch.megahertz.swissqrbillsgeneratorapi.payload.Invoice;
import ch.megahertz.swissqrbillsgeneratorapi.service.CRMService;
import ch.megahertz.swissqrbillsgeneratorapi.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
//#CrossOrigin(origins = {"https://swissqrbillsgenerator.megahertz.ch/","http://localhost:4200/"})
#Slf4j
#RestController
public class ApiController {
private static final Logger logger = LoggerFactory.getLogger(ApiController.class);
#Autowired
private FileStorageService fileStorageService;
#Autowired
private CRMService crmService;
#GetMapping
public String generateQRBills() {
log.info("Enter in GeT API");
return "Get ok";
}
#PostMapping("/generate")
public ResponseEntity<Resource> uploadFile(#RequestParam("file") MultipartFile file) throws IOException {
System.out.println("Enter in generate API");
logger.info("Enter in generate API");
log.info("Enter in generate POST API");
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
Invoice facture = crmService.getFactureInfo(fileName);
File fileWithQR = fileStorageService.addQrToFile(fileName, facture);
Resource resource = new UrlResource(fileWithQR.toURI());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE,Files.probeContentType(resource.getFile().toPath()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName+ "\"")
.body(resource);
}
}
Do you have any idea?
If Postman is returning the query, then the problem is probably in the Angular front end. I believe I was getting a 403 error when I tried to send a String from my backend, it had to be wrapped in an object and unwrapped by Angular to be a string in Angular.

I keep getting "Error: connect ECONNREFUSED 192.168.0.29:8080 " On postman console while im trying to make a get request on sts4

I have been trying all possible urls but same error keeps showing. please help. thanks in advance
here is my controller
package com.springstad.stad.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.springstad.stad.entitites.Names;
import com.springstad.stad.services.NameService;
#RestController
public class MyController {
#Autowired
private NameService nameservice;
// get employee names
#RequestMapping(path="/Names",method = RequestMethod.GET)
public List<Names> getNames(){
return this.nameservice.getNames();
}
#RequestMapping(path="/names/{nameID}",method = RequestMethod.GET)
public Names getNames(#PathVariable("nameID") String nameID) {
return this.nameservice.getNames(Long.parseLong(nameID));
}
}
what proxy config must i do for the postman to get responses from the code? ive been using localhost:8080/Names as url
Assuming its Spring-Boot app, pls check for servlet: context-path in application.yml (or application.properties). Lets say its value is "app1", then try with following url
localhost:8080/app1/Names

No mapping for GET /me

I have this spring boot app and I'm new to spring boot. I have this controller created but it throws 404 and says No mapping for GET /me in the console. I couldn’t find the issue and I need to get this as soon as possible.
Here's the log: https://pastebin.com/Qf5W6MZU
Any other endpoints in this controller also doesn’t work.
import org.sefglobal.scholarx.exception.BadRequestException;
import org.sefglobal.scholarx.exception.NoContentException;
import org.sefglobal.scholarx.exception.ResourceNotFoundException;
import org.sefglobal.scholarx.exception.UnauthorizedException;
import org.sefglobal.scholarx.model.Mentee;
import org.sefglobal.scholarx.model.Profile;
import org.sefglobal.scholarx.model.Program;
import org.sefglobal.scholarx.service.IntrospectionService;
import org.sefglobal.scholarx.util.EnrolmentState;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/me")
public class AuthUserController {
private final IntrospectionService introspectionService;
public AuthUserController(IntrospectionService introspectionService) {
this.introspectionService = introspectionService;
}
#GetMapping
#ResponseStatus(HttpStatus.OK)
public Profile getLoggedInUser(#CookieValue(value = "profileId", defaultValue = "-1") long profileId)
throws ResourceNotFoundException, UnauthorizedException {
return introspectionService.getLoggedInUser(profileId);
}
#GetMapping("/programs/mentee")
#ResponseStatus(HttpStatus.OK)
public List<Program> getMenteeingPrograms(#CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, NoContentException {
return introspectionService.getMenteeingPrograms(profileId);
}
#PutMapping("/mentor/{id}/confirmation")
#ResponseStatus(HttpStatus.OK)
public Mentee confirmMentor(#PathVariable long id,
#CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, BadRequestException {
return introspectionService.confirmMentor(id, profileId);
}
}
I found the issue I haven’t included the package.

Rest web sercive path Not Found

Try to hit my web service through rest client http://localhost:8080/gurukul/userList but it shows error 'Not Found'.
{
"timestamp": 1462078050576
"status": 404
"error": "Not Found"
"message": "No message available"
"path": "/gurukul/userList"
}
below is My controller in which I add path by RequestMapping but still not found the path after spring-boot
package controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import bean.UserList;
import common.Status;
import constants.Constants;
import constants.Messages;
import dao.UserListDAO;
#EnableAutoConfiguration
#Controller
#RestController
#RequestMapping("gurukul")
public class GurukulController {
#RequestMapping(value = "/userList", method = RequestMethod.GET)
#ResponseBody
public Map<String, Object> getUsersList() {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
UserListDAO userListDAO = (UserListDAO) context.getBean("userListDAO");
Map<String, Object> resultMap = new HashMap<>();
List<UserList> listResult = userListDAO.getUsers();
if (listResult != null) {
resultMap.put(Constants.RESULT, listResult);
resultMap.put(Constants.STATUS, Status.SUCCESS);
} else {
resultMap.put(Constants.RESULT, Messages.UNABLE_TO_GET_USERS_LIST);
resultMap.put(Constants.STATUS, Status.FAILURE);
}
return resultMap;
}
}
enter code here
your URL should have been http://localhost:8080/context root/Controller class Path/serivice method path
Use http://localhost:8080/context root path/gurukul/userList

Categories

Resources