it's my swagger Config file
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
#Configuration
#EnableSwagger2
public class SwaggerConfiguration {
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("example.com"))
.paths(regex("/product.*"))
.build()
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfo(
"Spring Boot REST API",
"Spring Boot REST API for Online",
"1.0",
"Terms of service",
new Contact("Example Example", "https://springframework.guru/about/", "example#gmail.com"),
"Apache License Version 2.0",
"https://www.apache.org/licenses/LICENSE-2.0");
}
}
Student Controller
import java.util.List;
import java.util.Optional;
import com.example.learnspring.StudentRepository.StudentRepository;
import com.example.learnspring.model.StudentDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
public class StudentController {
#Autowired
private StudentRepository eRepo;
#PostMapping("/employees")
public StudentDto save (#RequestBody StudentDto employee) {
return eRepo.save(employee);
}
//#RequestMapping("/greeting/{lang}")
#RequestMapping(value = "/greeting/{lang}", method = RequestMethod.GET)
#GetMapping("/student")
public List<StudentDto> get () {
return eRepo.findAll();
}
#GetMapping("/student/{id}")
public StudentDto get (#PathVariable int id) {
Optional<StudentDto> employee = eRepo.findById(id);
if (employee.isPresent()) {
return employee.get();
}
throw new RuntimeException("Not found for the id "+id);
}
#PutMapping("/student/{id}")
public StudentDto update (#PathVariable int id, #RequestBody StudentDto employee) {
employee.setId(id);
return eRepo.save(employee);
}
#DeleteMapping("/student/{id}")
public ResponseEntity<HttpStatus> delete (#PathVariable int id) {
eRepo.deleteById(id);
return new ResponseEntity<HttpStatus>(HttpStatus.NO_CONTENT);
}
}
StudentDTO class
import lombok.*;
import lombok.experimental.FieldDefaults;
import javax.persistence.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "student")
#Setter
#Getter
#NoArgsConstructor
#Data
#FieldDefaults(level= AccessLevel.PRIVATE)
public class StudentDto {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false)
private int id;
#Column(name = "name")
#NotNull(message = "Name cannot be null")
private String name;
#Column(name = "age")
#NotNull(message = "Age cannot be null")
#Min(value = 15, message = "Age should not be less than 15")
#Max(value = 65, message = "Age should not be greater than 65")
private int age;
public String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
public int getAge() {
return age;
}
public void setAge(int age){
this.age=age;
}
}
My Repository
import com.example.learnspring.model.StudentDto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository extends JpaRepository<StudentDto, Integer> {
}
Myapplication class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#SpringBootApplication
#EnableSwagger2
public class LearnSpringApplication {
public static void main(String[] args) {
SpringApplication.run(LearnSpringApplication.class, args);
}
}
application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver
server.port=9090
spring.jpa.hibernate.ddl-auto=update
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>LearnSpring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>LearnSpring</name>
<description>LearnSpring</description>
<properties>
<java.version>18</java.version>
<swagger.version>3.0.0</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--springfox dependencies for api documentations in swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.ivy</groupId>
<artifactId>ivy</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.project-lombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
When I run this application everything looks fine but I can't see the POST/PUT/or DELETE. I try to many things I find from Internet but it doesn't work. I new on this topic. I actually want to wrote null inputs and get exceptions for exception handling.
So your Docket Configuration has specified a regex pattern for product
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("example.com"))
.paths(regex("/product.*"))
.build()
.apiInfo(metaData());
}
But your controllers don't have any APIs with /product.
Thus you're not able to see APIs in swagger documentation.
Try with below configuration and see if it shows you all endpoints and then start working around regex configurations.
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
Above configuration matches all the API paths in your web application basically anywhere.
You can access your APIs at
Change the APPLICATION_PORT and CONTEXT-PATH
http://localhost:{{APPLICATION_PORT}}/{{CONTEXT-PATH}}/swagger-ui.html
Related
northwind/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>anilacar</groupId>
<artifactId>northwind</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>northwind</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>19.0.1</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Product.java
package anilacar.northwind.entities.concretes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
#Data
#Entity
#Table(name = "products")
public class Product {
#Id //işlemleri primary keye göre yapar #Id olarak belirtmeliyiz
#GeneratedValue //sıralama işlemi için numaraları
#Column(name="product_id")
private int id ;
#Column(name="category_id")
private int categoryId;
#Column(name="product_name")
private String productName;
#Column(name="unit_price")
private double unitPrice ;
#Column(name="unit_in_stock")
private Integer unitsInStock;
#Column(name="quantity_per_unit")
private String quantityPerUnit;
public Product() {
}
public Product(int id, int categoryId, String productName, double unitPrice, Integer unitsInStock,
String quantityPerUnit) {
super();
this.id = id;
this.categoryId = categoryId;
this.productName = productName;
this.unitPrice = unitPrice;
this.unitsInStock = unitsInStock;
this.quantityPerUnit = quantityPerUnit;
}
}
ProductDao.java
package anilacar.northwind.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import anilacar.northwind.entities.concretes.Product;
public interface ProductDao extends JpaRepository<Product, Integer>{
}
ProductsController.java
ProductManager.java
package anilacar.northwind.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import anilacar.northwind.business.abstracts.ProductService;
import anilacar.northwind.dataAccess.abstracts.ProductDao;
import anilacar.northwind.entities.concretes.Product;
#Service
public class ProductManager implements ProductService {
private ProductDao productDao;
#Autowired
public ProductManager(ProductDao productDao) {
super();
this.productDao = productDao;
}
#Override
public List<Product> getAll() {
return this.productDao.findAll();
}
}
ProductsController.java
package anilacar.northwind.api.controllers;
import java.util.List;
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;
import anilacar.northwind.business.abstracts.ProductService;
import anilacar.northwind.entities.concretes.Product;
#RestController
#RequestMapping("api/products")
public class ProductsController {
private ProductService productService;
#Autowired
public ProductsController(ProductService productService) {
super();
this.productService = productService;
}
#GetMapping("/getall")
public List<Product> getAll(){
return this.productService.getAll();
}
}
How can ı fix this problem . Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null .
This is a simple code that i got from youtube for practice. well i did the code correcly but i cant get the explicit mapping correclty, that what the 404 error in the postman says.
I don't know if its my Spring boot app problem or the code error. please have a look at this , Since spring boot is not giving a proper answer.
//CONTROLLER
#Slf4j
#RestController
#RequestMapping("/api/v1")
public class RestuController {
#Autowired
private RestuService restuService;
/////////////////////////////////////POST MAPPING//////////////////////////////////////////////////////////////////////
#PostMapping("/POST/save")
Restaurant addRestaurant(#RequestBody Restaurant restaurant) {
return restuService.saveRestu(restaurant);
}
#PostMapping("/POST/saves")
List<Restaurant> addRestaurants(#RequestBody List<Restaurant> restaurants) {
return restuService.saveRestaurants(restaurants);
}
#GetMapping("/GET/resturants")
List<Restaurant> findAllRestaurants(){
log.debug("reached /GET/resturants");
return restuService.getRestaurants();
}
#GetMapping("/GET/{id}")
Restaurant findRestaurantById(#PathVariable int id) {
log.debug("reached /GET/{id} :" + id);
return restuService.getRestaurantById(id);
}
#GetMapping("/GET/{name}")
Restaurant findRestaurantByName(#PathVariable String name) {
log.debug("reached /GET/{name}:" + name);
return restuService.getRestaurantByname(name);
}
#GetMapping("/GET/{dist}")
List<Restaurant> findRestaurantByDist(#PathVariable int distance) {
log.debug("reached /GET/{dist} :" + distance);
return restuService.getRestaurantbyDist(distance);
}
#GetMapping("/GET/{loc}")
List<Restaurant> findRestaurantByLocation(#PathVariable String location) {
log.debug("reached /GET/{loc} : " + location);
return restuService.getRestaurantbyLocation(location);
}
#GetMapping("/GET/{cuisine}")
List<Restaurant> findRestaurantByCuisine(#PathVariable String cuisine) {
log.debug("reached /GET/{cuisine} : " + cuisine);
return restuService.getRestaurantbyCuisine(cuisine);
}
#GetMapping("/GET/{budget}")
List<Restaurant> findRestaurantByBudget(#PathVariable int budget) {
log.debug("reached /GET/{Budget} : " + budget);
return restuService.getRestaurantbyBudget(budget);
}
}
//SERVICE
package SERVICE;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ENTITY.Restaurant;
import REPOSITORY.RestuRepository;
#Service
public class RestuService {
#Autowired
RestuRepository restuRepository;
///////////////////postmethods//////////////////////////////////////
public Restaurant saveRestu(Restaurant restaurant) {
return restuRepository.save(restaurant);
}
public List<Restaurant> saveRestaurants(List<Restaurant> restaurants) {
return restuRepository.saveAll(restaurants);
}
///////////////////////////////////////////////////////////////////////////////////////
//////////////////GET METHODS//////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
public List<Restaurant> getRestaurants(){
return restuRepository.findAll();
}
public Restaurant getRestaurantById(int id){
return restuRepository.findById(id).orElse(null);
}
public Restaurant getRestaurantByname(String name){
return restuRepository.findByName(name);
}
public List<Restaurant> getRestaurantbyDist(int distance){
return restuRepository.findByDist(distance);
}
public List<Restaurant> getRestaurantbyLocation(String location){
return restuRepository.findByLocation(location);
}
public List<Restaurant> getRestaurantbyCuisine(String cuisine){
return restuRepository.findBycuisine(cuisine);
}
public List<Restaurant> getRestaurantbyBudget(int budget){
return restuRepository.findBybudget(budget);
}
}
//REPOSITORY
package REPOSITORY;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ENTITY.Restaurant;
#Repository
public interface RestuRepository extends JpaRepository<Restaurant, Integer> {
Restaurant findByName(String name);
List<Restaurant> findByDist(int distance);
List<Restaurant> findByLocation(String location);
List<Restaurant> findBycuisine(String cuisine);
List<Restaurant> findBybudget(int budget);
}
//ENTITY OR MODEL CLASS
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "restaurant_tbl")
public class Restaurant {
#Id
#GeneratedValue
private int id;
private String name;
private String cuisine;
private String location;
private int distance;
private int budget;
}
//APPLICATION.PROPERTIES
server.port = 6282
spring.datasource.dbcp2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url =jdbc:mysql://localhost:3306/restaurants
spring.datasource.username = root
spring.datasource.password = ****
spring.jpa.show-sql =true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
//POM.XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sangamam</groupId>
<artifactId>RESTAURANT-SERVICE</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RESTAURANT-SERVICE</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
here is my UserController class
package ritu.login;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
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.RestController;
#RestController
#Configuration
#RequestMapping("/vs1")
public class UserController {
#Autowired
UserService userService;
#GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
#GetMapping("/user/{id}")
private User getUser(#PathVariable("id") long id) {
return userService.getUserById(id);
}
#DeleteMapping("/user/{id}")
public void deleteUser(#PathVariable("id") long id) {
userService.delete(id);
}
#PostMapping("/users")
public long saveUser(#RequestBody User user) {
userService.saveOrUpdate(user);
return user.getId();
}
#PutMapping("/users")
public User Update(#RequestBody User users) {
userService.saveOrUpdate(users);
return users;
}
}
Here is UserService class
package ritu.login;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserService {
#Autowired
UserRepository userRepository;
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
userRepository.findAll().forEach(user1 -> users.add(user1));
return users;
}
public User getUserById(long id) {
return userRepository.findById(id).get();
}
public void saveOrUpdate(User users) {
userRepository.save(users);
}
public void delete(long id) {
userRepository.deleteById(id);
}
public void update(User users, long id) {
userRepository.save(users);
}
}
here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>ritu.login</groupId>
<artifactId>login-register</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>login-register</name>
<description>login example</description>
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.30</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
here is my url in postman
http://localhost:8080/vs1/users
It gives error of 404 Not found..what should i do?
here is Pojo class
package ritu.login;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
#Entity
#ManagedBean(name = "loginBean")
#SessionScoped
#Component
public class User implements Serializable{
private static final long serialVersionUID = -7250065889869767422L;
#Id
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String validate(Long id,String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/any", "root", "jaygurudev1#");
PreparedStatement ps = con.prepareStatement("Select id,name from user where id=? and name=?");
ps.setLong(1, id);
ps.setString(2, name);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return "hello.xhtml";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Passowrd", "Please enter correct username and Password"));
return "index";
}
} catch (Exception e) {
System.out.println("in exception");
}
return null;
}
}
i saw some tutorial on javatpoint and other website but still the issue can't get solved.
what am i missing in the code or any version related issues?
IT GIVES 404 ERROR,WHILE HITTING URL
since,eclipse is showing error i have to add annotation.api jar in build path after that i have removed spring security dependency from pom.xml and it totally works
I have this Problem with Spring-boot
When Run the Server cannot run
APPLICATION FAILED TO START
Description:
Field book in com.example.BookProject.Servies.BookServies required a bean named 'book' 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 named 'book' in your configuration.
My pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.BookProject</groupId>
<artifactId>BookProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Book</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
And My Entity Class
package com.example.BookProject.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="book")
public class Book {
#Id
private String id;
#Column(unique = true,nullable = false ,name = "BookTitle")
private String title;
#Column(name = "BookDecription",unique = false, nullable = true)
private String Decription;
public Book() {
super();
}
public Book(String id, String title, String decription) {
super();
this.id = id;
this.title = title;
Decription = decription;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDecription() {
return Decription;
}
public void setDecription(String decription) {
Decription = decription;
}
}
My repository:
package com.example.BookProject.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.BookProject.Model.Book;
#Repository
public interface BookRepo extends JpaRepository<Book, String> {
}
My Servies:
package com.example.BookProject.Servies;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.BookProject.Model.Book;
import com.example.BookProject.Repository.BookRepo;
#Service
#Transactional
public class BookServies {
//i am inject BookRepo Here
#Autowired
public BookRepo book;
//find all Book
public List<Book> FindAllBook(){
return book.findAll();
}
//find ById Book
public Book FindById(String id)
{
return book.findById(id).get();
}
//Add new Book
public void AddBook(Book newBook) {
book.save(newBook);
}
public void DeleteBook(String id) {
book.deleteById(id);
}
}
My Controller:
package com.example.BookProject.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.BookProject.Model.Book;
import com.example.BookProject.Servies.BookServies;
#RestController
#RequestMapping(value = "api/book")
public class BookController {
//inject servies
#Autowired
private BookServies book;
//find all book
#GetMapping(value = "/allBook")
public List<Book> AllBook(){
return book.FindAllBook();
}
//Add New Book Method
#PostMapping(value = "/addBook")
public void AddBook(#RequestBody Book NewBook)
{
book.AddBook(NewBook);
}
//Find Book By Id
#GetMapping(value = "bookId/{id}")
public Book FindBook(#PathVariable String id)
{
return book.FindById(id);
}
//DeleteBook By Id
#GetMapping(value = "/deleteId/{id}")
public void DeleteBook(#PathVariable String id)
{
book.DeleteBook(id);
}
}
The issue is due to dependency conflict, spring-boot-starter-data-jpa dependency is enough, because hibernate-core 5.X.X Final version is included.
From the above image I hope you understood the issue,
Solution:
Removed unwanted dependencies and resolved the conflict
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
After removed the unwanted dependencies application is up,
[2m2021-01-09 02:47:53.923[0;39m [32m INFO[0;39m [35m14703[0;39m
[2m---[0;39m [2m[ main][0;39m
[36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m
Tomcat started on port(s): 8080 (http) with context path ''
[2m2021-01-09 02:47:53.926[0;39m [32m INFO[0;39m [35m14703[0;39m
[2m---[0;39m [2m[ main][0;39m
[36mcom.knf.dev.mockito.DemoApplication [0;39m [2m:[0;39m Started
DemoApplication in 1.927 seconds (JVM running for 2.316)
I need you because #CROSSOrigin doesn't work and i don't understand why, you have my code here. In fact, i use WebService but i have a problem with the 'Acess-Control-Allow-Origin" i tried all but nothing had worked, please help me !!
SPRING BOOT Project with version 2.1.2 and i would like to build a REST API for ANGULAR 7
PROBLEM:
zone.js:3243 GET http://localhost:8080/apiEquipment/equipments 404
localhost/:1 Access to XMLHttpRequest at 'http://localhost:8080/apiEquipment/equipments' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
zone.js:3243 XHR failed loading: GET "http://localhost:8080/apiEquipment/equipments".
core.js:15714 ERROR
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8080/apiEquipment/equipments", ok: false, …}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>GoSecuriServices</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GoSecuriServices</name>
<description>Rest API for GoSecuri Application</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application.java
package com.example.GoSecuriServices;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories("com.example.GoSecuriServices.repository")
#EntityScan("com.example.GoSecuriServices.model")
#ComponentScan
#SpringBootApplication
public class GoSecuriServicesApplication {
public static void main(String[] args) {
SpringApplication.run(GoSecuriServicesApplication.class, args);
}
}
Equipment.java (my table)
package model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
#Entity
#Table(name = "Equipment")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public class Equipment {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Equipment_id;
#NotBlank
private String EquipmentName;
#NotBlank
private Integer Nb;
// Getters and Setters
public Long getEquipment_id() {
return this.Equipment_id;
}
public void SetEquipment_id(Long id) {
this.Equipment_id = id;
}
public String getEquipmentName() {
return this.EquipmentName;
}
public void setEquipmentName(String name) {
this.EquipmentName = name;
}
public Integer getNb() {
return this.Nb;
}
public void setNb(Integer nb) {
this.Nb = nb;
}
}
EquipmentRepository.java
package repository;
import model.Equipment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface EquipmentRepository extends JpaRepository<Equipment, Long> {
}
EquipmentController.java
package controller;
import exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import model.Equipment;
import repository.EquipmentRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
#RestController
#CrossOrigin(origins = "*", allowedHeaders = "*", maxAge = 3600)
#RequestMapping("/apiEquipment")
public class EquipmentController {
#Autowired
EquipmentRepository equipmentRepository;
#RequestMapping(value= "/apiEquipment/**", method=RequestMethod.OPTIONS)
public void corsHeaders(HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
response.addHeader("Access-Control-Max-Age", "3600");
}
// Get all equipments
#GetMapping("/equipments")
public List<Equipment> getAllEquipments() {
return equipmentRepository.findAll();
}
// Create new equipment
#PostMapping("/equipments")
public Equipment createEquipment(#Valid #RequestBody Equipment equipment) {
return equipmentRepository.save(equipment);
}
// Get a single equipment
#GetMapping("/equipments/{id}")
public Equipment getEquipmentById(#PathVariable(value = "id") Long equipmentId) {
return equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));
}
// Update a Equipment
#PutMapping("/equipments/{id}")
public Equipment updateNote(#PathVariable(value = "id") Long equipmentId,
#Valid #RequestBody Equipment equipmentDetails) {
Equipment equipment = equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));
equipment.setEquipmentName(equipmentDetails.getEquipmentName());
equipment.setNb(equipmentDetails.getNb());
Equipment updatedEquipment = equipmentRepository.save(equipment);
return updatedEquipment;
}
// Delete a Equipment
#DeleteMapping("/equipments/{id}")
public ResponseEntity<?> deleteEquipment(#PathVariable(value = "id") Long equipmentId) {
Equipment equipment = equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));
equipmentRepository.delete(equipment);
return ResponseEntity.ok().build();
}
}
Did you read the CORS Support section in Spring Documentation?
You can also try to use Spring Higher-Order Components and #EnableCORS or if you don't want to use additional dependency use #Bean from here
You need to configure a web cross-domain configuration as follows:
package com.liukai.routermanagement.config;
import com.liukai.routermanagement.interceptor.LoginHandlerInterceptor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
#SpringBootConfiguration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login","/router/login","/user/registered");
super.addInterceptors(registry);
}
// this main mothod,Just add this method
#Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET","POST","PUT","DELETE");
super.addCorsMappings(registry);
}
}