Fixed : spring mvc queries not found in postman because it is not in the same paquage - spring

i am new in spring world and i have implemented a method but when i go to browser and click
http://localhost:8081/SpringMVC/servlet/aaa
i get this error message :
{
"timestamp": "2020-12-26T23:16:53.052+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/SpringMVC/servlet/aaa"
}
I have tried two methods but still i am facing the same message
here my controller:
package t.esprit.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import tn.esprit.entities.Contrat;
import tn.esprit.entities.Departement;
import tn.esprit.entities.Employe;
import tn.esprit.entities.Entreprise;
import tn.esprit.services.IEmployeService;
import tn.esprit.services.IEntrepriseService;
#SpringBootApplication(scanBasePackages={
"tn.esprit"})
#RestController
public class RestControlEmploye {
#Autowired
IEmployeService empService;
#Autowired
IEntrepriseService entService;
/* #PostMapping("/ajouterEmployer")
#ResponseBody
public Employe ajouterEmploye(#RequestBody Employe emp){
empService.ajouterEmploye(emp);
return emp;
}
#PostMapping("/affecterEmployerDepartement/{employeId}/{depId}")
#ResponseBody
public Employe affecterEmployeADepartement(#RequestParam("user-id")int employeId,#RequestParam("user-id") int depId) {
return empService.affecterEmployeADepartement(employeId, depId);
}
#PostMapping("/ajouterContrat")
#ResponseBody
public int ajouterContrat(#RequestBody Contrat contrat) {
return empService.ajouterContrat(contrat);
}
#PostMapping("/affecterContratEmployer/{contratId}/{employeId}")
#ResponseBody
public void affecterContratAEmploye(#RequestParam("contratId")int contratId,#RequestParam("employeId")int employeId) {
empService.affecterContratAEmploye(contratId, employeId);
}
#PostMapping("/affecterContratEmployer/{employeId}")
#ResponseBody
public String getEmployePrenomById(#RequestParam("employeId")int employeId) {
return empService.getEmployePrenomById(employeId);
}
#GetMapping("/getNombreEmployeJPQL")
#ResponseBody
public long getNombreEmployeJPQL() {
return empService.getNombreEmployeJPQL();
}
#GetMapping("/getAllEmploye")
public List<Employe> listemploye() {
List<Employe> list = empService.listemploye();
return list;
}
#PostMapping("/affecterEmployeDepartement")
#ResponseBody
public void affecterEmployeDepartement(#RequestBody Employe user, #RequestBody Departement dep) {
empService.affecterEmployeDepartement(user, dep);
}
#GetMapping("/getAllEmployeByEntreprise")
#ResponseBody
public List<Employe> getallEmployebyEntreprise(#PathVariable("identr")int identr) {
return empService.getallEmployebyEntreprise(identr);
}
#PutMapping("/mettreAjourEmailByEmployeId")
#ResponseBody
public void mettreAjourEmailByEmployeId(#RequestParam("email")String email, #RequestParam("employeId")int employeId) {
empService.mettreAjourEmailByEmployeId(email, employeId);
}
#GetMapping("/getEmployeById/{employeId}")
#ResponseBody
public Employe getEmployeById( #PathVariable("employeId") int employeId) {
return empService.getEmployeById(employeId);
}
#DeleteMapping("/deleteEmployeById/{id}")
#ResponseBody
public void deleteEmployerById(#RequestParam("id") int id) {
empService.deleteEmployerById(id);
}
#DeleteMapping("/deleteEmployeContractById/{id}")
#ResponseBody
public void deleteEmployerContractById(#RequestParam("id") int id) {
empService.deleteEmployerContractById(id);
}
*/
/*#GetMapping("getAllEmployeNames")
public List<String> getAllEmployeNamesJPQL() {
List<String> list = empService.getAllEmployeNamesJPQL();
return list;
}*/
#RequestMapping(value="/aaa", method= RequestMethod.GET, produces = "application/json; charset=utf-8")
public List<String> getAllEmployeNamesJPQL() {
List<String> list = empService.getAllEmployeNamesJPQL();
return list;
}
}
i do not understand what is happening , i launched my application as a spring boot application and tried man of those different queries but i still get the same result , for idea my database and apache server are active and working fine and the my repositories working fine too , just the urls none worked for me!
here my application properties file:
#Server configuration
server.servlet.context-path=/SpringMVC
spring.mvc.servlet.path=/servlet
server.port=8081
### DATABASE ###
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/timesheet?useUnicode=true&useJDBCCo
spring.datasource.username=root
spring.datasource.password=
### JPA / HIBERNATE ###
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
#Web configuration
spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.jsp
#logging configuration
logging.level.tn.esprit.service=debug
logging.level.tn.esprit.repository=warn
logging.level.root=INFO
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %-5level - %logger{36} - %msg%n
logging.file=C:\logs\springboot.log
what am i missing???? why postman and my browser can not catch the queries?

You should add #RequestMapping annotation on top of your class and this parameter should be "/SpringMVC/servlet/{function extension}". For this function "aaa" as you show.
import java.util.List;
#SpringBootApplication(scanBasePackages={"tn.esprit"})
#RestController
#RequestMapping("/SpringMVC/servlet")
public class RestControlEmploye {
#Autowired
IEmployeService empService;
#Autowired
IEntrepriseService entService;
#RequestMapping(value="/aaa", method= RequestMethod.GET, produces = "application/json; charset=utf-8")
public List<String> getAllEmployeNamesJPQL() {
List<String> list = empService.getAllEmployeNamesJPQL();
return list;
}
}

Related

Spring rest controller does not validate my DTO

I have this request and response:
#Data
public class TestRequestDto {
#Min(7)
private String name;
}
#Data
public class TestResponseDto {
private String response;
}
And I have a controller:
package com.example.validation.demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
#Slf4j
#RestController
public class TetController {
#PostMapping("/test")
public TestResponseDto getTestResponseDto(#Valid #RequestBody TestRequestDto request){
log.info(request.getName());
TestResponseDto response = new TestResponseDto();
response.setResponse("response");
return response;
}
}
I send a post request({"name":"test"}) with an invalid name but it works. What am I doing wrong?
Starting with Boot 2.3, we also need to explicitly add the spring-boot-starter-validation dependency

Spring Boot MongoDB get only certain fields from database into model

I am trying to understand how to work with MongoDB and Spring Boot. I have a mongodb with sample data and I want it to return only selected fields and not the entire data.
My mongoDB collection contains data in the format
DAO.java
package com.books.Reading.DAO;
import com.books.Reading.model.booksModel;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
public interface readingListDAO extends MongoRepository<booksModel, String> {
#Query("{'title' : 'Griffon in Action'}")
public booksModel findFirstByOrderByTitleAsc();
}
model.java
package com.books.Reading.model;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class booksModel {
String title;
String isbn;
int pageCount;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
}
controller.java
package com.books.Reading.controller;
import com.books.Reading.model.booksModel;
import com.books.Reading.service.readingListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class readingListController {
#Autowired
private readingListService rlService;
#RequestMapping("/")
#ResponseBody
public booksModel getOne(){
return rlService.getOne();
}
}
service.java
package com.books.Reading.service;
import com.books.Reading.model.booksModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class readingListService {
#Autowired
private com.books.Reading.DAO.readingListDAO readingListDAO;
public booksModel getOne(){
System.out.println(readingListDAO.findFirstByOrderByTitleAsc());
return readingListDAO.findFirstByOrderByTitleAsc();
}
}
application.properties
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=book
spring.session.mongodb.collection-name=readinglist
The MongoDB is hosted locally. How can I retrieve only selected fields (title, isbn and pageCount) from the database.
I am very new to Spring Boot, so if there are other errors or best practices, I welcome your feedback.
By default, all the properties of document will be fetched. if you want to ignore some of the properties in the result, you can use filter option.
#Query(value = "{'title' : ?0}", fields = "{'description' : 0}")
BooksModel findBooksModelByTitle(String title);

Deployed Spring App is not getting routed to correct URL on first logins

I deployed a Spring App to Heroku. I am using Spring Security for logging in and registration. My problem is that for new users, when they initially log-in, it takes them to the base URL (the URL that Heroku gave me for my site). All of my main html files are in a folder named "cheese". The problem is that it directs me to the main URL (instead of "/cheese/account", which is where I direct it to be routed in my SecurityConfig), and I get a white label error.
This only happens the first time. When they log on again, it takes them to the correct URL, which is "/cheese/account". Also, once in a while, I will click on the base URL that heroku gave for my site, and it gives me just that URL, and doesn't direct me to "/cheese/login". This will happen if I try to access the URL from an incognito window.
I dont have this problem at all when running it locally. Here is the relevant code...Let me know if you need anything, in addition.
SecurityConfig
package com.example.demo;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.sql.DataSource;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select email as principal, password as credentials, true from customer where email=?")
.authoritiesByUsernameQuery("select customer_email as principal, role_id as role from user_roles where customer_email=?")
.passwordEncoder(passwordEncoder()).rolePrefix("ROLE_");
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(
"/**/webjars/**",
"/cheese/signup",
"/cheese/login",
"/cheese/success").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/cheese/login")
.defaultSuccessUrl("/cheese/account")
.permitAll();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
UserController
package com.example.demo.controllers;
import com.example.demo.models.Customer;
import com.example.demo.models.data.CustomerDao;
import com.example.demo.models.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
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("cheese")
public class UserController {
#Autowired
private CustomerDao customerDao;
#Autowired
UserService userService;
#RequestMapping(value = "login")
public String loginPage(Model model) {
model.addAttribute("title", "Login Page");
model.addAttribute("customer", new Customer());
return "cheese/login";
}
#RequestMapping(value = "account")
public String accountInfo(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = customerDao.findByEmail(authentication.getName());
model.addAttribute("name", customer.getName());
model.addAttribute("customer", customer);
return "cheese/account";
}
#GetMapping("signup")
public String displaySignUpForm(Model model) {
model.addAttribute("title", "Sign Up");
model.addAttribute("customer", new Customer());
return "cheese/signup";
}
#PostMapping(value = "signup")
public String processSignUp(Model model, #ModelAttribute Customer customer, Errors errors) {
if (errors.hasErrors()) {
return "cheese/signup";
}
userService.createUser(customer);
return "cheese/success";
}
}
MainController
package com.example.demo.controllers;
import com.example.demo.models.Cheese;
import com.example.demo.models.data.CheeseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RequestMapping(value = "cheese")
#Controller
public class MainController {
#Autowired
CheeseDao cheeseDao;
#RequestMapping(value = "")
public String hello(Model model) {
model.addAttribute("title", "Grocery List");
model.addAttribute("cheeses", cheeseDao.findAll());
return "cheese/index";
}
#GetMapping("add")
public String displayAddCheeseForm(Model model) {
model.addAttribute("title", "Add Cheese");
model.addAttribute("cheese", new Cheese());
return "cheese/add";
}
#PostMapping("add")
public String processAddCheeseForm(Model model,
#ModelAttribute #Valid Cheese cheese,
Errors errors) {
if (errors.hasErrors()) {
return "cheese/add";
}
cheeseDao.save(cheese);
return "redirect:";
}
#RequestMapping(value = "remove", method = RequestMethod.GET)
public String displayRemoveCheeseForm(Model model) {
model.addAttribute("cheeses", cheeseDao.findAll());
model.addAttribute("title", "Remove Cheese");
return "cheese/remove";
}
#RequestMapping(value = "remove", method = RequestMethod.POST)
public String processRemoveCheeseForm(Model model, #RequestParam int[] cheeseIds) {
for (int id : cheeseIds) {
cheeseDao.deleteById(id);
}
return "redirect:";
}
}

Spring - Failed to convert property value of type java.lang.String to required type

I am making a project of the Housing Association in Spring.
When I'm trying to add an object to my list of apartments I'm getting an error that is written somehow on the page:
https://s28.postimg.org/vrhy6mbd9/blad.jpg
Apartments have relation Many to One Building.
Apartment Controller:
package pl.dmcs.spoldzielnia.controllers;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestUtils;
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.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import pl.dmcs.spoldzielnia.domain.Apartment;
import pl.dmcs.spoldzielnia.service.ApartmentService;
import pl.dmcs.spoldzielnia.service.BuildingService;
#Controller
#SessionAttributes
public class ApartmentController {
#Autowired
ApartmentService apartmentService;
#Autowired
BuildingService buildingService;
#RequestMapping("admin/apartment")
public String listApartment(Map<String, Object> map, HttpServletRequest request) {
int apartmentId = ServletRequestUtils.getIntParameter(request, "apartmentId" , -1);
if (apartmentId > 0)
{
Apartment apartment = apartmentService.getApartment(apartmentId);
apartment.setBuilding(buildingService.getBuilding(apartmentService.getApartment(apartmentId).getBuilding().getId()));
map.put("selectedBuilding", apartmentService.getApartment(apartmentId).getBuilding().getId());
map.put("apartment", apartment);
}
else
map.put("apartment", new Apartment());
map.put("buildingList", buildingService.listBuilding());
map.put("apartmentList", apartmentService.listApartment());
return "apartment";
}
#RequestMapping(value = "admin/addApartment", method = RequestMethod.POST)
public String addContact(#ModelAttribute("apartment") Apartment apartment, BindingResult result,
HttpServletRequest request, Map<String, Object> map) {
if (result.getErrorCount()==0)
{
if (apartment.getId()==0)
{
if (apartment.getBuilding().getId() > 0)
apartment.setBuilding(buildingService.getBuilding(apartment.getBuilding().getId()));
apartmentService.addApartment(apartment);
}
else
{
apartmentService.editApartment(apartment);
}
return "redirect:/admin/apartment.html";
}
map.put("buildingList", buildingService.listBuilding());
map.put("apartmentList", apartmentService.listApartment());
return "apartment";
}
#RequestMapping("admin/delete/apartment/{apartmentId}")
public String deleteApartment(#PathVariable("apartmentId") Integer apartmentId) {
apartmentService.removeApartment(apartmentId);
return "redirect:/admin/apartment.html";
}
// #RequestMapping("/apartment")
// public ModelAndView showContacts() {
//
// return new ModelAndView("apartment", "command", new Apartment());
// }
Domain:
package pl.dmcs.spoldzielnia.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="apartment")
public class Apartment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
int id;
#Column(name="apartmentNumber", nullable=false)
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne
private Building building;
public Building getBuilding() {
return building;
}
public void setBuilding(Building building) {
this.building = building;
}
}
}
Building Service Implementation:
package pl.dmcs.spoldzielnia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.dmcs.spoldzielnia.dao.BuildingDAO;
import pl.dmcs.spoldzielnia.domain.Building;
import pl.dmcs.spoldzielnia.domain.Building;
#Service
#Transactional
public class BuildingServiceImpl implements BuildingService{
#Autowired
BuildingDAO buildingDAO;
#Transactional
public void addBuilding(Building building) {
buildingDAO.addBuilding(building);
}
#Transactional
public List<Building> listBuilding() {
return buildingDAO.listBuilding();
}
#Transactional
public Building getBuilding(int id) {
return buildingDAO.getBuilding(id);
}
#Transactional
public void removeBuilding(int id) {
buildingDAO.removeBuilding(id);
}
#Transactional
public void editBuilding(Building building) {
buildingDAO.editBuilding(building);
}
}
Could you help me to solve my problem?
The problem is that you are assuming that Spring MVC is going to be able to fill your Apartment object from the data passed. From the form it looks like the Building number is 12, which probably is a unique identifier for the Building in the database, but how is Spring MVC going to know how to go to the database, retrieve the proper building object and put it into the Apartment object?
Remember that objects mapped through SpringMVC parameters are regular Java POJOs, not Hibernate attached entities. So, when the mapping occurs SpringMVC is trying to put "12" into the building attribute of type Building into your POJO (which explains the error you are getting).
You have two options:
First, you can register a custom formatter, that will use the passed id to retrieve a Building from the database:
import org.springframework.core.convert.converter.Converter;
public class BuildingIdToBuildingConverter implements Converter<String, Building> {
private BuildingService buildingService;
public BuildingIdToBuildingConverter(BuildingService buildingService) {
this.buildingService = buildingService;
}
#Override
public Building convert (String id) {
return buildingService.getBuilding(id);
}
}
And register it:
public class AppConfig extends WebMvcConfigurerAdapter {
...
#Bean
public BuildingService buildingService(){
return new BuildingService();
}
#Override
public void addFormatters (FormatterRegistry registry) {
registry.addConverter(new BuildingIdToBuildingConverter(buildingService()));
}
}
Second, do this work manually by sending the building id in a separate parameter:
#RequestMapping(value = "admin/addApartment", method = RequestMethod.POST)
public String addContact(#ModelAttribute("apartment") Apartment apartment, #RequestParam("buildingId") String buildingId, BindingResult result, HttpServletRequest request, Map<String, Object> map) {
if (result.getErrorCount()==0){
if (apartment.getId()==0){
apartment.setBuilding(buildingService.getBuilding(buildingId));
apartmentService.addApartment(apartment);
}
}
else{
apartmentService.editApartment(apartment);
}
return "redirect:/admin/apartment.html";
}
map.put("buildingList", buildingService.listBuilding());
map.put("apartmentList", apartmentService.listApartment());
return "apartment";
}
And change your HTML accordingly to send the buildingId value.

Spring boot rest : Circular view path [error]: would dispatch back to the current handler URL [/error] again

My issue is I get 404 error when calling the spring boot application on localhost:8080/users
package com.myproj.users.controller;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.security.Principal;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.myproj.users.Greeting;
import com.myproj.users.PhysicalCharacteristicsRepository;
import com.myproj.users.UserRepository;
import com.myproj.users.UserResource;
#RestController
#RequestMapping("/users")
public class UserRestController {
private UserRepository userRepository;
private PhysicalCharacteristicsRepository characteristicsRepository;
#RequestMapping(value = "/greeting/", method = RequestMethod.GET)
public String greeting() throws UserPrincipalNotFoundException {
return "Greeting";
}
#RequestMapping(value = "/error/")
public String error() {
return "Error handling";
}
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody Greeting sayHello(#RequestParam(value = "name", required = false, defaultValue = "Stranger") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
#Autowired
UserRestController(UserRepository userRepository, PhysicalCharacteristicsRepository characteristicsRepository) {
this.userRepository = userRepository;
this.characteristicsRepository = characteristicsRepository;
}
}
package com.myproj.users.controller;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import org.springframework.hateoas.VndErrors;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.weather.exceptions.UserNotFoundException;
#ControllerAdvice
class UserControllerAdvice {
#ResponseBody
#ExceptionHandler(UserNotFoundException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
VndErrors userNotFoundExceptionHandler(UserNotFoundException ex) {
return new VndErrors("error", ex.getMessage());
}
#ResponseBody
#ExceptionHandler(UserPrincipalNotFoundException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
VndErrors userPrincipalNotFoundException(UserPrincipalNotFoundException ex) {
return new VndErrors("error", ex.getMessage());
}
}
package com.myproj.users;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
I have tested the spring project in https://spring.io/guides/gs/actuator-service/ and it worked so I ignore what's going on.
I have defined a controller to manage errors. I have copied it from Spring Boot Remove Whitelabel Error Page
The new Application class is the following :
package com.test;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#ComponentScan(basePackages = "com.test")
#EnableAutoConfiguration
#EnableJpaRepositories(basePackages = "com.test")
#EntityScan(basePackages = "com.test")
public class Application {
static final Logger logger = LogManager.getLogger(Application.class.getName());
public static void main(String[] args) {
logger.debug("Entered the application");
SpringApplication.run(Application.class, args);
}
private Application() {
}
}
As you can see I have added a controller in ComponentScan as follows :
#ComponentScan(basePackages = "com.test")
#EnableJpaRepositories(basePackages = "com.test")
#EntityScan(basePackages = "com.test")
To test I used curl curl http://localhost:9002/eleves/Hammami/ and firefox.
Changing #Controller to #RestController solved my issue.
In my case I was using thymeleaf(MVC), after that I switched to pure backend.

Resources