No mapping for GET /WEB-INF/pages/patients.jsp - java

I'm currently developing crud web-application with spingboot and hibernate, and experiencing difficulties with displaying pages in browser (returns "page not found" 404 error and no mapping warning in Spring log). For some reason I also cannot preview jsp-pages as Idea states that "There is no configured/running web-servers found!" even tough spring-web has embedded Tomcat server.
Webconfig:
package testgroup.private_clinic.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages ="testgroup.private_clinic")
public class Webconfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/res/**").addResourceLocations("/res/");
}
#Bean
ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setSuffix(".jsp");
viewResolver.setPrefix("/WEB-INF/pages/");
return viewResolver;
}
}
AppInitializer:
package testgroup.private_clinic.config;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{HibernateConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{Webconfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] {characterEncodingFilter};
}
}
Controller:
package testgroup.private_clinic.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import testgroup.private_clinic.model.Patient;
import testgroup.private_clinic.service.PatientService;
import java.util.List;
#Controller
public class PatientController {
PatientService patientService;
#Autowired
public void setPatienceService(PatientService patientService){
this.patientService = patientService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView allPatients(){
List<Patient> patients = patientService.allPatients();
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("patients");
modelAndView.addObject("patientList", patients);
return modelAndView;
}
#RequestMapping(value= "/edit{id}", method = RequestMethod.GET)
public ModelAndView editPage(#PathVariable("id") int id){
Patient patient = patientService.getByID(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("editPage");
modelAndView.addObject("patient", patient);
return modelAndView;
}
#RequestMapping(value="/edit", method = RequestMethod.POST)
public ModelAndView editPatient(#ModelAttribute("patient") Patient patient){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:/");
patientService.edit(patient);
return modelAndView;
}
}
Pom-file:
<?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>
<groupId>testorg</groupId>
<artifactId>private_clinic</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.28.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
Spring log:
2021-03-06 02:46:33.941 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : Starting SpringBootClass on DESKTOP-96Q7T8E with PID 13956 (C:\Users\Anton\IdeaProjects\Private_clinic_temp\target\classes started by Anton in C:\Users\Anton\IdeaProjects\Private_clinic_temp)
2021-03-06 02:46:33.943 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : No active profile set, falling back to default profiles: default
2021-03-06 02:46:34.712 INFO 13956 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-03-06 02:46:34.719 INFO 13956 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-06 02:46:34.719 INFO 13956 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-03-06 02:46:34.793 INFO 13956 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-06 02:46:34.793 INFO 13956 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 820 ms
2021-03-06 02:46:34.900 INFO 13956 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.28.Final
2021-03-06 02:46:34.995 INFO 13956 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-03-06 02:46:35.107 INFO 13956 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL9Dialect
2021-03-06 02:46:35.506 INFO 13956 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-03-06 02:46:35.748 INFO 13956 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-03-06 02:46:35.756 INFO 13956 --- [ main] t.private_clinic.SpringBootClass : Started SpringBootClass in 2.044 seconds (JVM running for 2.527)
2021-03-06 02:46:48.864 INFO 13956 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-03-06 02:46:48.864 INFO 13956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-03-06 02:46:48.868 INFO 13956 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Hibernate: select patient0_.id as id1_0_0_, patient0_.adress as adress2_0_0_, patient0_.diagnosis as diagnosi3_0_0_, patient0_.patient_name as patient_4_0_0_, patient0_.patient_patronimic as patient_5_0_0_, patient0_.status as status6_0_0_, patient0_.patient_surname as patient_7_0_0_ from patients patient0_ where patient0_.id=?
2021-03-06 02:46:48.991 WARN 13956 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping for GET /WEB-INF/pages/editPage.jsp
Main Class:
package testgroup.private_clinic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class)
public class SpringBootClass extends SpringBootServletInitializer {
public static void main(String[] args){
SpringApplication.run(SpringBootClass.class, args);
}
}

Related

How to put multiple values into a json in java

I'm trying to return a list of values from JDBC but multiple columns of the database to solve this I just made a JSON object to make something like this
{
"Results 1": {
"IP": "192.168.1.2",
"Port": "13442",
"Domain": "google.com"
},
"Results 2": {
"IP": "192.168.1.2",
"Port": "13442",
"Domain": "google.com"
}
}
The issue is im getting this error WARN 43953 --- [nio-1900-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
What I've tried
I've tried using a hash map but it doesn't work and I don't even know if it can return the value like a want it.
What I hope
I hope at the end I can get a list of values similar to the way I showed above, all separate. This is to be displayed on HTML later so if I'm doing something i shouldn't also let me know
This is my code
package com.mchugo.que.McHugoQue.Controller;
import com.mchugo.que.McHugoQue.Models.ConnectionDetails;
import com.mchugo.que.McHugoQue.Models.SearchCredential;
import com.mysql.cj.xdevapi.JsonArray;
import org.json.JSONObject;
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.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
#RestController
public class ApiController {
#RequestMapping(value={"/search/credential", "xyz"}, method={RequestMethod.POST,RequestMethod.PUT, RequestMethod.GET})
public JsonArray searchCredential(#RequestBody SearchCredential searchCredential){
Connection connection = null;
Statement st = null;
ResultSet rs = null;
String Username = searchCredential.getUsername();
//grabs connection details
ConnectionDetails connectionDetails = new ConnectionDetails();
String username = "";
String password = "";
JsonArray array = new JsonArray();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + connectionDetails.getHost() + "/" + connectionDetails.getDatabase(), connectionDetails.getUsername(), connectionDetails.getPassword());
Statement statement = con.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM credentials WHERE identifier = '" + Username + "'");
while(res.next()){
JSONObject data = new JSONObject();
username = res.getString("identifier");
password = res.getString("password");
data.put("Username", username);
data.put("Password", password);
array.add(data);
}
}
catch(Exception ex){
System.out.println("Exception : " + ex.toString());
}
System.out.println(array);
return(array);
}
}
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.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mchugo.que</groupId>
<artifactId>McHugoQue</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>McHugoQue</name>
<description>Que for sending data to email for the compermised passwords</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
<version>0.0.20131108.vaadin1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.6.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml.ws/jaxws-api -->
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.10.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
What I tried
HashMap<String, String> data = new HashMap<>();
for(int i = 0; i <= 10; i++){
HashMap<String, String> data1 = new HashMap<>();
data1.put("IP", i + "");
data1.put("PORT", i + 1 + "");
data.put("value " + i, data1);
}
System.out.println(data);
Traceback
2022-04-15 13:22:08.415 INFO 43953 --- [ main] c.m.que.McHugoQue.McHugoQueApplication : Starting McHugoQueApplication using Java 16.0.1 on Macbook-Air.lan with PID 43953 (/Volumes/Drive/FiverrWork/untitled folder/McHugoQue/target/classes started by danielcaminero in /Volumes/Drive/FiverrWork/untitled folder/McHugoQue)
2022-04-15 13:22:08.419 INFO 43953 --- [ main] c.m.que.McHugoQue.McHugoQueApplication : No active profile set, falling back to 1 default profile: "default"
2022-04-15 13:22:10.677 INFO 43953 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 1900 (http)
2022-04-15 13:22:10.698 INFO 43953 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-04-15 13:22:10.698 INFO 43953 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2022-04-15 13:22:10.852 INFO 43953 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-04-15 13:22:10.852 INFO 43953 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2295 ms
2022-04-15 13:22:11.513 INFO 43953 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 1900 (http) with context path ''
2022-04-15 13:22:11.535 INFO 43953 --- [ main] c.m.que.McHugoQue.McHugoQueApplication : Started McHugoQueApplication in 4.137 seconds (JVM running for 5.008)
2022-04-15 13:22:21.712 INFO 43953 --- [nio-1900-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-15 13:22:21.712 INFO 43953 --- [nio-1900-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-04-15 13:22:21.713 INFO 43953 --- [nio-1900-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
{"Value 1":{"Username":"johnsen#cityeyes.dk","Password":"nodea03"}}
2022-04-15 13:22:22.181 WARN 43953 --- [nio-1900-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
You should work with a List instead putting the values inside an object and increasing the counter variable. I would suggest you use something like this
....
//grabs connection details
ConnectionDetails connectionDetails = new ConnectionDetails();
String username = "";
String password = "";
JSONArray array = new JSONArray();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + connectionDetails.getHost() + "/" + connectionDetails.getDatabase(), connectionDetails.getUsername(), connectionDetails.getPassword());
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM credentials WHERE identifier = '" + Username + "'");
while(res.next()){
JSONObject data = new JSONObject();
String username = res.getString("identifier");
String password = res.getString("password");
data.put("Username", username);
data.put("Password", password);
array.add(data);
}
}
catch(Exception ex){
System.out.println("Exception : " + ex.toString());
}
System.out.println(data);
return(data);
Your output will look slightly different.
[
{
"Username: "firstUserName",
"Password": "somePass"
},
{
"Username: "secondUserName",
"Password": "someOtherPass"
}
]
It is however better to work with lists/arrays. Otherwise you wold have to access your result by incrementing variables until an error is thrown or something like this.

Whitelabel error when i try make to make a get from database

I am trying to make a small rest-api in springboot but i always get this errorerror 404
It is connected to a database but when I try to exceute a GET from Post I also have 404 error
This is my structure
project structure
My pom
<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.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>Clientix</groupId>
<artifactId>Ruben_DeNicolas</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Clientix</name>
<description>TFG</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-web</artifactId>
</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>
Repository
package repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import models.ClientesModel;
#Repository
public interface ClientesRepository extends CrudRepository<ClientesModel, Integer>{
}
Service
package services;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import models.ClientesModel;
import repositories.ClientesRepository;
#Service
public class ClientesService {
#Autowired
ClientesRepository clientesRepository;
public ArrayList<ClientesModel>getClientes()
{
return(ArrayList<ClientesModel>)clientesRepository.findAll();
}
public ClientesModel insert(ClientesModel c)
{
return clientesRepository.save(c);
}
}
Model
package models;
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 = "clientes")
public class ClientesModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(unique = true, nullable = false)
private Integer idCliente;
private String NombreCliente;
private String CIFNIF;
private String DireccionFacturacion;
public ClientesModel(String NombreCliente) {
this.NombreCliente = NombreCliente;
}
public ClientesModel(int idCliente, String NombreCliente, String CIFNIF, String DireccionFacturacion) {
this.idCliente = idCliente;
this.NombreCliente = NombreCliente;
this.CIFNIF = CIFNIF;
this.DireccionFacturacion = DireccionFacturacion;
}
public Integer getIdCliente() {
return idCliente;
}
public void setIdCliente(Integer idCliente) {
this.idCliente = idCliente;
}
public String getNombreCliente() {
return NombreCliente;
}
public void setNombreCliente(String nombreCliente) {
NombreCliente = nombreCliente;
}
public String getCIFNIF() {
return CIFNIF;
}
public void setCIFNIF(String cIFNIF) {
CIFNIF = cIFNIF;
}
public String getDireccionFacturacion() {
return DireccionFacturacion;
}
public void setDireccionFacturacion(String direccionFacturacion) {
DireccionFacturacion = direccionFacturacion;
}
}
Controller
package controllers;
import java.util.ArrayList;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import models.ClientesModel;
import services.ClientesService;
#RestController
#RequestMapping(value = "/clientes",produces="application/json")
public class ClientesController {
#Autowired
ClientesService clientesService;
//OBTENER TODOS LOS CLIENTES
//#RequestMapping(value = "/",method = RequestMethod.GET)
#GetMapping()
public ArrayList<ClientesModel> getClientes()
{
return clientesService.getClientes();
}
//INSTERTAR CLIENTE
#PostMapping
public ClientesModel insert(#RequestBody ClientesModel c)
{
return this.clientesService.insert(c);
}
}
```
Clientix application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan()
public class ClientixApplication {
public static void main(String[] args) {
SpringApplication.run(ClientixApplication.class, args);
}
}
This is the SpringBoot log
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.6)
2022-04-06 16:05:32.098 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : Starting ClientixApplication using Java 17.0.2 on DESKTOP-0EJNGE1 with PID 15728 (C:\Users\Rubén\Desktop\TestSpringBoot\Ruben_DeNicolas (1)\Ruben_DeNicolas\target\classes started by Rubén in C:\Users\Rubén\Desktop\TestSpringBoot\Ruben_DeNicolas (1)\Ruben_DeNicolas)
2022-04-06 16:05:32.101 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : No active profile set, falling back to 1 default profile: "default"
2022-04-06 16:05:32.373 INFO 15728 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-04-06 16:05:32.381 INFO 15728 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 2 ms. Found 0 JPA repository interfaces.
2022-04-06 16:05:32.627 INFO 15728 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-04-06 16:05:32.632 INFO 15728 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-04-06 16:05:32.632 INFO 15728 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60]
2022-04-06 16:05:32.692 INFO 15728 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-04-06 16:05:32.692 INFO 15728 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 569 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2022-04-06 16:05:32.784 INFO 15728 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-04-06 16:05:32.810 INFO 15728 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.7.Final
2022-04-06 16:05:32.893 INFO 15728 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-04-06 16:05:32.945 INFO 15728 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-04-06 16:05:32.948 WARN 15728 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2022-04-06 16:05:33.018 INFO 15728 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-04-06 16:05:33.034 INFO 15728 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL55Dialect
2022-04-06 16:05:33.132 INFO 15728 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-04-06 16:05:33.138 INFO 15728 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-04-06 16:05:33.156 WARN 15728 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-04-06 16:05:33.313 INFO 15728 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-04-06 16:05:33.319 INFO 15728 --- [ main] C.Ruben_DeNicolas.ClientixApplication : Started ClientixApplication in 1.398 seconds (JVM running for 1.705)
2022-04-06 16:05:36.286 INFO 15728 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-04-06 16:05:36.287 INFO 15728 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-04-06 16:05:36.287 INFO 15728 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
what is the url your hitting on your browser, make sure not hitting with https...
Code looks okay, try hitting
http://localhost:8080/clientes

Can't connect Spring boot with MongoDb

I'm trying to make a simple progam with Spring Boot work with MongoDB in Spring Boot 2.3.9
From the startup logs I suspect that something is wrong, it seems like it's initialized twice.
This is my console output:
2021-03-08 01:54:43.515 INFO 26609 --- [ restartedMain] c.a.a.r.SpringbootRegistroApplication : Starting SpringbootRegistroApplication on santiagoVB with PID 26609 (/home/santiago/Documentos/workspace/springboot-registro/target/classes started by santiago in /home/santiago/Documentos/workspace/springboot-registro)
2021-03-08 01:54:43.521 INFO 26609 --- [ restartedMain] c.a.a.r.SpringbootRegistroApplication : No active profile set, falling back to default profiles: default
2021-03-08 01:54:43.680 INFO 26609 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-03-08 01:54:43.682 INFO 26609 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-03-08 01:54:45.719 INFO 26609 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-03-08 01:54:45.895 INFO 26609 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 167ms. Found 1 MongoDB repository interfaces.
2021-03-08 01:54:46.683 INFO 26609 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-03-08 01:54:46.699 INFO 26609 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-03-08 01:54:46.701 INFO 26609 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-03-08 01:54:46.830 INFO 26609 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-03-08 01:54:46.830 INFO 26609 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3147 ms
2021-03-08 01:54:47.152 INFO 26609 --- [ restartedMain] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-03-08 01:54:47.363 INFO 26609 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:12}] to localhost:27017
2021-03-08 01:54:47.372 INFO 26609 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=9, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=5581801}
2021-03-08 01:54:47.714 INFO 26609 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-03-08 01:54:48.326 INFO 26609 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-03-08 01:54:48.685 INFO 26609 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-03-08 01:54:48.701 INFO 26609 --- [ restartedMain] c.a.a.r.SpringbootRegistroApplication : Started SpringbootRegistroApplication in 6.21 seconds (JVM running for 9.239)
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.3.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.appcity.app.registro</groupId>
<artifactId>springboot-registro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-registro</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>15</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My application.properties:
spring.data.mongodb.uri=mongodb://localhost:27017/App
spring.data.mongodb.auto-index-creation=true
#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.username=Udea
#spring.data.mongodb.password=udeapp
#spring.data.mongodb.database=App
My Object:
package com.appcity.app.registro.models.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "UsuarioDb")
public class UsuarioDb {
#Id
private String id;
private String username;
private String phone;
private String email;
private String password;
public UsuarioDb() {
super();
}
public UsuarioDb(String id, String username, String phone, String email, String password) {
super();
this.id = id;
this.username = username;
this.phone = phone;
this.email = email;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "UsuarioDb [id=" + id + ", username=" + username + ", phone=" + phone + ", email=" + email
+ ", password=" + password + "]";
}
}
My Interface:
package com.appcity.app.registro.models.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.appcity.app.registro.models.entity.UsuarioDb;
#Repository
public interface RegistroDao extends MongoRepository<UsuarioDb, String>{
}
My Controller:
package com.appcity.app.registro.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.appcity.app.registro.models.dao.RegistroDao;
import com.appcity.app.registro.models.entity.UsuarioDb;
//#CrossOrigin
#RestController
public class RegistroController {
#Autowired
private RegistroDao repository;
#PostMapping("/registro/crear")
public String saveUsuarioDb(#RequestBody UsuarioDb usuarioDb) {
repository.save(usuarioDb);
return "Added usuarioDb with id : " + usuarioDb.getId();
}
#GetMapping("/registro/listar")
public List<UsuarioDb> getUsers(){
return repository.findAll();
}
#GetMapping("/registro/listar/{id}")
public Optional<UsuarioDb> getUser(#PathVariable String id){
return repository.findById(id);
}
#DeleteMapping("/registro/eliminar/{id}")
public String deleteUser(#PathVariable String id) {
repository.deleteById(id);
return "usuarioDb deleted with id : "+id;
}
}
My MongoDb Status in Ubuntu:
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2021-03-08 00:30:58 -05; 1h 46min ago
Docs: https://docs.mongodb.org/manual
Main PID: 21445 (mongod)
Memory: 160.1M
CGroup: /system.slice/mongod.service
└─21445 /usr/bin/mongod --config /etc/mongod.conf
mar 08 00:30:58 santiagoVB systemd[1]: Started MongoDB Database Server.
My database in MongoDb:
show dbs
App 0.000GB
admin 0.000GB
config 0.000GB
local 0.000GB
What am I doing wrong?
What configuration do I have wrong?
I ran into a similar kind of issue and I installed a different JDK patch. I had JDK 11.0.2 and I changed it to JDK 11.0.10 and It worked for me.
Also, you need to have the #CrossOrigin(origins = "*") annotation. * (asterisk) means you are allowing requests from any origin.

cant connect to mysql databse using spring boot

When I am hitting url(http://localhost:8080/pjt/samples) in Postman for json data,it shows the following error.
{
"timestamp": "2020-05-17T10:54:26.705+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/pjt/samples"
}
1)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.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>samplepjt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>samplepjt</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-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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2)model:
package 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
#Table(name = "samples")
public class Sample {
private Long id ;
private String name;
private String city;
public Sample(String name, String city) {
this.name = name;
this.city = city;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "city", nullable = false)
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Sample [id=" + id + ",name=" + name + ", city=" + city + "]";
}
}
3)repository
package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import model.Sample;
#Repository
public interface SampleRepository extends JpaRepository<Sample,Long>{
}
4)controller
package controller;
import java.util.List;
import javax.validation.Valid;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import model.Sample;
import repository.SampleRepository;
#RestController
#RequestMapping("/pjt")
public class SampleController {
#Autowired
private SampleRepository sampleRepository;
#PostMapping("/samples")
public Sample createSample(#Valid #RequestBody Sample sample) {
return sampleRepository.save(sample);
}
#GetMapping("/samples")
public List<Sample> getAllSample() {
return sampleRepository.findAll();
}
}
5)main function
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SamplepjtApplication {
public static void main(String[] args) {
SpringApplication.run(SamplepjtApplication.class, args);
}
}
6)application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/sampledb?useSSL=false
spring.datasource.username = root
spring.datasource.password = dali
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
. ____ _ __ _ _
/\ / ' __ _ ()_ __ __ _ \ \ \ \
( ( )_ | '_ | '| | ' / ` | \ \ \ \
\/ )| |)| | | | | || (| | ) ) ) )
' |____| .|| ||| |__, | / / / /
=========|_|==============|___/=///_/
:: Spring Boot :: (v2.2.7.RELEASE)
2020-05-17 16:47:56.159 INFO 3688 --- [ main] com.example.demo.SamplepjtApplication : No active profile set, falling back to default profiles: default
2020-05-17 16:47:58.395 INFO 3688 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-17 16:47:58.476 INFO 3688 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 49ms. Found 0 JPA repository interfaces.
2020-05-17 16:48:00.119 INFO 3688 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2020-05-17 16:48:00.142 INFO 3688 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-05-17 16:48:00.143 INFO 3688 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.34]
2020-05-17 16:48:00.496 INFO 3688 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-05-17 16:48:00.497 INFO 3688 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4199 ms
2020-05-17 16:48:00.980 INFO 3688 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-17 16:48:01.156 INFO 3688 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
2020-05-17 16:48:01.579 INFO 3688 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-17 16:48:01.898 INFO 3688 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-05-17 16:48:02.714 INFO 3688 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-05-17 16:48:02.771 INFO 3688 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2020-05-17 16:48:03.635 INFO 3688 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation:[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-17 16:48:03.660 INFO 3688 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-17 16:48:04.042 WARN 3688 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-17 16:48:04.388 INFO 3688 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-17 16:48:04.845 INFO 3688 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2020-05-17 16:48:04.849 INFO 3688 --- [ main] com.example.demo.SamplepjtApplication : Started SamplepjtApplication in 9.906 seconds (JVM running for 12.757)
2020-05-17 16:48:13.367 INFO 3688 --- [nio-8081-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-17 16:48:13.369 INFO 3688 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-05-17 16:48:13.395 INFO 3688 --- [nio-8081-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 25 ms
Can anyone help me to fix this issue?
You have to place the SampleController.java in com.example.demo.controller & SampleRepository.java in com.example.demo.repository. Or all the files should be in com.example.demo folder.
Because #SpringBootApplication has to scan all the components. Go through this doc for better understanding https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/html/using-boot-structuring-your-code.html.

Post and Get not mapped to Spring boot - status : 404

I have a simple application to test Spring Boot.
Below is the configuration and the packages are set as per Spring documentation.
There is no error in application startup. Using Spring boot with eclipse.
Still the controller is not mapped to the server and when I do Post or Get it says :
{
"timestamp": 1547026379146,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/postdata"
}
Repository:
package com.abc.nice.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.abc.nice.entity.Messages;
#Repository
public interface MessagesRepository extends JpaRepository<Messages, Long> {
}
Entity:
package com.abc.nice.entity;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "Messages")
public class Messages{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Size(max = 100)
private String toNumber;
#Size(max = 250)
private String hsm;
#Size(max = 250)
private String template;
#Size(max = 250)
private String parameters;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTo() {
return toNumber;
}
public void setTo(String toNumber) {
this.toNumber = toNumber;
}
public String getHsm() {
return hsm;
}
public void setHsm(String hsm) {
this.hsm = hsm;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getParameters() {
return parameters;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
}
Controller :
package com.abc.nice.controller;
import java.util.List;
import java.util.Map;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.abc.nice.entity.Messages;
import com.abc.nice.repo.MessagesRepository;
#RestController
public class ControllerRest {
#Autowired
private Messages msgDao;
private MessagesRepository msgRepo;
RestTemplate restTemplate;
#GetMapping({ "/StatusData" })
public List<Messages> index() {
return this.msgRepo.findAll();
}
#PostMapping(path = {"/postdata"})
public ResponseEntity<Messages> createBody(#RequestBody Map<String, String> body) {
this.msgDao = new Messages();
this.msgDao.setTemplate((String) body.get("template"));
this.msgDao.setParameters((String) body.get("parameters"));
this.msgDao.setHsm((String) body.get("hsm"));
this.msgDao.setTo((String) body.get("to"));
return new ResponseEntity<Messages>(this.msgRepo.save(this.msgDao), HttpStatus.OK);
}
}
MainClass :
package com.abc.nice;
import org.hibernate.HibernateException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
//#EntityScan("com.abc.nice.entity")
#ComponentScan({"com.abc.nice.entity","com.abc.nice.controller"})
#EnableJpaRepositories({"com.abc.nice.repo"})
//#EnableAutoConfiguration
public class TestApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(TestApplication .class, args);
}
}
Startup Log :
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.9.RELEASE)
2019-01-09 17:33:27.724 INFO 19732 --- [ main] com.abc.nice.TestApplication : Starting TestApplication on abcD02 with PID 19732 (C:\Users\abcd\Desktop\test\target\classes started by abcD in C:\Users\abcd\Desktop\test)
2019-01-09 17:33:27.728 INFO 19732 --- [ main] com.abc.nice.TestApplication : No active profile set, falling back to default profiles: default
2019-01-09 17:33:27.827 INFO 19732 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:33:29.489 INFO 19732 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-01-09 17:33:29.506 INFO 19732 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-09 17:33:29.507 INFO 19732 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2019-01-09 17:33:29.746 INFO 19732 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-09 17:33:29.746 INFO 19732 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1922 ms
2019-01-09 17:33:30.005 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-01-09 17:33:30.009 INFO 19732 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-01-09 17:33:30.598 INFO 19732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2019-01-09 17:33:30.610 INFO 19732 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-01-09 17:33:30.680 INFO 19732 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2019-01-09 17:33:30.682 INFO 19732 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-01-09 17:33:30.683 INFO 19732 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2019-01-09 17:33:30.749 INFO 19732 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2019-01-09 17:33:30.864 INFO 19732 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-01-09 17:33:31.033 INFO 19732 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2019-01-09 17:33:31.058 INFO 19732 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-01-09 17:33:31.388 INFO 19732 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:33:31.454 INFO 19732 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-01-09 17:33:31.455 INFO 19732 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-01-09 17:33:31.489 INFO 19732 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.489 INFO 19732 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.527 INFO 19732 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-01-09 17:33:31.866 INFO 19732 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-01-09 17:33:31.937 INFO 19732 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-01-09 17:33:31.942 INFO 19732 --- [ main] com.abc.nice.WhatsapptestApplication : Started WhatsapptestApplication in 4.532 seconds (JVM running for 6.213)
2019-01-09 17:39:45.612 INFO 19732 --- [on(2)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2019-01-09 17:39:45.613 INFO 19732 --- [on(2)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4206a205: startup date [Wed Jan 09 17:33:27 SGT 2019]; root of context hierarchy
2019-01-09 17:39:45.616 INFO 19732 --- [on(2)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2019-01-09 17:39:45.617 INFO 19732 --- [on(2)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
Application.properties:
#spring.datasource.type=org.apache.commons.dbcp.BasicDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/ptpreconn?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.data.jpa.repositories.enabled=true
#spring.jpa.database-platform=org.hibernate.dialect.MYSQL5Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
server.port=${PORT:8080}
Please attach request from e.g. the developers' tools with HTTP verb that you are using and exact response from that request. I am concerned about #GetMapping - why it is in curly braces?
About post mapping, maybe you should describe consumes and produces part of mapping?
E.g.
#PostMapping(path = "/members", consumes = "application/json", produces = "application/json")
I have never used #PostMapping annotation without those parts.
UPDATE:
After removal of unnecessary component scan in Main class change controller as follow:
#RestController
public class ControllerRest {
#Autowired
private MessagesRepository msgRepo;
RestTemplate restTemplate;
#GetMapping({ "/StatusData" })
public List<Messages> index() {
return this.msgRepo.findAll();
}
#PostMapping(path = {"/postdata"})
public ResponseEntity<Messages> createBody(#RequestBody Map<String, String> body) {
Messages msgDao = new Messages();
msgDao.setTemplate((String) body.get("template"));
msgDao.setParameters((String) body.get("parameters"));
msgDao.setHsm((String) body.get("hsm"));
msgDao.setTo((String) body.get("to"));
return new ResponseEntity<Messages>(this.msgRepo.save(this.HttpStatus.OK);
}
}
Add a context path to your application.properties file or application.yml, whichever you are using.
server.servlet.contextPath=/springbootapi
Hit your endpoint: The endpoint for your POST method will be:
http://localhost:{PORT}/springbootapi/postdata
Why dont you statically supply your port. I think the port should be something like:
server.port=8080
I don't understand why you using #RequestBody with "Map<String,String>".
Try this code :
#Autowired
private MessagesRepository msgRepo;
#PostMapping("/postdata")
public ResponseEntity<Object> createBody(#RequestBody Message message) {
Message saveMessage= msgRepo.save(message);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(saveMessage.getId()).toUri();
return ResponseEntity.created(location).build();
}

Categories

Resources