Why object is not initializing in spring mvc? - spring-mvc

Example: User.java
#Component
public class User{
public String name;
public String email;
public User() {
super();
}
public User(String name, String email) {
super();
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
}
HomeController.java
#Controller
public class HomeController {
#Resource
User user;
#RequestMapping(value="/getUsers", method= RequestMethod.POST)
public #ResponseBody User getUser(User user){
return user;
}
}
But user.getName() and user.getEmail() is null. User class is not initializing. Why? Even though I am sending user object at client side as
POST /spring/getUsers HTTP/1.1 Host: localhost:2015 Cache-Control: no-cache {"name":"vinod", "email":"vinod#gmaol.com" }

Here is a sample code. Please go through the documentation once to understand how requestBody annotation works etc.
#Controller
public class HomeController {
#RequestMapping(value="/getUsers", method= RequestMethod.POST)
public #ResponseBody User getUser(#RequestBody User user){
return user;
}
}

Related

asp core web api http post is null

I created a webapi by looking at the ms basic documentation.
ms Doc
it was work
todoitems
Besides todoitems I
Because I wanted to use it in the form of Avatar Chart
Insert the model Avatarchart, create Avatarchartcontext, and make the controller as a scaffold.
solution view
However, when I tried to receive data as a post, the data always came in null.
error
null
this is code
[Route("api/AvatarCharts")]
[ApiController]
public class AvatarChartsController : ControllerBase
{
private readonly AvatarChartContext _context;
public AvatarChartsController(AvatarChartContext context)
{
_context = context;
}
// GET: api/AvatarCharts
[HttpGet]
public async Task<ActionResult<IEnumerable<AvatarChart>>> GetAvatarCharts()
{
return await _context.AvatarCharts.ToListAsync();
}
// GET: api/AvatarCharts/5
[HttpGet("{modelId}")]
public async Task<ActionResult<AvatarChart>> GetAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
return avatarChart;
}
// PUT: api/AvatarCharts/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{modelId}")]
public async Task<IActionResult> PutAvatarChart(long modelId, AvatarChart avatarChart)
{
if (modelId != avatarChart.modelId)
{
return BadRequest();
}
_context.Entry(avatarChart).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AvatarChartExists(modelId))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/AvatarCharts
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<AvatarChart>> PostAvatarChart( AvatarChart avatarChart)
{
_context.AvatarCharts.Add(avatarChart);
await _context.SaveChangesAsync();
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}
// DELETE: api/AvatarCharts/5
[HttpDelete("{modelId}")]
public async Task<IActionResult> DeleteAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
_context.AvatarCharts.Remove(avatarChart);
await _context.SaveChangesAsync();
return NoContent();
}
private bool AvatarChartExists(long modelId)
{
return _context.AvatarCharts.Any(e => e.modelId == modelId);
}
}
public class AvatarChartContext :DbContext
{
public AvatarChartContext(DbContextOptions<AvatarChartContext> options) : base(options)
{
}
public DbSet<AvatarChart> AvatarCharts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AvatarChart>().HasKey(c => c.modelId);
}
}
public class AvatarChart
{
[Key]
public long modelId;
public string colorCode;
public long dateTime; //ex 20210101130000
public string name;
public string diagnose;
}
swagger
add postgressql dbenter image description here
Update:
You missed the {get; set;}.
public class AvatarChart
{
[Key]
public long modelId {get; set;}
public string colorCode {get; set;}
public long dateTime {get; set;} //ex 20210101130000
public string name {get; set;}
public string diagnose {get; set;}
}
Can you make these changes and tell me what value is being returned on the variable result. Also, can you validate your ModelState first?
[HttpPost]
public async Task<ActionResult> PostAvatarChart( AvatarChart avatarChart)
{
await _context.AvatarCharts.AddAsync(avatarChart);
var result = await _context.SaveChangesAsync() > 0;
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}

Asp.Net webapi : throw new RestException(HttpStatusCode.Unauthorized)

I am a beginner developer and I have an issue in Query handler when using throw new RestException(HttpStatusCode.Unauthorized)
this is my query handler:
namespace Application.User
{
public class Login
{
public class Query : IRequest<AppUser>
{
public string Email { get; set; }
public string Password { get; set; }
}
public class QueryValidator : AbstractValidator<Query>
{
public QueryValidator()
{
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
}
}
public class Handler : IRequestHandler<Query, AppUser>
{
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signUserManager;
public Handler(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
{
_userManager = userManager;
_signUserManager = signInManager;
}
public async Task<AppUser> Handle(Query request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
throw new RestException(HttpStatusCode.Unauthorized);
var result = await _signUserManager.CheckPasswordSignInAsync(user, request.Password, false);
if (result.Succeeded)
{
//TODO : generate token
return user;
}
throw new RestException(HttpStatusCode.Unauthorized);
}
}
}
}

ControlsFX: AutoCompletion bind to a model class

I have a model class:
public class Client {
private long id;
private String name;
#Override
public String toString() {
return this.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and I have a Textfield that I want to use auto complete using a list of Client class, using ControlsFX, here is what I did:
AutoCompletionBinding<Client> binding = TextFields.bindAutoCompletion(searchField, SuggestionProvider.create(appState.clients));
Where appStat.Clients is a list of Client class. For some reason I get no suggestions appearing. What am I doing wrong?

Add Property to ControlsFX PropertySheet

I am creating a PropertySheet and I want to add a Property to the sheet. The problem is, what happens if the value of the property changes, the PropertySheet needs to update to reflect those changes. How would I do this?
import java.util.Map;
import javafx.beans.property.Property;
import org.controlsfx.control.PropertySheet;
public class PropertyItem implements PropertySheet.Item {
private Map<String, Property> map;
private String key;
private String name;
private String description;
PropertyItem(Map<String, Property> map, String key, String name, String description){
this.map = map;
this.key = key;
this.name = name;
this.description = description;
}
#Override
public String getCategory() {
return null;
}
#Override
public String getDescription() {
return description;
}
#Override
public String getName() {
return name;
}
#Override
public Class<?> getType() {
return map.get(key).getValue().getClass();
}
#Override
public Object getValue() {
return map.get(key).getValue();
}
#Override
public void setValue(Object arg0) {
map.get(key).setValue(arg0);
}
}
This is probably too late but anyway...
The property editor uses the following method from PropetySheet.Item interface to listen to value changes.
optional<ObservableValue<? extends Object>> getObservableValue();
You need to implement this method on your PropertyItem class.

Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException

I a trying to send object from client to server. Below is the Controller using spring mvc.
#Controller
public class HomeController {
public class User{
public String name;
public String email;
public User() {
super();
}
public User(String name, String email) {
super();
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
}
#RequestMapping(value="/getUsers", method= RequestMethod.POST)
public #ResponseBody User getUser(User user){
return user;
}}
In client side I am sending object in post like this
http://localhost:2015/spring/getUsers
POST /spring/getUsers HTTP/1.1
Host: localhost:2015
Cache-Control: no-cache
{"name":"vinod", "email":"vinod#gmaol.com" }
But I am getting error at server side like this
HTTP Status 500 - Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.vinod.spring.HomeController$User]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.vinod.spring.HomeController$User.<init>()
Try make the refactoring for your User class to another file, and put a reference of it in your controller using the #Resource annotation. Maybe the exception was throwed because User class is nested.
Example:
User.java
#Component
public class User{
public String name;
public String email;
public User() {
super();
}
public User(String name, String email) {
super();
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
}
HomeController.java
#Controller
public class HomeController {
#Resource
User user;
#RequestMapping(value="/getUsers", method= RequestMethod.POST)
public #ResponseBody User getUser(User user){
return user;
}
}

Resources