RestController in Spring boot- 404 ERROR instead of JSON object [duplicate] - java

This question already has answers here:
Spring Boot #autowired does not work, classes in different package
(13 answers)
Closed 4 years ago.
I have a very simple Rest Controller only for test and its not working..
I'm using spring boot and postman for client-side.
my rest controller:
#RestController
#RequestMapping("system")
public class LoginController {
public static CouponSystemResponse csRes = new CouponSystemResponse();
#RequestMapping(value = "login", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public CouponSystemResponse login(#RequestParam(value = "username") String username,
#RequestParam(value = "password") String password, #RequestParam(value = "type") String type) {
csRes.setMessage("You have successfully logged in");
csRes.setStatus("OK");
return csRes;
CouponSystemResponse:
#Component
public class CouponSystemResponse {
private String status = "";
private String message = "";
public CouponSystemResponse() {
}
public CouponSystemResponse(String status, String message) {
super();
this.status = status;
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#Override
public String toString() {
return "CouponSystemResponse [status=" + status + ", message=" + message + "]";
}
postman output:
postman output
url: http://localhost:8080/system/login?username=admin&password=1234&type=ADMIN
Can't figure what the problem could be. Appreciate any help.
Update: I add picture of main app+structure:
main app

All your components are in subpackages of package com.orel.couponsystem, but your #SpringBootApplication annotated CouponWebApplication class is in package com.orel.t.couponsystem.config, which means that none of your components are auto-scanned.
Standard solution: Move class CouponWebApplication out to the base package:
package com.orel.couponsystem;
Alternate solution: Explicitly name the base package:
#SpringBootApplication(scanBasePackages = "com.orel.couponsystem")

Related

POST request from Angular to SpringBoot API not sending parameters

I have this code, where I send an object to the API:
validateLogin(user:User):Observable<string>{
console.log(JSON.stringify(user));
return this.http.post<string>(`http://localhost:8080/login/login`, user).pipe(
map((resp)=>{
return this.repareString(JSON.stringify(resp));
})
)
}
I don't see anything wrong, but Spring Boot says "required request parameter 'user' for method parameter type String is not present". I've also tried sending it as a JSON object but it says the same. I believe that this is caused by the code in angular, that's why I post it here.
#RestController
#RequestMapping("/login")
public class LoginController {
#PostMapping("/login")
public static String login(#RequestParam String user) throws Exception{
System.out.println(user);
Login l = new ObjectMapper().readValue(user, Login.class);
if(l.checkUser().equals("ok")){
if(l.checkPassword().equals("ok")){
return "logged";
} else {
return l.checkPassword();
}
}
return l.checkUser();
}
}
And the Login class:
public class Login extends Database{
public String email;
public String pass;
public Statement stm;
public Login(String email, String pass) throws Exception{
this.email = email;
this.pass = pass;
this.stm = (Statement) this.con.createStatement();
}
I have tried sending it as a JSON string and I've also tried sending the object properties individually as various params.
Change your controller like this:
#RestController
#RequestMapping("/login")
public class LoginController {
#PostMapping("/login")
public static String login(#RequestBody Login login) throws Exception{
System.out.println(login);
if(login.checkUser().equals("ok")){
if(login.checkPassword().equals("ok")){
return "logged";
} else {
return login.checkPassword();
}
}
return login.checkUser();
}
}

How to Use DI to get a final variable as #PostMapping's path

I have a final class Constants, which holds some final data.
#Component
public final class Constants {
public final String TOKEN;
public final String HOST;
public final String TELEGRAM;
public Constants(#Value("${myapp.bot-token}") String token,
#Value("${myapp.host}") String host) {
this.TOKEN = token;
this.HOST = host;
this.TELEGRAM = "https://api.telegram.org/bot" + TOKEN;
}
}
The problem is that, when I want to use a variable as #PostMapping path, I faced this error:
Attribute value must be constant
#RestController
#RequestMapping
public class Controller {
private final Constants constants;
#Autowired
public Controller(Constants constants) {
this.constants = constants;
}
#PostMapping(constants.TOKEN)// Problem is here
public ResponseEntity<?> getMessage(#RequestBody String payload) {
return new ResponseEntity<HttpStatus>(HttpStatus.OK);
}
}
I've tried to load TOKEN in my controller class but faced the same issue.
#RestController
#RequestMapping
public class Controller {
#Value("${myapp.bot-token}") String token
private String token;
#PostMapping(token)// Problem is here
public ResponseEntity<?> getMessage(#RequestBody String payload) {
return new ResponseEntity<HttpStatus>(HttpStatus.OK);
}
}
When I do something like this the problem will gone. But I don't want to declare my token in source-code.
#RestController
#RequestMapping
public class Controller {
private final String TOKEN = "SOME-TOKEN";
#PostMapping(TOKEN)// No problem
public ResponseEntity<?> getMessage(#RequestBody String payload) {
return new ResponseEntity<HttpStatus>(HttpStatus.OK);
}
}
Can anyone please give me a solution to this?
Try to paste string with property path inside #PostMapping annotation. Like this
#GetMapping(value = "${app.path}")
public String hello() {
return "hello";
}
You can only use a constant (i.e. a final static variable) as the parameter for an annotation.
Example:
#Component
class Constants {
public final static String FACEBOOK = "facebook";
}
#RestController
class Controller {
#PostMapping(Constants.FACEBOOK)
public ResponseEntity<ResponseBody> getMessage(#RequestBody String payload) {
return new ResponseEntity<>(HttpStatus.OK);
}
}
You must use builder pattern(use Lombok for ease) and freeze the value that you are getting from the properties and then use that in your program.

Required, request body is missing: public when I try loading Swagger

I am trying to access the swagger URL from my Spring-Boot application using the post request. But getting a 400-Bad request and it says the request body is missing. But the same request works fine in Postman.
Controller:
#RestController
public class IdVController {
#Autowired
private IdService idService;
#Autowired
protected FileUtility util;
/** The Constant STATUS. */
private static final String STATUS = "status";
/** The Constant SUCCESS. */
private static final String SUCCESS = "success";
/** The Constant SYSTEM. */
private static final String SYSTEM = "SYSTEM";
#RequestMapping(value ="/idApi")
public ResponseEntity<MarketPlaceResponse>
validateIdData(#RequestBody VerifyIdDTO verifyIdDTO) throws Exception {
JSONObject rawResponse = idService.validateId(verifyIdDTO);
IdVerifyEntity DTOResponse = (IdVerifyEntity)util.convertToEntity(rawResponse.toString(), IdVerifyEntity.class);
if (rawResponse.get(STATUS).equals(SUCCESS)) {
DTOResponse.setCreated_by(SYSTEM);
DTOResponse.setCreated_date(new
java.sql.Date(System.currentTimeMillis()).toString());
}
//return ResponseBuilder.buildResponse(DTOResponse);
MarketPlaceResponse response = new MarketPlaceResponse();
response.setResponse(DTOResponse);
return new ResponseEntity<MarketPlaceResponse>(response,HttpStatus.OK);
}
}
Request DTO:
public class VerifyIdDTO {
#NotBlank(message="Owner ID should not be empty")
private String id;
private String citizenship;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
}
I am contacting an external service by building URL and using GET from this POST method
this is the swagger URL
localhost:8080/idvalidationservice/swagger-ui.html
You can see the error message in this screenshot.

Spring MVC- REST POST - Bad Request 400

I am trying to post a request to my service, but it's not working. I am getting 400 Bad Request. I have GET requests that are working perfectly in the same controller.
Here is the method:
#RequestMapping(value = "/assign", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public Form5398Obj arriveTrip(#PathVariable String siteId,
#RequestBody ErrorMsg anError) throws Exception {
System.out.println(anError.toString());
}
The ErrorMessage java class is as follows:
public class ErrorMsg {
private String code;
private String msg;
private String request;
public ErrorMsg(String code, String msg, String request)
{
this.code = code;
this.msg = msg;
this.request = request;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
}
I did not configure anything else. What else do I need to do to get it to work? I am using JavaConfig, do I need to add any bean declarations?
I am sending:
with Content-Type: application/json
{
"code" : "101",
"msg" : "Hello Test",
"request" : "1"
}
I believe you need a no-argument constructor for ErrorMsg so that Jackson can instantiate an object to populate for the incoming request. Otherwise it would not know how the parameters in your 3 parameter constructor should be populated.
Try adding the following
public ErrorMsg() {
}

Bean Validation and requested parameter in spring mvc

Is it possible to use validators for validation request parameters from javax.validation.constraints package in any way? I.e. like the following:
#Controller
public class test {
#RequestMapping("/test.htm")
public String test(#RequestParam("name") #NotNull String name)
{
return "index";
}
}
Use this way:
public class Comment{
#NotEmpty
#Length(max = 140)
private String text;
//Methods are omitted.
}
Now use #Valid in controller
#Controller
public class CommentController {
#RequestMapping(value = "/api/comment", method = RequestMethod.POST)
#ResponseBody
public Comment add(#Valid #RequestBody Comment comment) {
return comment;
}
}
When you are applying #Valid for Comment object in your cotroller,it will apply the validation mentioned in Comment class and its attribute like
#NotEmpty
#Length(max = 140)
private String text;
You can also check this out for little alternate way of doing:
http://techblogs4u.blogspot.in/2012/09/method-parameter-validation-in-spring-3.html
you can try this
#Controller
public class test {
#RequestMapping("/test.htm")
public String test(#RequestParam(value="name",required=true) String name)
{
return "index";
}
}

Categories