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();
}
}
Related
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.
hi i have a problem with my project (small blog site) that i can't handle for a while
that's my LoginController
'''
#Controller
#SessionAttributes("currentUser")
public class LoginController {
#Autowired
UserService userService;
#ModelAttribute("currentUser")
public User setUpUserForm() {
return new User();
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public String showLoginPage() {
return "loginsite";
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public String userLogin(#ModelAttribute("currentUser") User user,ModelMap model,#RequestParam String login,#RequestParam String password) {
if(userService.checkUserLoginData(login, password)==true) {
user=userService.getUserByLogin(login);
System.out.println("Logged in user");
System.out.println("ID:"+user.getUserId());
System.out.println("Login:"+user.getLogin());
System.out.println("Password:"+user.getPassword());
System.out.println("Email:"+user.getEmail());
return "welcomesite";
}else {
model.put("message", "Check your login and password ! ");
return "loginsite";
}
}
}
'''
that's my UserController
'''
#Controller
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value="/",method = RequestMethod.GET)
public String posts() {
return "redirect:/posts";
}
#RequestMapping(value="/createaccount",method = RequestMethod.GET)
public String showRegisterPage() {
return "registrationpage";
}
#RequestMapping(value="/createaccount",method = RequestMethod.POST)
public String createAccount(ModelMap model,#RequestParam String login,#RequestParam String password,#RequestParam String email) {
userService.addUser(new User(login,password,email));
return "redirect:/login";
}
#RequestMapping(value="/login/accountsettings",method = RequestMethod.GET)
public String showAccountSettings(#SessionAttribute("currentUser") User user) {
System.out.println("amil"+user.getEmail());
return "userSettings";
}
#RequestMapping(params="update",value="/login/accountsettings",method = RequestMethod.POST)
public String updateAccountSettings(#SessionAttribute("currentUser") User user,#RequestParam String login,#RequestParam String password,#RequestParam String email) {
user=userService.updateUser(new User(login,password,email));
return "redirect:/login";
}
#RequestMapping(params="delete",value="/login/accountsettings",method = RequestMethod.POST)
public String deleteAccount(#RequestParam String login) {
userService.deleteUser(login);
return "redirect:/posts";
}
'''
i would like to pass user data after logging in to next pages for ex /login/accountsettings or even to have user id to add post with his id as a creator of this post. After logging in everythink is okay i have complete user data but when im tring to get them in /login/accountsettings User is empty(full of null values).what am I doing wrong?
output:
enter image description here
or I have a question, is there another better way to transfer user data until logging out?
Thanks for help!
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")
I have a controller class with a few methods one of which is a method that is supposed to take POST requests and create a new Account with the JSON from the body of that POST request.
When I try to use curl to make the POST request I get an error that says
{"timestamp":1493988808871,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Required request body is missing: org.springframework.http.ResponseEntity<?> com.example.AccountRestController.add(java.lang.String,java.lang.String)","path":"/users/add"}
The curl command I'm using
curl -X POST --data '{"userName":"bepis", "password":"xyz"}' -H "Content-Type:application/json" http://localhost:8080/users/add
AccountRestController
#RequestMapping(method = RequestMethod.POST, value = "/add", produces = { MediaType.APPLICATION_JSON_VALUE})
ResponseEntity<?> add(#RequestBody String username, #RequestBody String password) {
Account result = accountRepository.save(new Account (username, password));
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
You cannot use multiple #RequestBody. You need to wrap everything into a class that will be used to match your request body.
The same is answered also here.
There is also a JIRA issue for a feature request which was rejected.
NOTE: if you want to write less, you can use #PostMapping instead of #RequestMapping(method = RequestMethod.POST).
NOTE: #RequestParam and #PathVariable are used to extract data from URI, not from body.
NOTE: the same is valid also for the equivalent [FromBody] attribute from ASP.NET WebAPI.
Complete example:
Bellow I created a working example similar to your case:
Request DTO
public class AccountCreateRequest {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Response DTO
public class AccountCreateResponse {
private String userName;
private String password;
public AccountCreateResponse() {
}
public AccountCreateResponse(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Controller
#RestController
#RequestMapping("/v1/account")
public class AccountController {
#PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseStatus(HttpStatus.CREATED) AccountCreateResponse add(#RequestBody() AccountCreateRequest account) {
AccountCreateResponse response = new AccountCreateResponse(account.getUserName(), account.getPassword());
return response;
}
}
curl request
curl -X POST --data '{"userName":"bepis", "password":"xyz"}' -H "Content-Type:application/json" http://localhost:8080/v1/account
So I changed #Requestbodys to a single #RequestBody like andreim said, it fixed my bad request error but for some reason the account username would always be null when the post request went through.
I messed with a few thing, eventually leading me to swap the order of the Account constructor parameters from
Account(String username, String password)
to
Account(String password, String username)
This worked for some reason and let me make my post request with the proper values. Latter out of curiosity I decided to swap the parameters back to Account(String username, String password)
and the post request still works as intended.
I have no idea what I did to get rid of the null problem but it seams to have worked.
I am building a spring based WebApp including a RESTful method call.
I use RESTeasy and jackson to return the username of the current logged in user
(this information is stored in a session bean called "UserBean")
UserBean:
#Component("userBean")
#Scope("session")
public class UserBean implements Serializable {
#Autowired
private InitApp app;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
OverviewBean is the bean that contains the rest method (including the jackson conversion to json):
#Component("overviewBean")
#Scope("view")
#Path("/repairs")
public class OverviewBean {
#Autowired
private InitApp app;
#Autowired
private UserBean userBean;
private List<Repair> openRepairsClient;
private List<Repair> closedRepairsClient;
#PostConstruct
public void fillRepairs() {
try {
String username = userBean.getUsername();
openRepairsClient = app.repairService.findOpenRepairsByClient((Client) app.userService.getUser(userBean.getUsername()));
closedRepairsClient = app.repairService.findClosedRepairsByClient((Client) app.userService.getUser(userBean.getUsername()));
} catch (UserServiceException ex) {
Logger.getLogger(OverviewBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Getters and setters openRepairsClient/closedRepairsClient
#GET
#Path("/getrepairs")
#Produces("application/json")
public String getOpenRepairsInJson() {
String username = userBean.getUsername();
return "test";
}
}
fillRepairs() is able to use userBean without any errors. For example the "String username = userBean.getUsername();" within the try catch returns the username correctly.
My issue is that when getOpenRepairsInJson gets called it throws a nullPointerException
on "String username = userBean.getUsername();". It seems that my userBean is not "linked"
at the moment of the method call. What am I doing wrong?
Thanks in advance!