I want make simple web service using java spring restful web service .
I Use request Mapping annotation in controller class but when i run project there is no mapping there .
Here is controller Class :
import java.util.List;
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 guru.webservice.domain.Customer;
import guru.webservice.services.CustomerService;
#RestController
#RequestMapping(CustomerController.BASE_URL)
public class CustomerController {
public static final String BASE_URL = "api/v1/customers";
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
#GetMapping
List<Customer> getAllCustomers() {
return customerService.findAllCustomer();
}
#GetMapping("/{id}")
public Customer getCustomerById(#PathVariable Long id) {
return customerService.findCustomerById(id);
}
}
To let Spring scan and configure #Controller annotated classes, you need to configure component scanning on packages where controllers are stored.
i.e: /src/main/java/guru/webservices/spring/config/AppConfig.java
AppConfig.java:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableWebMvc //THIS
#ComponentScan(basePackages = "guru.services") //THIS
public class AppConfig {
}
Also:
#Autowired
private CustomerService customerService;
And then:
#GetMapping("/{id}")
public ResponseEntity getCustomerById(#PathVariable("id") Long id) {
Customer customer = customerDAO.get(id);
if (customer == null) {
return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
}
return new ResponseEntity(customer, HttpStatus.OK);
}
Related
I am aware that there are a lot of questions related to the same but none of them worked for some reason. Hence, posting the same and hoping to get some response.
I am trying to follow the SpingBoot application tutorial from Youtube and build the same application. But for some reason I get following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field postRepository in com.testingconverter.service.PostService required a bean of type 'com.testingconverter.repository.PostRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.testingconverter.repository.PostRepository' in your configuration.
Following are my classes:
Main SpringBootApplication class:
package com.testingconverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
public class TestingConverterApplication {
public static void main(String[] args) {
SpringApplication.run(TestingConverterApplication.class, args);
}
}
Controller class:
package com.testingconverter.controller;
import com.testingconverter.entities.PostEntity;
import com.testingconverter.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class BlogController {
#Autowired
private PostService postService;
#GetMapping(value = "/")
public String index() {
return "index";
}
#GetMapping(value = "/posts")
public List<PostEntity> posts() {
return postService.getAllPost();
}
#PostMapping(value = "/posts")
public void publishPost(#RequestBody PostEntity post) {
postService.insert(post);
}
}
My Entity class:
package com.testingconverter.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
#Entity
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
public class PostEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
private String body;
private Date date;
}
My Repository class:
package com.testingconverter.repository;
import com.testingconverter.entities.PostEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface PostRepository extends JpaRepository<PostEntity, Long> {
}
My Service class:
package com.testingconverter.service;
import com.testingconverter.entities.PostEntity;
import com.testingconverter.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class PostService {
#Autowired
private PostRepository postRepository;
public List<PostEntity> getAllPost() {
return postRepository.findAll();
}
public void insert(PostEntity post) {
postRepository.save(post);
}
}
I tried many things like adding the #ComponentScan etc but nothing seems to work for me. Can someone please explain to me what's going wrong here? How can I fix this?
Following is my project structure:
You excluding default database configuration. Remove that exclude part and add your database configuration in application properties files.
If you going to exclude then you have to create you datasource in configuration file.
#Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder =
DataSourceBuilder.create();
dataSourceBuilder.driverClassName("");
dataSourceBuilder.url("");
dataSourceBuilder.username("");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
I have tried to receive all the entries in a table as JSON objects, get request shows '200 OK' but it returns a [{}].
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Table(name = "man")
public class User {
#Id
#GeneratedValue
#Column(name = "man_id")
private Integer id;
#Column(name = "man_name")
private String name;
#Column(name = "salary")
private Double salary;
#Column(name = "reg")
private LocalDateTime dateTime;
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDAO extends JpaRepository<User,Integer> {
}
Service Layer
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService {
private final UserDAO userDAO;
#Autowired
public UserService(UserDAO userDAO) {
this.userDAO = userDAO;
}
public List<User> findAll(){
return userDAO.findAll();
}
}
Controller
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 java.util.List;
#RestController
#RequestMapping("/man")
public class UserControl {
private final UserService userService;
#Autowired
public UserControl(UserService userService) {
this.userService = userService;
}
#GetMapping("/all")
public List<User> findAll(){
return userService.findAll();
}
}
apllication.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: onionnetwork
jpa:
hibernate.dll-auto: update
generate: true
show-sql: true
Used Dependencies: starter-web , stater-jpa , mysql connector
NOTE: I'm currently learning spring boot through YouTube tutorials, so there will be some cringy programming practices.If you guys could help me with reviews and good resources to learn spring-boot, much appreciated. :)
I've done a simple list with sql server, but it doesn't show me the result, it just shows me the white page.
I have no error in the console. Will the sql server 2017 be? please any help?
connection to sql server 2017
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=DB_PRUEBA_V1;integratedSecurity=true
spring.jpa.show-sql=true
#spring.jpa.hibernate.ddl-auto=update
server.port=8090
package app
package app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ProyectoV2Application {
public static void main(String[] args) {
SpringApplication.run(ProyectoV2Application.class, args);
}
}
package model
package model;
import java.io.Serializable;
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
#Table(name = "TB_USERS")
public class Users implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "COD_USER")
private int codUser;
#Column(name = "NOM_USER")
private String nomUser;
#Column(name = "EMA_USER")
private String emUser;
public int getCodUser() {
return codUser;
}
public void setCodUser(int codUser) {
this.codUser = codUser;
}
public String getNomUser() {
return nomUser;
}
public void setNomUser(String nomUser) {
this.nomUser = nomUser;
}
public String getEmUser() {
return emUser;
}
public void setEmUser(String emUser) {
this.emUser = emUser;
}
}
package repository
package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import model.Users;
#Repository
public interface UserDAO extends JpaRepository<Users, Integer>{
}
service
package service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import model.Users;
import repository.UserDAO;
#Service
public class UserService {
#Autowired
private UserDAO dao;
public List<Users> lista(){
return dao.findAll();
}
}
package controller
package controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import model.Users;
import service.UserService;
#RestController
#RequestMapping(value = "/CrudUsers")
public class UserController {
#Autowired
private UserService us;
#ResponseBody
#GetMapping(path = "/lista", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Users> lista(){
return us.lista();
}
}
Whitelabel Error Page
Because you created each class in different package like below,
app --> ProyectoV2Application
model --> Users
repository --> UserDAO
service --> UserService
controller --> UserController
But spring boot scans the classes that are either in root package or in sub package of root package, so move all these classes into sub packages of root package
app --> ProyectoV2Application
app.model --> Users
app.repository --> UserDAO
app.service --> UserService
app.controller --> UserController
I'm new to spring boot and I can't get an example from my spring boot book to work. Here is the code
Description:
Parameter 0 of constructor in Thomas.ChapterController required a bean of >type 'Thomas.ChapterRepository' that could not be found.
Action:
Consider defining a bean of type 'Thomas.ChapterRepository' in your configuration.
Chapter.java
package Thomas;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Data
#Document
public class Chapter {
#Id /*tells mongodb that this will be the primary key for Mongo Document */
private String Id;
private String name;
public Chapter(String name) {
this.name = name;
}
}
ChapterRepository.java
package Thomas;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
public interface ChapterRepository extends ReactiveCrudRepository<Chapter, String> {
}
LoadDatabase.Java
package Thomas;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Flux;
import org.springframework.context.annotation.Configuration;
#Configuration /* Marks this class as a source of beans */
public class LoadDatabase {
#Bean /* Indicates that the return value of init is a Spring Bean */
CommandLineRunner init(ChapterRepository repository) {
return args -> {
Flux.just (
new Chapter("Quick Start With Java"),
new Chapter("Reactive Web With Spring Boot"),
new Chapter("...and More!"))
.flatMap(repository::save)
.subscribe(System.out::println);
};
}
}
ChapterController.java
package Thomas;
import reactor.core.publisher.Flux;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ChapterController {
private final ChapterRepository repository;
public ChapterController(ChapterRepository repository)
{
this.repository = repository;
}
#GetMapping("/chapters")
public Flux<Chapter> listing() {
return repository.findAll();
}
}
ThomasSpringApplication.java
package Thomas;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ThomasSpringApplication {
public static void main(String [] args) {
SpringApplication.run(ThomasSpringApplication.class, args);
}
}
Figured out i was pulling in the wrong dependencies in my pom.xml
My UserController class:
package org.peronalitymeet.controller;
import org.peronalitymeet.entity.User;
import org.peronalitymeet.entity.request.AddUserRequest;
import org.peronalitymeet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import java.util.List;
#RestController
public class UserController {
private UserRepository userRepository;
#Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(value="/users", method = RequestMethod.GET)
public List<User> findAllUsers(){
return userRepository.findAll();
}
#RequestMapping(value="/signup", method = RequestMethod.POST)
public void addUser(#RequestBody AddUserRequest addUserRequest){
User user = new User();
user.setFirstname(addUserRequest.getFirstname());
user.setSurname(addUserRequest.getSurname());
userRepository.save(user);
}
}
My problem is that now if i open the localhost:8080/users URL,
i will get all my users within JSON format. Previously i followed a Spring mvc tutorial, and there they used ModelAndView method to automatically open a jsp page if an URL was called.
Is there any way to use FindAll Users() and at the same time open a jsp or html page and list the result of the method within that?
#RestController is a meta-annotation that tells Spring to return the text that it gets back as-is to the user. It's equivalent to adding #ResponseBody #Controller to your class.
If you want to do something with a JSP, your class should look something like what I have below. I am only changing the /users endpoint, but the idea would apply everywhere.
package org.peronalitymeet.controller;
import org.peronalitymeet.entity.User;
import org.peronalitymeet.entity.request.AddUserRequest;
import org.peronalitymeet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
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.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
#Controller
public class UserController {
private UserRepository userRepository;
#Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(value="/users", method = RequestMethod.GET)
public ModelAndView findAllUsers(ModelAndView mav){
List<User> users = userRepository.findAll();
mav.addObject("users", users);
mav.setViewName("users");
return mav;
}
#ResponseBody
#RequestMapping(value="/signup", method = RequestMethod.POST)
public void addUser(#RequestBody AddUserRequest addUserRequest){
User user = new User();
user.setFirstname(addUserRequest.getFirstname());
user.setSurname(addUserRequest.getSurname());
userRepository.save(user);
}
}
Then set up your view page called users.jsp to display the items in the users variable and you should be set.