No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate - spring

I am getting an error as No qualifying bean of type 'com.springmvc.dao.UserDAO' available: expected at least 1 bean which qualifies as autowire candidate. for the following code, My base class is "com.springmvc"
My Controller Class is
package com.springmvc.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.springmvc.dao.UserDAO;
import com.springmvc.dao.UserDAOImpl;
import com.springmvc.type.User;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
private UserDAO usrdao;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("Date", formattedDate );
return "index";
}
/*
#RequestMapping(value="/login",method = RequestMethod.POST)
public String welcome(Locale locale,Model model,#ModelAttribute("LoginBean")LoginBean login){
if(login != null && login.getUserName() != "" && login.getPassword() != ""){
if(login.getUserName().equals("ajith") && login.getPassword().equals("123")){
model.addAttribute("msg","Welcome "+login.getUserName());
return "welcome";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
else{
model.addAttribute("error","Please Enter Login Details");
return "index";
}
}
*/
#RequestMapping(value="/checkLogin",method = RequestMethod.POST)
public String CheckUser(Model model,#ModelAttribute("User")User user){
if(user != null && user.getUserName() != "" && user.getPass() != ""){
boolean isActive = usrdao.isActiveUser(user.getUserName(), user.getPass());
if(isActive){
List<User> usrLst = usrdao.ListAllUsers();
model.addAttribute("message",user.getUserName());
model.addAttribute("usrLst",usrLst);
return "home";
}
else{
model.addAttribute("error","Invalid Login Details");
return "index";
}
}
return "index";
}
#RequestMapping(value="/createUser", method = RequestMethod.GET)
public String RedirectCreateUser(Model model){
return "createUser";
}
public String createUser(Model model, #ModelAttribute User user){
usrdao.CreateOrUpdateUser(user);
return "";
}
}
UserDAO
package com.springmvc.dao;
import java.util.List;
import com.springmvc.type.User;
public interface UserDAO {
public void CreateOrUpdateUser(User user);
public void DeleteUser(int uid);
public User GetUser(int uid);
public List<User> ListAllUsers();
public boolean isActiveUser(String userName,String pass);
}
UserDAOImpl
package com.springmvc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;
import com.springmvc.type.User;
#Repository("UserDAO")
public class UserDAOImpl implements UserDAO {
private JdbcTemplate jdbc;
/*
public void setJdbc(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
*/
public UserDAOImpl(DataSource DS) {
jdbc = new JdbcTemplate(DS);
}
#Override
public void CreateOrUpdateUser(User user) {
if(user.getUid() == 0){
String query = "INSERT INTO userdetails(UserName,Name,Pass) VALUES(?,?,?)";
jdbc.update(query,user.getUserName(),user.getName(),user.getPass());
}
else{
String query = "UPDATE userdetails SET UserName = ?,Name = ?,Pass = ?,isActive = ? WHERE id = ?";
jdbc.update(query, user.getUserName(),user.getName(),user.getPass(),user.getIsActive(),user.getUid());
}
}
#Override
public void DeleteUser(int uid) {
String query = "DELETE FROM userdetails WHERE id = ?";
jdbc.update(query, uid);
}
#Override
public User GetUser(int uid) {
String query = "SELECT * FROM userdetails WHERE id = ?";
return jdbc.query(query, new ResultSetExtractor<User>() {
#Override
public User extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
return null;
}
});
}
#Override
public List<User> ListAllUsers() {
String query = "SELECT * FROM userdetails";
List <User> usrLst = jdbc.query(query, new RowMapper<User>() {
#Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUid(rs.getInt("id"));
user.setUserName(rs.getString("UserName"));
user.setName(rs.getString("Name"));
user.setIsActive(rs.getInt("isActive"));
return user;
}
});
return usrLst;
}
#Override
public boolean isActiveUser(String userName, String pass) {
String query = "SELECT id FROM userdetails WHERE UserName = ? AND Pass = ? AND isActive = 1";
SqlRowSet rs = jdbc.queryForRowSet(query,userName,pass);
if(rs.next())
return true;
else
return false;
}
}
Thank You

UserDAOImpl do not have default constructor. either add default constructor or autowire the construction arg.

Spring is using a strong naming convention.
Try to use as a variable userDao as the autowired variable and use the same string in the #repository.
See this little explanation here:
https://www.tutorialspoint.com/spring/spring_beans_autowiring.htm

Related

Custom Exception not thrown in controller-method when no data is found in database

My controller always give Internal server error whenever my condition fail, and are suppose to throw custom exception ResourceNotFoundException.
When I call account/1-endpoint (no account with id 1 in database) I expect an ResourceNotFoundException, but instead I get Internal server Error.. I do not understand why ResourceNotFoundException is not thrown, I watched several youtube tutorials on the topic.
Please help by providing possible solutions.
My model classes are
package com.bank2.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Proxy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#javax.persistence.Table(name="Account")
#Proxy(lazy = false)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Account {
#Id
int accountNumber;
#Column(name="balance")
Double balance;
#Column(name="accountType")
String accountType;
public Account() {
super();
}
#Override
public String toString() {
return "Account [accountNumber=" + accountNumber + ", balance=" + balance + ", accountType=" + accountType + "]";
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public Account(int accountNumber, Double balance, String accountType) {
super();
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}
}
package com.bank2.Model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name="Customer")
#Proxy(lazy = false)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Integer customerId;
#Column(name="customerName")
String customerName;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,targetEntity = Account.class)
#JoinColumn(name = "ca_fk",referencedColumnName ="customerId")
private List<Account> accounts;
public Customer() {
super();
}
public Customer(Integer customerId, String customerName, List<Account> accounts) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.accounts = accounts;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public List<Account> getAccount() {
return accounts;
}
public void setAccount(List<Account> accounts) {
this.accounts = accounts;
}
#Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" + customerName + ", accounts=" + accounts + "]";
}
}
My service classes are
package com.bank2.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bank2.Model.Customer;
import com.bank2.repository.CustomerRepository;
#Service
public class CustomerService {
#Autowired
CustomerRepository customerRepository;
public Customer customerCreate(Customer customer) {
Customer x= customerRepository.save(customer);
return x;
}
}
package com.bank2.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bank2.Model.Account;
import com.bank2.repository.AccountRepository;
#Service
public class AccountService {
#Autowired
AccountRepository accountRepository;
public Account findAccountById(int accountNumber) {
return accountRepository.getById(accountNumber);
}
}
my controller class are
package com.bank2.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bank2.Exception.ResourceNotFoundException;
import com.bank2.Model.Account;
import com.bank2.ServiceImpl.AccountService;
#RestController
#RequestMapping("/account")
public class AccountController {
#Autowired
AccountService accountService;
#GetMapping("/{accountNumber}")
public ResponseEntity<?> getAccountById(#PathVariable("accountNumber") int accountNumber){
Account acc=accountService.findAccountById(accountNumber);
if(acc==null) {
throw new ResourceNotFoundException("Account [accountNumber="+accountNumber+"] can't be found");
}else {
return new ResponseEntity<>(acc,HttpStatus.FOUND);
}
}
package com.bank2.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 com.bank2.Exception.ResourceNotFoundException;
import com.bank2.Model.Customer;
import com.bank2.ServiceImpl.CustomerService;
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerService customerService;
#PostMapping("/createCust")
public ResponseEntity<?> CreateCustomer(#RequestBody Customer customer){
Customer cus=customerService.customerCreate(customer);
Optional<Customer> cus1 = Optional.ofNullable(cus);
if(cus1.isEmpty()) {
throw new ResourceNotFoundException("customer not created!!");
}else {
return new ResponseEntity<>(cus,HttpStatus.CREATED);
}
}
}
my expection classes are
package com.bank2.Exception;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.http.HttpStatus;
public class ApiErrors {
String message;
List<String> details;
HttpStatus status;
LocalDateTime timestamp;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<String> getDetails() {
return details;
}
public void setDetails(List<String> details) {
this.details = details;
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public ApiErrors() {
super();
// TODO Auto-generated constructor stub
}
public ApiErrors(String message, List<String> details, HttpStatus status, LocalDateTime timestamp) {
super();
this.message = message;
this.details = details;
this.status = status;
this.timestamp = timestamp;
}
#Override
public String toString() {
return "ApiErrors [message=" + message + ", details=" + details + ", status=" + status + ", timestamp="
+ timestamp + "]";
}
}
package com.bank2.Exception;
public class ResourceNotFoundException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message) {
super(message);
}
}
package com.bank2.Exception;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
#ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex){
String msg=ex.getMessage();
List<String> details=new ArrayList<>();
details.add("Resource not found");
ApiErrors errors=new ApiErrors(msg,details,HttpStatus.BAD_REQUEST,LocalDateTime.now());
return new ResponseEntity<Object>(errors,HttpStatus.BAD_REQUEST);
}
#ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleOther(Exception ex){
String msg=ex.getMessage();
List<String> details=new ArrayList<>();
details.add("Other Exceptions");
ApiErrors errors=new ApiErrors(msg,details,HttpStatus.INTERNAL_SERVER_ERROR,LocalDateTime.now());
return new ResponseEntity<Object>(errors,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
This is the Internal server error I have gotten so far in Postman:
{
"message": "Unable to find com.bank2.Model.Account with id 1; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.bank2.Model.Account with id 1",
"details": [
"Other Exceptions"
],
"status": "INTERNAL_SERVER_ERROR",
"timestamp": "2022-04-02T22:09:28.0486246"
}
My repositories are
'''
package com.bank2.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bank2.Model.Account;
#Repository
public interface AccountRepository extends JpaRepository<Account, Integer> {
}
'''
'''
package com.bank2.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bank2.Model.Customer;
#Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
}
'''
From the Documentation JpaRepository.html#getById-ID-
T getById(ID id)
Returns a reference to the entity with the
given identifier. Depending on how the JPA persistence provider is
implemented this is very likely to always return an instance and throw
an EntityNotFoundException on first access. Some of them will reject
invalid identifiers immediately.
The error message you get shows ...nested exception is EntityNotFoundException, so that could be normal...
So you could throw a ResourceNotFoundException in your service when the Account is not found.
#Service
public class AccountService {
public Account findAccountById(int accountNumber) {
try {
return accountRepository.getById(accountNumber);
} catch(EntityNotFoundException e) {
throw new ResourceNotFoundException("Account [accountNumber="+accountNumber+"] can't be found")
}
}

Creating role requirement for accessig a webpage with Spring BOOT

I am trying to add to website I created a requirement for user to be logged-in in order to access content and also split 3 types of users: non logged-in person, admin and standard user. I struggle a lot with it as I was unable to find a guide that would both explain it to me and work properly at the same time. Could you guys please help me and tell em what am I doing wrong? I spent 6 days trying to get this logging in feature to work and I feel compleatly lost at this point because I tried so many different codes and approaches from guides I found. As for my database I am using SQL Workbench.
The problem is (at least I think this is the problem) that in SecurityConfig in configure method I am not actually passing Role of the User (hasAnyRole('Admin')). I was trying to do it in many ways but I don't really udnerstand how am I supposed to pass Role to it.
Here is my controller package:
MainController:
package Projekt.ProjektAI.controller;
import Projekt.ProjektAI.entities.Book;
import Projekt.ProjektAI.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.ModelAndView;
import java.security.Provider;
import java.util.List;
#Controller
public class MainController {
private BookService service;
#Autowired
public MainController(BookService service){
this.service = service;
}
#RequestMapping("/")
public String viewNormalHomePage(Model model) {
List<Book> listBooks = service.listAll();
model.addAttribute("listBooks", listBooks);
return "indexNormal";
}
#RequestMapping("/admin")
public String viewAdminHomePage(Model model) {
List<Book> listBooks = service.listAll();
model.addAttribute("listBooks", listBooks);
return "index";
}
#RequestMapping("/user")
public String viewUserHomePage(Model model) {
List<Book> listBooks = service.listAll();
model.addAttribute("listBooks", listBooks);
return "indexStandard";
}
#RequestMapping("/admin/new")
public String showNewBookPage(Model model) {
Book book = new Book();
model.addAttribute("book", book);
return "newBook";
}
#RequestMapping("/admin/edit/{id}")
public ModelAndView showEditBookPage(#PathVariable(name = "id") Long id) {
ModelAndView mav = new ModelAndView("editBook");
Book book = service.get(id);
mav.addObject("book", book);
return mav;
}
#RequestMapping(value = "/admin/save", method = RequestMethod.POST)
public String saveBook(#ModelAttribute("book") Book book) {
service.save(book);
return "redirect:/";
}
#RequestMapping("/admin/delete/{id}")
public String deleteBook(#PathVariable(name = "id") Long id) {
service.delete(id);
return "redirect:/";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
return "login";
}
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String userIndex() {
return "user/index";
}
}
UserRegistrationController:
package Projekt.ProjektAI.controller;
import javax.validation.Valid;
import Projekt.ProjektAI.service.UserService;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/registration")
public class UserRegistrationController {
#Autowired
private UserService userService;
#ModelAttribute("user")
public UserRegistrationDTO userRegistrationDto() {
return new UserRegistrationDTO();
}
#GetMapping
public String showRegistrationForm(Model model) {
return "registration";
}
#PostMapping
public String registerUserAccount(#ModelAttribute("user") #Valid UserRegistrationDTO userDto,
BindingResult result) {
User existing = userService.findByEmail(userDto.getEmail());
if (existing != null) {
result.rejectValue("email", null, "There is already an account registered with that email");
}
if (result.hasErrors()) {
return "registration";
}
userService.save(userDto);
return "redirect:/registration?success";
}
}
Entities package:
Book entity:
package Projekt.ProjektAI.entities;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
#Entity
#Getter
#Setter
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String autor;
#Column
private String tytul;
#Column
private String gatunek;
#Column
private float cena;
public Book() {
}
#Override
public String toString() {
return "Book{" +
"id=" + id +
", autor='" + autor + '\'' +
", tytul='" + tytul + '\'' +
", gatunek='" + gatunek + '\'' +
", cena=" + cena +
'}';
}
}
Role entity:
package Projekt.ProjektAI.entities;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
#Getter
#Setter
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
protected Role() {}
public Role(String name) {
this.name = name;
}
#Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
User entity:
package Projekt.ProjektAI.entities;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.Collection;
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Table(uniqueConstraints = #UniqueConstraint(columnNames = "email"))
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Collection <Projekt.ProjektAI.entities.Role> roles;
public Collection <Projekt.ProjektAI.entities.Role> getRoles() {
return roles;
}
public void setRoles(Collection <Projekt.ProjektAI.entities.Role> roles) {
this.roles = roles;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", password='" + "*********" + '\'' +
", roles=" + roles +
'}';
}
}
registration DTO package:
FieldMatch interface:
package Projekt.ProjektAI.registrationDTO;
import javax.validation.Payload;
import javax.validation.Constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#Target({
TYPE,
ANNOTATION_TYPE
})
#Retention(RUNTIME)
#Constraint(validatedBy = FieldMatchValidator.class)
#Documented
public #interface FieldMatch {
String message() default "{constraints.field-match}";
Class < ? > [] groups() default {};
Class < ? extends Payload > [] payload() default {};
String first();
String second();
#Target({
TYPE,
ANNOTATION_TYPE
})
#Retention(RUNTIME)
#Documented
#interface List {
FieldMatch[] value();
}
}
Field Match Validator:
package Projekt.ProjektAI.registrationDTO;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.BeanUtils;
public class FieldMatchValidator implements ConstraintValidator <Projekt.ProjektAI.registrationDTO.FieldMatch, Object > {
private String firstFieldName;
private String secondFieldName;
#Override
public void initialize(final Projekt.ProjektAI.registrationDTO.FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
#Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
try {
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
} catch (final Exception ignore) {}
return true;
}
}
User Registration DTO:
package Projekt.ProjektAI.registrationDTO;
import lombok.Getter;
import lombok.Setter;
import javax.validation.Valid;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
#Projekt.ProjektAI.registrationDTO.FieldMatch.List({
#Projekt.ProjektAI.registrationDTO.FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
#Projekt.ProjektAI.registrationDTO.FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")
})
#Getter
#Setter
public class UserRegistrationDTO {
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
private String password;
#NotEmpty
private String confirmPassword;
#Email
#NotEmpty
private String email;
#Email
#NotEmpty
private String confirmEmail;
#AssertTrue
private Boolean terms;
}
repositories package:
Book Repository
package Projekt.ProjektAI.repositories;
import Projekt.ProjektAI.entities.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}
User Repository:
package Projekt.ProjektAI.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import Projekt.ProjektAI.entities.User;
#Repository
public interface UserRepository extends JpaRepository < User, Long > {
User findByEmail(String email);
}
security package:
package Projekt.ProjektAI.security;
import Projekt.ProjektAI.entities.User;
import Projekt.ProjektAI.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import Projekt.ProjektAI.service.UserService;
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/new", "/edit/{id}", "/save", "/delete/{id}")
.access("hasAnyRole('Admin')")
.and()
.authorizeRequests()
.antMatchers("/registration**","/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
}
service package:
Book Service:
package Projekt.ProjektAI.service;
import Projekt.ProjektAI.entities.Book;
import Projekt.ProjektAI.repositories.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class BookService {
private BookRepository repo;
#Autowired
public BookService(BookRepository repo)
{
this.repo =repo;
}
public List<Book> listAll() {
return repo.findAll();
}
public void save(Book book) {
repo.save(book);
}
public Book get(long id) {
return repo.findById(id).get();
}
public void delete(long id) {
repo.deleteById(id);
}
}
User Service interface:
package Projekt.ProjektAI.service;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.entities.User;
import org.springframework.security.core.userdetails.UserDetailsService;
public interface UserService extends UserDetailsService {
User findByEmail(String email);
User save(UserRegistrationDTO registration);
}
User Service Implementation:
package Projekt.ProjektAI.service;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import Projekt.ProjektAI.service.UserService;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.entities.User;
import Projekt.ProjektAI.entities.Role;
import Projekt.ProjektAI.service.UserService;
import Projekt.ProjektAI.registrationDTO.UserRegistrationDTO;
import Projekt.ProjektAI.repositories.UserRepository;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private BCryptPasswordEncoder passwordEncoder;
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
public User save(UserRegistrationDTO registration) {
User user = new User();
user.setFirstName(registration.getFirstName());
user.setLastName(registration.getLastName());
user.setEmail(registration.getEmail());
user.setPassword(passwordEncoder.encode(registration.getPassword()));
user.setRoles(Arrays.asList(new Role("ROLE_USER")));
return userRepository.save(user);
}
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(),
mapRolesToAuthorities(user.getRoles()));
}
private Collection < ? extends GrantedAuthority > mapRolesToAuthorities(Collection < Role > roles) {
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
}
application properties:
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://localhost:3366/projektai?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin
Thank you very much for any tips!

Unsatisfied dependency expressed through field 'userTokenService'

homeControler
package com.book.controller;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.book.entity.User;
import com.book.entity.security.UserToken;
import com.book.entity.security.service.SecurityService;
import com.book.entity.security.service.UserTokenService;
#Controller
public class HomeController {
#Autowired
private UserTokenService userTokenService;
#Autowired
private SecurityService securityService;
#RequestMapping("/")
public String getHome() {
return "index";
}
#RequestMapping("/myaccount")
public String myAccount() {
return "myAccount";
}
#RequestMapping("/login")
public String login(Model model) {
model.addAttribute("classActiveLogin", true);
return "myAccount";
}
#RequestMapping("/forgetPassword")
public String forgetPassword(Model model) {
model.addAttribute("classActiveForgetPassword", true);
return "myAccount";
}
#RequestMapping("/newUser")
public String newUser(Locale locale, #RequestParam("token") String token, Model model) {
UserToken userToken = userTokenService.getPasswordResetToken(token);
if (userToken == null) {
String msg = "Invalid Token";
model.addAttribute("msg", msg);
return "redirect:/badRequest";
}
User user = userToken.getUser();
String username = user.getUsername();
UserDetails userDetails = securityService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),
userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
model.addAttribute("classActiveEdit", true);
return "myProfile";
}
}
User Token
package com.book.entity.security;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import com.book.entity.User;
#Entity
public class UserToken {
private static final int EXPIRATION = 60 * 24;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String token;
#OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
#JoinColumn(nullable=false, name="user_id")
private User user;
private Date expiryDate;
public UserToken(final String token, final User user) {
super ();
this.token = token;
this.user = user;
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
private Date calculateExpiryDate (final int expiryTimeInMinutes) {
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(new Date().getTime());
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime());
}
public void updateToken(final String token) {
this.token = token;
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
#Override
public String toString() {
return "P_Token [id=" + id + ", token=" + token + ", user=" + user + ", expiryDate=" + expiryDate + "]";
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public static int getExpiration() {
return EXPIRATION;
}
}
UserTokenService
package com.book.entity.security.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.book.entity.User;
import com.book.entity.security.UserToken;
import com.book.entity.security.repo.PasswordResetRepo;
import com.book.entity.security.repo.UserTokenRepo;
#Service("userTokenService")
public class UserTokenService implements UserTokenRepo{
#Autowired
private PasswordResetRepo repo;
#Override
public UserToken getPasswordResetToken(final String token) {
return repo.findByToken(token);
}
#Override
public void createPasswordResetTokenForUser(final User user, final String token) {
final UserToken myToken = new UserToken(token, user);
repo.save(myToken);
}
}
UserTokenRepo
package com.book.entity.security.repo;
import com.book.entity.User;
import com.book.entity.security.UserToken;
public interface UserTokenRepo {
UserToken getPasswordResetToken(final String token);
void createPasswordResetTokenForUser(final User user, final String token);
}
SecurityService
package com.book.entity.security.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.book.entity.User;
import com.book.entity.security.repo.SecurityUserRepository;
#Service
public class SecurityService implements UserDetailsService {
#Autowired
private SecurityUserRepository securityUserRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = securityUserRepository.findByUsername(username);
if (null == user) {
throw new UsernameNotFoundException("Username not found");
}
return user;
}
}
PasswordResetRepo
package com.book.entity.security.repo;
import java.util.Date;
import java.util.stream.Stream;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import com.book.entity.User;
import com.book.entity.security.UserToken;
public interface PasswordResetRepo extends JpaRepository<UserToken, Long > {
UserToken findByToken(String token);
UserToken findByUser(User user);
Stream<UserToken> findAllByExpiryDateLessThan(Date now);
#Modifying
#Query("delete from P_Token t where t.expirydate <= ?1")
void deleteAllExpiredSince(Date now);
}
Error:-->
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController': Unsatisfied dependency expressed through field 'userTokenService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userTokenService': Unsatisfied dependency expressed through field 'repo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'passwordResetRepo': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: antlr/RecognitionException
May be problem lays on HomeController bellow code:
#Autowired
private UserTokenService userTokenService;
Replace this code with bellow code:
#Autowired
private UserTokenRepo userTokenService;
Your main error portion is:
Unsatisfied dependency expressed through field 'repo'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'passwordResetRepo': Invocation of init
method failed; nested exception is java.lang.NoClassDefFoundError:
antlr/RecognitionException
Here it is failed to create bean passwordResetRepo cause antlr/RecognitionException
Its solution is java.lang.ClassNotFoundException: antlr.RecognitionException shows antlr lib missing.
Add it and itss done :)
You can try to add the following dependency. It will solve your issue.
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-complete</artifactId>
<version>3.5.2</version>
</dependency>
Another possible consideration:
Please check all JPA query on PasswordResetRepo repository. Sometimes if query not matched with entity variable name then Spring can't create bean for that repository
Hope this will solve your problem.
Thanks :)
Take a look at the stacktrace. The issue is: spring IoC container is failing to create homeController bean; because the container is failing to create userTokenService bean; and that is because the container is failing to create passwordResetRepo bean with java.lang.NoClassDefFoundError.
Adding the following in your config file should solve your problem:
<jpa:repositories base-package="com.book.entity.security.repo" />
As you are using Spring Boot, please check this guide on Accessing Data with JPA.
From the above mentioned guide:
By default, Spring Boot will enable JPA repository support and look
in the package (and its subpackages) where #SpringBootApplication is
located. If your configuration has JPA repository interface
definitions located in a package not visible, you can point out
alternate packages using #EnableJpaRepositories and its type-safe
basePackageClasses=MyRepository.class parameter.

Spring MVC to REST

I have a Spring MVC aplication. I want to convert it to a RESTful
webservice, which returns a JSON response. Can somebody help me with this??
Basically, I want to convert my controller to a REST controller.
My Code :
///////////////////////////PersonController//////////////////////////////
package com.journaldev.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.journaldev.spring.model.Person;
import com.journaldev.spring.service.PersonService;
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required=true)
#Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p){
if(p.getId() == 0){
//new person, add it
this.personService.addPerson(p);
}else{
//existing person, call update
this.personService.updatePerson(p);
}
return "redirect:/persons";
}
#RequestMapping("/remove/{id}")
public String removePerson(#PathVariable("id") int id){
this.personService.removePerson(id);
return "redirect:/persons";
}
#RequestMapping("/edit/{id}")
public String editPerson(#PathVariable("id") int id, Model model){
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}
/////////////////////////////////PersonDAO/////////////////////////////
package com.journaldev.spring.dao;
import java.util.List;
import com.journaldev.spring.model.Person;
public interface PersonDAO {
public void addPerson(Person p);
public void updatePerson(Person p);
public List<Person> listPersons();
public Person getPersonById(int id);
public void removePerson(int id);
}
///////////////////////////////PersonDAOImpl/////////////////////////
package com.journaldev.spring.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.journaldev.spring.model.Person;
#Repository
public class PersonDAOImpl implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addPerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("Person saved successfully, Person Details="+p);
}
#Override
public void updatePerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("Person updated successfully, Person Details="+p);
}
#SuppressWarnings("unchecked")
#Override
public List<Person> listPersons() {
Session session = this.sessionFactory.getCurrentSession();
List<Person> personsList = session.createQuery("from Person").list();
for(Person p : personsList){
logger.info("Person List::"+p);
}
return personsList;
}
#Override
public Person getPersonById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details="+p);
return p;
}
#Override
public void removePerson(int id) {
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
if(null != p){
session.delete(p);
}
logger.info("Person deleted successfully, person details="+p);
}
}
//////////////////////////////////Person(Model)///////////////////////
package com.journaldev.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Entity bean with JPA annotations
* Hibernate provides JPA implementation
* #author pankaj
*
*/
#Entity
#Table(name="PERSON")
public class Person {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString(){
return "id="+id+", name="+name+", country="+country;
}
}
///////////////////////////////////PersonService///////////////////
package com.journaldev.spring.service;
import java.util.List;
import com.journaldev.spring.model.Person;
public interface PersonService {
public void addPerson(Person p);
public void updatePerson(Person p);
public List<Person> listPersons();
public Person getPersonById(int id);
public void removePerson(int id);
}
//////////////////////////////ServiceImpl////////////////////////////
package com.journaldev.spring.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.journaldev.spring.dao.PersonDAO;
import com.journaldev.spring.model.Person;
#Service
public class PersonServiceImpl implements PersonService {
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
#Override
#Transactional
public void addPerson(Person p) {
this.personDAO.addPerson(p);
}
#Override
#Transactional
public void updatePerson(Person p) {
this.personDAO.updatePerson(p);
}
#Override
#Transactional
public List<Person> listPersons() {
return this.personDAO.listPersons();
}
#Override
#Transactional
public Person getPersonById(int id) {
return this.personDAO.getPersonById(id);
}
#Override
#Transactional
public void removePerson(int id) {
this.personDAO.removePerson(id);
}
}
First you have to add Jackson Databind dependency in your pom file then you can define your rest controller for exemple :
#RestController
public class PersonRestService {
#Autowired
private PersonService personService ;
#RequestMapping(value="/persons",method=RequestMethod.POST)
public Person addPerson(#RequestBody Person Person) {
return personService.addPerson(Person);
}
#RequestMapping(value="/persons",method=RequestMethod.Delete)
public void deletePerson(int code) {
personService.deletePerson(code);
}
#RequestMapping(value="/persons",method=RequestMethod.GET)
public Person getPerson(#RequestParam int code) {
return personService.getPersonById(code);
}
#RequestMapping(value="/allPersons",method=RequestMethod.GET)
public List<Person> getAllPerson() {
return personService.getAllPerson();
}
}
Its easy, what you need to do is add a response in JSON for all request which need it.
The annotation is #ResponseBody and you can return any object, jackson will serialize it to json format for you.
For example in your code:
#RequestMapping("/remove/{id}")
#ResponseBody
public boolean removePerson(#PathVariable("id") int id){
this.personService.removePerson(id);
//true if everything was OK, false if some exception
return true;
}
...
#RequestMapping(value = "/persons", method = RequestMethod.GET)
#ResponseBody
public List<Person> listPersons(Model model) {
return this.personService.listPersons();
}
You only need to modify your controller, to make it RESTFul
Also you will have to add logic to your JS code to handle the new responses values.
Simply use the annotation #RestController.
You can also refer to previously asked question on this link
Difference between spring #Controller and #RestController annotation

sessionfactory always null when done with javaconfig

The sessionFactory Bean which is autowired in my DAO is always showingup to be null. below is my project.
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
#Configuration
#Import({HibernateConfig.class})
public class AppConfig {
#Bean
public PropertyPlaceholderConfigurer propertyPlaceHolderConfigurer(){
PropertyPlaceholderConfigurer prop = new PropertyPlaceholderConfigurer();
prop.setLocation(new ClassPathResource("dbProperties.properties"));
prop.setIgnoreUnresolvablePlaceholders(true);
return prop;
}
}
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.model.Person;
#Configuration
//#EnableTransactionManagement
//#PropertySource(value={"classpath:dbProperties.properties"})
public class HibernateConfig {
#Value("${driverClassName}")
private String driverClassName;
#Value("${url}")
private String url;
#Value("${username}")
private String username;
#Value("${password}")
private String password;
#Value("${hibernate.dialect}")
private String hibernateDielect;
#Value("${hibernate.show_sql}")
private String hibernateShowSQL;
#Value("${hibernate.hbm2ddl.auto}")
private String hibernateHbm2Ddlauto;
#Bean
public DataSource datasource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", hibernateDielect);
properties.put("hibernate.show_sql", hibernateShowSQL);
properties.put("hibernate.hbm2ddl.auto", hibernateHbm2Ddlauto);
return properties;
}
#Bean
#Autowired
public SessionFactory sessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.scanPackages("com.configuration");
sessionBuilder.addAnnotatedClass(Person.class);
sessionBuilder.addProperties(hibernateProperties());
return sessionBuilder.buildSessionFactory();
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
}
import java.util.List;
import com.model.Person;
public interface PersonDao {
void savePerson(Person persom);
void deletePerson(String taxid);
List<Person> getAllPersons();
Person updatePerson(Person person);
Person findPersonById(String taxid);
}
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.Person;
#Service
public class PersonDaoImpl implements PersonDao {
#Autowired
SessionFactory sessionFactory;
#Override
#Transactional
public void savePerson(Person person) {
sessionFactory.getCurrentSession().persist(person);
}
#Override
#Transactional
public void deletePerson(String taxid) {
// TODO Auto-generated method stub
// Criteria criteria = getSession().createCriteria(Person.class);
Query query = sessionFactory.getCurrentSession().createSQLQuery("DELETE FROM PERSON WHERE taxid = :taxid");
query.setString(taxid, "taxid");
}
#SuppressWarnings("unchecked")
#Override
#Transactional
public List<Person> getAllPersons() {
// TODO Auto-generated method stub
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Person.class);
return (List<Person>) criteria.list();
}
#Override
#Transactional
public Person updatePerson(Person person) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().update(person);
return person;
}
#Override
#Transactional
public Person findPersonById(String taxid) {
// TODO Auto-generated method stub
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Person.class);
criteria.add(Restrictions.eq("taxid", taxid));
return (Person) criteria.uniqueResult();
}
}
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name ="person")
public class Person {
#Column(name ="FIRSTNAME")
private String firstName;
#Column(name ="LASTNAME")
private String lastName;
#Column(name ="DOB")
private Date DOB;
#Column(name ="TAXID")
#Id
private String taxid;
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 Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public String getTaxid() {
return taxid;
}
public void setTaxid(String taxid) {
this.taxid = taxid;
}
#Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", DOB=" + DOB + ", taxid=" + taxid + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((DOB == null) ? 0 : DOB.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((taxid == null) ? 0 : taxid.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (DOB == null) {
if (other.DOB != null)
return false;
} else if (!DOB.equals(other.DOB))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (taxid == null) {
if (other.taxid != null)
return false;
} else if (!taxid.equals(other.taxid))
return false;
return true;
}
}
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import com.configuration.AppConfig;
import com.dao.PersonDaoImpl;
import com.model.Person;
public class AppMain {
public static void main(String args[]) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Person person = new Person();
person.setFirstName("Akhil");
person.setLastName("goli");
person.setTaxid("123abc456");
PersonDaoImpl impl = new PersonDaoImpl();
impl.savePerson(person);
}
}
Exception in thread "main" java.lang.NullPointerException at
com.dao.PersonDaoImpl.savePerson(PersonDaoImpl.java:25) at
main.AppMain.main(AppMain.java:20)
You have to call afterPropertiesSet() for initializing the bean. Now you only created the bean but not initialized.
I figured it out. As I was using Hibernate4 I need to use
StandardServiceRegistryBuilder class to get SessionFactory.
Hope this snippet helps.
public class HibernateUtil {
public SessionFactory getSessionFactory()
{
Configuration config = new Configuration().configure();
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
SessionFactory session = config.buildSessionFactory(serviceRegistryBuilder.build());
return session;
}
I am putting sessionFactory configuration code here. Hope it will help you.
#Bean
// #Autowired
// #Bean(name = "sessionFactory")
public SessionFactory sessionFactory() throws IOException {
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
sessionFactory.setHibernateProperties(hibernateProperties);
sessionFactory.afterPropertiesSet(); // Used in Spring-boot 2.x for initializing the bean
SessionFactory sf = sessionFactory.getObject();
System.out.println("## getSessionFactory: " + sf);
return sf;
}

Resources