Spring boot controller fails to hit error 404 - java

I am building this Spring Boot application with Hibernate and MySQL. I know this is pretty basic and the same question is asked multiple times but I can't figure out why my controller isn't hitting and gives 404 error. As I see, the problem is with ComponentScan where my #SpringBootApplication and #RestController reside within one package while my #Repository and #Entity lie in another package.
When I include the package as #ComponentScan(basePackages = "com.sample.user"), the project builds and runs successfully but does not hit the GET method getUser() and no console output of an error as well. The GET method hits only when I omit the
#Autowired private UserRepository userRepository; from the controller class along with #ComponentScan in application class.
Controller
package com.sample.rest.controller;
import com.sample.user.entity.User;
import com.sample.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping ("user")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping("/")
public User getUser() {
User user = new User();
user.setFirstName("Lady");
user.setLastName("Gaga");
user.setEmail("l.gaga#ymail.com");
userRepository.save(user);
return user;
}
}
Application
package com.sample.rest;
import com.sample.rest.controller.UserController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = "com.sample.user")
public class RestServicesApplication {
public static void main(String[] args) {
SpringApplication.run(RestServicesApplication.class, args);
}
}
Repository Interface
package com.sample.user.repository;
import com.sample.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
#EnableJpaRepositories
#Repository
public interface UserRepository extends JpaRepository<User, Long> {}
Entity
package com.sample.user.entity;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
#Entity
#Table(name = "user")
#EntityListeners(AuditingEntityListener.class)
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "last_name", nullable = false)
private String lastName;
#Column(name = "email_address", nullable = false)
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Browser Page
https://ibb.co/KDsqLn3

With #ComponentScan(basePackages = "com.sample.user") you are overwriting the default behavior.
So either remove this and put the packages below the package where you have #SpringBootApplication or add all packages to #ComponentScan.
I recommend not to use the default Spring Boot behavior.
So remove ComponentScan an move RestServicesApplication to the com.sample package

Use this it will resolve your Issue.
#ComponentScan(basePackages = "com.sample")
or use multiple package sacn somthing like
#ComponentScan({ "com.sample", "com.sample.user" })

Related

User is in database, but it still lets him register unlimited amount of times

While there is user in the database, another user with exactly the same credentials is "successfully" inserted in the database...
Hello! I'm building my own ecommerce app and I included spring security. Now, while I was developing security part of the app, I tried it to see if it's working and once I entered desired info in the request body, for the first request the user was successfully inserted in the database, but when I tried to do it the second time, to check if the userExists which throws and error that user is already registered, works, it just added another user with the same credentials (name, lastname, mail and so). I go to userRepository to check if there is already the user with the same email, it makes sense what i wrote, but it doesnt work...Please help...Here are all the files:
EDIT : Mistakenly copied UserRegistrationController twice...So here is the userService.java:
package com.marin.thrift.service;
import com.marin.thrift.dao.UserRepository;
import com.marin.thrift.entity.User;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
#Service
#AllArgsConstructor
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final static String USER_NOT_FOUND = "user with email %s not found";
private final BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByUsername(email).orElseThrow(()-> new UsernameNotFoundException(String.format(USER_NOT_FOUND, email)));
}
public String singUpUser(User user){
boolean userExists = userRepository.findByUsername(user.getEmail()).isPresent();
if(userExists){
return "user already in place";
}
String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepository.save(user);
return "it works";
}
}
package com.marin.thrift.registration;
import lombok.AllArgsConstructor;
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;
#RestController
#RequestMapping(path = "api/v1/registration")
#AllArgsConstructor
public class UserRegistrationController {
private RegistrationService registrationService;
#PostMapping
public String register(#RequestBody registrationRequest request){
return registrationService.register(request);
}
}
package com.marin.thrift.registration;
import lombok.AllArgsConstructor;
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;
#RestController
#RequestMapping(path = "api/v1/registration")
#AllArgsConstructor
public class UserRegistrationController {
private RegistrationService registrationService;
#PostMapping
public String register(#RequestBody registrationRequest request){
return registrationService.register(request);
}
}
package com.marin.thrift.registration;
import com.marin.thrift.entity.Role;
import com.marin.thrift.entity.User;
import com.marin.thrift.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
#Service
#AllArgsConstructor
public class RegistrationService {
private final EmailValidator emailValidator;
private final UserService userService;
public String register(registrationRequest request) {
Boolean isValidEmail = emailValidator.test(request.getEmail());
if (!isValidEmail){
throw new IllegalStateException("Email is not valid");
}
return userService.singUpUser(new User(request.getFirstName(), request.getLastName(),
request.getPassword(), request.getEmail(), Role.USER));
}
}
package com.marin.thrift.entity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Date;
#Entity
#Data
#Table(name = "users")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "date_of_birth")
private Date dateOfBirth;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
private Role role;
private Boolean locked = false;
private Boolean enabled = false;
public User(String firstName, String lastName, String password, String email, Role role) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.email = email;
this.role = role;
}
public User() {
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.name());
return null;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername(){
return email;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return !locked;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
}
package com.marin.thrift.security.config;
import com.marin.thrift.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#AllArgsConstructor
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception{
http.csrf()
.disable().authorizeRequests()
.antMatchers("/api/v*/registration/**").permitAll()
.anyRequest().authenticated().and().formLogin();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.authenticationProvider(daoAuthenticationProvider());
}
#Bean
public DaoAuthenticationProvider daoAuthenticationProvider(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(bCryptPasswordEncoder);
provider.setUserDetailsService(userService);
return provider;
}
}
package com.marin.thrift.registration;
import lombok.*;
#Getter
#AllArgsConstructor
#EqualsAndHashCode
#ToString
public class registrationRequest {
private final String firstName;
private final String lastName;
private final String password;
private final String email;
}
Without UserService it's hard to say what is happen. But if I see your jpa mapping I can guess that if you want unique entry per unique user, you have to delete generated column id. And instead you have to put #Id annotation on email. In this case you need also make changes in sql table.
Or as alternative you can stay by current mapping and simply conduct findByEmail before save entity. And if Optional is not empty - then user is already in database registred.
I just fixed my mistake. The mistake was in the database where I forgot to set email as unique. Once I did that, the code works perfectly.

SpringBoot #Service annotation issue

Hi people I am working on one application .I have created a model but after giving all annotation and configuring all properties it is showing below error. Can anyone please look into below issue?
application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/expenses
spring.datasource.username =dante
spring.datasource.password =jboss
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.format_sql=true
server.port=9191
Main Class
package com.expenses.demo;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.expenses.demo.modal.Role;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.service.UserService;
#SpringBootApplication
public class ExpenseApplication implements CommandLineRunner {
#Autowired
private UserService userService;
public static void main(String[] args) {
SpringApplication.run(ExpenseApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Starting code");
User user = new User();
user.setFirstname("Aniket");
user.setLastname("Turiley");
user.setEmail("abc#gmail.com");
user.setPassword("abc");
user.setPhone("99220289");
Role role1=new Role();
role1.setRoleId(44L);
role1.setRoleName("ADMIN");
Set<UserRole> userRoleSet = new HashSet<>();
UserRole userRole = new UserRole();
userRole.setRole(role1);
userRole.setUser(user);
userRoleSet.add(userRole);
User user1= this.userService.createUser(user,userRoleSet);
System.out.println(user1.getUsername());
}
}
Model Class
Role.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="roleinformation")
public class Role {
#Id
private long roleId;
private String roleName;
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "role")
private Set<UserRole> userRoles = new HashSet<>();
public Role() {
}
public Role(int roleId, String roleName) {
this.roleId = roleId;
this.roleName = roleName;
}
public long getRoleId() {
return roleId;
}
public void setRoleId(long l) {
this.roleId = l;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
User.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="usersinfo")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private String username;
private String password;
private String email;
private String phone;
private boolean enable=true;
// user has many roles
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "user")
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
public User() {
}
public User(Long id, String firstname, String lastname, String username, String password, String email,
String phone, boolean enable) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.enable = enable;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
Repository Interfaces
RoleRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.Role;
public interface RoleRepository extends JpaRepository<Role, Long>{
}
UserRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.User;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByUsername(String username);
}
Service Class
Service.java
package com.expenses.service;
import java.util.Set;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
public interface UserService {
//creating user
public User createUser(User user,Set<UserRole> userRoles) throws Exception;
}
Service Implementation class
ServiceImplementation.java
package com.expenses.service;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.repository.RoleRepository;
import com.expenses.repository.UserRepository;
import com.expenses.service.UserService;
#Service
public class UserServiceImplementation implements UserService{
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
User local= this.userRepository.findByUsername(user.getUsername());
if(local!=null) {
System.out.println("User Already Exist");
throw new Exception("User Already Exist");
}else {
// user create
for(UserRole ur:userRoles) {
roleRepository.save(ur.getRole());
}
user.getUserRoles().addAll(userRoles);
local = this.userRepository.save(user);
}
return local;
}
}
ERROR
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2021-07-28 18:16:59.304[0;39m [31mERROR[0;39m [35m8492[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.b.d.LoggingFailureAnalysisReporter [0;39m [2m:[0;39m
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userService in com.expenses.demo.ExpenseApplication required a bean of type 'com.expenses.service.UserService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.expenses.service.UserService' in your configuration.
Spring Boot will do the component scan (search for Classes with #Service, #Repository, #Controller, #Component) annotation only classes that are located in the same package as the main class (#SpringBootApplication annoteted class), and its subpackages.
So you need eighter to
move ExpenseApplication one package up, to com.expenses,
move all classes that needs to be found by the component scan to to com.expenses.demo or a subpackage, or
configure the component scan (and Spring Data too), for example, by #SpringBootApplication(scanBasePackages = "com.expenses")
BTW: Najeeb Arif is right too, in addition you need to add #Autowired to UserServiceImplementation.userRepository but I think you do not need to add the #Repository annotation to the Spring-Data-JPA repository interfaces.
Add this to your main class
#SpringBootApplication(scanBasePackages = "com.expenses")
This will help the component scan will find your classes.
First mark both of your Repositories with
#Repository
In your user service, you are missing the Autowired annotation.
I personally like the constructor injection.
Role Repository
#Repository
public interface RoleRepository extends JpaRepository<Role, Long>{
}
Same for the user repo.
in your User Service Impl
#Service
public class UserServiceImplementation implements UserService{
private final UserRepository userRepository;
private final RoleRepository roleRepository;
/* when using constructor injection #Autowired is not required */
public UserServiceImplementation(UserRepository userRepository, RoleRepository roleRepository){
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
//...
}
}

Jpa Repository instance is null in service layer

So i want to save the data with the help of JPA repository but when i autowired it is giving me null.
I don't know what else to do in here I have also tried with #EnableJPARepository annotation still no help. So here are the classes i am using. I want to save the data that is published by kafka so is it best to create a seperate function or can i put save to db function in consume json?
Repository
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import org.springframework.data.repository.CrudRepository;
public interface KafkaRepository extends CrudRepository<KafkaEntity,Long> {
}
KafkaEntityClass
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import javax.persistence.*;
#Entity
#Table(name = "messages")
public class KafkaEntity {
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private String userName;
#Column(nullable = false)
private String userMessage;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
ServiceClass
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import com.prateek.addaKafka.addaKafka.model.UserPublishModel;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
#Service
public class KafkaListenerService {
#Autowired
KafkaRepository kafkaRepository;
#KafkaListener(topics = "NewTopic",groupId = "group_json",
containerFactory = "userKafkaListenerFactory")
public UserPublishModel consumeJson(UserPublishModel userPublishModel) {
return userPublishModel;
}
public void saveToDB(UserPublishModel userPublishModel){
ModelMapper modelMapper=new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
KafkaEntity kafkaEntity=modelMapper.map(userPublishModel, KafkaEntity.class);
kafkaRepository.save(kafkaEntity);
}
}
MainClass
package com.prateek.addaKafka.addaKafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
public class AddaKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(AddaKafkaApplication.class, args);
}
}

REST API is always throwing 404 error in Spring boot maven multimodule project with H2 database

I am new to Spring boot and I have created a multi-module project(maven) with spring boot. And I created some REST APIs and connected to H2 database.
The database is connected successfully and able to run in localhost.
This is my project tree.. User-Management is parent and core, serverAPI are child modules. And I have created packages for each module and added the relevant classes.
I have tried everything I know and searched google for like 5 days but nothing worked for me. I have included every code I wrote here. Please help me to find what the issue is.
(I am using intellij idea 2020.3 ultimate)
User.java
package com.hms.usermanagement.core.model;
import javax.persistence.*;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "full_name")
private String fullName;
#Column(name = "email")
private String email;
public User() {
}
public User(long id, String fullName, String email) {
this.id = id;
this.fullName = fullName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}}
UserRepository
package com.hms.usermanagement.core.repository;
import com.hms.usermanagement.core.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
Application
package com.hms.usermanagement.serverAPI.application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.run(args);
}}
UserController
package con.hms.usermanagement.serverAPI.controller;
import com.hms.usermanagement.core.model.User;
import com.hms.usermanagement.core.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#RestController
#RequestMapping("/api")
public class UserController {
#Autowired
private UserRepository userRepository;
//Create Users
#PostMapping("/user")
public User createUser( #Validated #RequestBody User user){
return userRepository.save(user);
}
//View all Users
#GetMapping("/users")
public List<User> getAllUsers(){
return userRepository.findAll();
}
//Update Users
#PutMapping("/users/{id}")
public ResponseEntity <User> updateUser(#PathVariable(value = "id") long userId , #RequestBody User userDetails){
Optional<User> user = userRepository.findById(userId);
if(user.isPresent()){
User _user = user.get();
_user.setFullName(userDetails.getFullName());
_user.setEmail(userDetails.getEmail());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
}else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
//Delete Users
#DeleteMapping("/users/{id}")
public ResponseEntity<?> deleteUser(#PathVariable(value = "id") long userId){
userRepository.findById(userId);
userRepository.deleteById(userId);
return ResponseEntity.ok().build();
}
application.properties
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#enable H2 console
spring.h2.console.enabled=true
#custom H2 console
spring.h2.console.path=/h2
schema-h2.sql
CREATE TABLE users (id long PRIMARY KEY AUTO_INCREMENT, full_name VARCHAR(30), email VARCHAR(50));
I have tried using both these 2 urls
Even "id" field is auto generated but I tried to add id also using postman.. But still getting the same error
Your Sprint boot runner class, Application class is under com.hms.usermanagement.serverAPI.application package, so Spring boot will only scan the components under com.hms.usermanagement.serverAPI.application. So your core and web components are not recognized by Spring boot.
To solve the issue try to move Application.java class under com.hms.usermanagement.
Or you can customize the component scan by adding#ComponentScan annotation to Application.java class:
#SpringBootApplication
#ComponentScan(basePackages = "com.hms.usermanagement")
I did a new maven: mvn clean verify of the project and the issue was solved.
Remove #Validated and try #Valid as below
Calling with [LOCALHOST]:[PORT]/api/user
//Create Users
#PostMapping("/user")
public User createUser(#RequestBody #Valid User user){
return userRepository.save(user);
}

Spring Boot MVC mapping

I have problem with my Spring project. I just started with Spring Boot and i try to make ez controller which redirect me to another web.
When i started my application and go to browser on
localhost:8080/person
there is problem with mapping idk why
enter image description here
This is my structure
enter image description here
PersonController
package Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import Model.Person;
public class PersonController {
#RequestMapping("/person")
public String person(Model model)
{
Person p = new Person();
p.setFirstName("John");
p.setLastName("BonJovi");
p.setAge(23);
model.addAttribute("person", p);
return "personview";
}
}
Person Class
package Model;
public class Person {
String firstName;
String lastName;
int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
And "Main"
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Configuration
#EnableAutoConfiguration
#ComponentScan({"demo","controller"})
public class EducationProjectApplication {
public static void main(String[] args) {
SpringApplication.run(EducationProjectApplication.class, args);
}
}
Add a #Controller to the top of your PersonController
Also - just check, your #ComponentScan({"demo","controller"})
"controller" is not capitalized, but your package is declared "Controller"
You must annotated your PersonController class as #RestController.
Like Rafael said you need to put annotations above PersonController class. #RestController if you want to build a REST controller, #Controller if you want to build normal website. Make sure you already configure your view resolver so it will return a jsp files.

Categories