Getting directed to 404 page in Spring Boot backend - java

I am working on Spring Boot application. I have my jsp frontend and my java backend. When I up the project in tomcat server I can see the frontend get upped. But when I try to direct the url to check the backend performance I am getting directed to 404.
Example http://localhost:8090/orders
#RequestMapping paths were defined in the correct way.I am using workbench in my case.
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/csse_ass
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=create
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
pom.xml (I have so many dependencies, I add the essential one here)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
controller
private OrderService orderService;
#RequestMapping("/orders")
public List<Order> getAllOrders(){
return orderService.getAllOrders();
}
service
#Autowired
private OrderRepository orderRepository;
public List<Order> getAllOrders(){
List<Order> orders = new ArrayList<>();
for (Order order : orderRepository.findAll()) {
orders.add(order);
}
return orders;
}
repository
public interface OrderRepository extends CrudRepository<Order,String> {}
As well as I have my order.java class.I hope it doesn't matter in this problem.
I get no errors in my terminal except the tomcat errors which is common.
Question
Why I am getting directed to 404 page as I mentioned in the very top of the question?
Somebody fix this issue for me, cuz I couldn't figure out the problem.

try this...
#RequestMapping("/orders")
#ResponseBody
public List<Order> getAllOrders(){
return orderService.getAllOrders();
}
use #Controller annotation also..

Related

What is the proper way to connect spring boot with mongo and read document?

Before all, I'm testing in Postman with this URL: http://localhost:8080/skiing/getSkiing, response is:
[
{}
]
I don't know is this all that I need for Mongo configuration with Spring, if it's no, can someone link me an example with good way how to connect Spring Boot with Mongo. And also, if this is all what I need for mongo configuration, how Spring read this? Where is this called or where Spring Boot actually use this?
spring.data.mongodb.database=tripadvisor
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
spring.servlet.multipart.max-file-size=256MB
spring.servlet.multipart.max-request-size=256MB
spring.servlet.multipart.enabled=true
Anyway, my response after trying to read all elements from documents is empty. This is my code for that:
Repo:
#Repository
public interface SkiingRepository extends MongoRepository<Skiing, String> {
}
Service
#Service
public class SkiingServiceImpl implements SkiingService {
#Autowired
private SkiingRepository skiingRepository;
#Override
public List<Skiing> getAllSkiing() {
return skiingRepository.findAll();
}
}
Controller:
#RestController
#RequestMapping("/skiing")
public class SkiingController {
#Autowired
SkiingService skiingService;
#GetMapping(value = "/getSkiing")
public ResponseEntity<?> getAllSkiing() {
List<Skiing> skiingList = skiingService.getAllSkiing();
return new ResponseEntity<Object>(skiingList, HttpStatus.OK);
}
}
There are some basic configurations when you work with Spring and MongoDB:
spring.data.mongodb.uri=
spring.data.mongodb.database=
spring.data.mongodb.username=
spring.data.mongodb.password=
spring.data.mongodb.port=
spring.data.mongodb.host=
The answer for question "Where is this called or where Spring Boot actually use this?" is Spring Data MongoDB - a project of Spring Framework
Please refer Spring Data MongoDB for more information

Swagger not showing my controllers. Tried Postman, my endpoints still failling

Hope you're all doing great. I'm trying to code API's with Java and Springboot as my framework. I'm using sqlServer as my database. I did the whole configuration to make the connection possible (enabled tcp/ip protocols, got sql servers up, used an sql server jar file and dll file in my project, allowed remote connections with sql server). When i execute a query in my project in works and shows me the data in the console. BUT, when I use Swagger, there isn't my User controllers and it's methods, it just brings the basic error controller.
I have the swagger dependencies in my pom file, and I have the #EnableSwagger2 in my main application.
This is what happens when I use postman:
I don't know what to do, I can't try my API's.
Here u can see my user controller:
import JDBC.DAO.UsuarioDAO;
import JDBC.DTO.Usuario;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.List;
#RestController
#RequestMapping("/")
#CrossOrigin(origins = "*", maxAge = 3600)
public class UsuarioResource {
//Get usuario por rut
#RequestMapping(method = RequestMethod.GET, value = "traerUsuario/{rut}")
public List<Usuario> obtenerUsuarioPorRut (#PathVariable ("rut") String rut) throws SQLException {
List<Usuario> user = new UsuarioDAO().obtenerUsuarioPorRut(rut);
return user;
}
//Get todos los usuarios
#RequestMapping(method = RequestMethod.GET, value = "allUsers")
public List <Usuario> getUsuarios() throws SQLException {
List <Usuario> usuarios = new UsuarioDAO().obtenerUsuarios();
return usuarios;
}
}
You can see my url should be localhost:8080/whateverendpointgoeshere (When I run my application it says running op port 8080).
This is the ConnectionManager I made to, uh, connect to the database (It works because as I said before, it brings me data when I do it directly in my IDE):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager {
private static Connection connection = null;
private static String connectionString = "jdbc:sqlserver://localhost:1433; databasename=prac; integratedSecurity=true";
public static Connection obtenerConexion() throws SQLException {
if (connection == null)
connection = DriverManager.getConnection(connectionString);
return connection;
}
}
In this image you can see why I'm using port 1433 to connect to sql server, I'm following what the TCP/IP says:
Swagger dependencies in my pom file:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
So... I've been stuck for some days trying to figure out why I can't hit my endpoints. I would appreciate some help.
I think since you can't access the endpoints even without swagger, this is an issue with your package structure. Your controller package and all other component packages (eg. service, repository) should be a subpackage under the package your main class (SpringBootApplication.java) is in. (If not a subpackage of your main class's package, you need to manually add them in #ComponentScan annotation.)
You need have configuration file for Swagger in spring boot.
#Configuration
public class SpringFoxConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Annotate the class with #Configuration . You can leave the rest same as above .
Restarting the server and hitting swagger URL should fix it .

Spring Boot #GetMapping to a URL ending with .jsp

We have a URL that has to end with (customer requirement) something like /test.jsp.
Now that we're finally running Spring Boot (2.1.1.RELEASE), we would like to ditch JSP and use some templating engine, in this case Mustache. I have a controller mapping like this:
#Controller
#RequestMapping("/")
public class TestController {
#GetMapping(path = "/test.jsp")
public ModelAndView test(...) {...}
}
This just doesn't work. I have
spring.mvc.pathmatch.use-suffix-pattern=true
In our application.properties, anything spring.mvc.view-related is commented out, when I add another mapping with just /test, it works for /test. Funny thing is I have managed to get the same exact thing working when using Spring MVC and Thymeleaf but I can't seem to find the difference.
Additionally, I added a test for this like so:
#ExtendWith(SpringExtension.class)
#SpringBootTest
#AutoConfigureMockMvc
#ActiveProfiles("test")
class TestTest {
#Autowired
private MockMvc mockMvc;
#Test
void test() throws Exception {
final MockHttpServletRequestBuilder testRequestBuilder = MockMvcRequestBuilders.get("/test.jsp");
MvcResult responseResult = mockMvc.perform(testRequestBuilder).andReturn();
response = responseResult.getResponse();
assertThat(response.getStatus(), equalTo(HttpStatus.OK.value()));
}
}
This works fine, the content of the response is also exactly what I want. The test profile is the same as the one when using mvn spring-boot:run for the time being.
Anyone got an idea on how to get this working? Thanks!
The dot is probably being truncated. or escaped.
You can probably do something like this:
#GetMapping("/{pageName:.+}")
public void test(
#PathVariable("pageName") String pageName) {
if(pageName.equals("test.jsp")) {
//...
}
I know you dont exactly want a variable, but just throwing an idea
I finally solved it - I had everything working including test.html, test.xml, test.wasd and test. So I figured it couldn't be Spring by itself. After some debugging in various Tomcat classes I found the culprit: JspServlet was somehow present in the classpath and being automatically configured, originating from
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
Removing the dependency led to test.jsp being recognized correctly.

Use mysql instead hsql java spring

I hava this codes and i use application.properties for use mysql but yet hsql is use.
application.properties
spring.datasource.url=jdbc:mysql://localhost:3307/dvv
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.platform=mysql
and application.class
#EnableAutoConfiguration
#EnableJpaRepositories(basePackageClasses = {VideoRepository.class, VideoRepository2.class})
#Configuration
#EnableWebMvc
#ComponentScan
public class Application {
// Tell Spring to launch our app!
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and Repository
#Repository
public interface VideoRepository2 extends CrudRepository<Video2, Long>{
// Find all videos with a matching title (e.g., Video.name)
public Collection<Video2> findByName(String title);
// Find all videos within a given category
public Collection<Video2> findByCategory(String category);
}
Can you verify,
1.Check how many application-XXX.properties files are exists in your application.
2.Check whether you are using correct profile to run this application.
Also share your hsql configuration as well.
make sure the mysql connector is added to your pom.xml /build.gradle
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

How to call a Spring managed object from a POJO?

I am running a web-app, which has one exposed class ( available to other POJO classes) and that has one autowired private member.
Spring managed class
public class EPSQueueSender {
#Autowired
private AmqpTemplate epsMessageTemplate;
public void dosomething(...){
epsMessageTemplate.convertAndSend(...); // Here epsMessageTemplate is null if instance of EPSQueueSender taken from other POJO
}
}
POJO class
public class Test{
EPSQueueSender sender = new EPSQueueSender();
sender.dosomething(....); // gives null exception on epsMessageTemplate
}
Spring code ( running as WebApp) and POJO class code( different Jar) are on same JVM. The POJO is not able to get initialized autowired object. However it is initialized if I use it in webApp project.
Can someone please give some suggestion how can I overcome this problem?
Last thing I would like to try is to hit webserver as http request from POJO.
beans can be pojo or xml many examples might help. You already have #autowired but you did not create the #bean method itself that belongs in a class annotated with #Configuration
Your problem could be overcome using #Configurable feature of spring. For it you have configure in xml with a code like belove
<context:annotation-config/>
<context:spring-configured/>
<context:load-time-weaver/>
in Java Congiguration like below:
#Configuration
#EnableAspectJAutoProxy
#EnableSpringConfigured
#EnableLoadTimeWeaving
public class ConfigApplicationContext {
}
with this configuration you can benefit of the load-waving aspect technique that througth the build-in Spring bean AnnotationBeanConfigureAspect you can inject Spring bean in a pojo that is annotated with #Configurable. you colud be have a code like below:
#Configurable
public class Test{
#Autowired
private EPSQueueSender sender;
public void method(){
sender.dosomething(....); // gives null exception on epsMessageTemplate
}
}
of course, since that you are using a load-wave technique you have configure an agent that will perform the istruments. the configuration is very simple and you have add a line like below in the start of the jvm or tomcat:
java -javaagent:path of the jar with the agent/spring-instrument.jar
remember of course of insert the aop and spring aop maven dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>yourVersion</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>4
<version>yourVersion</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>yourVersion</version>
</dependency>
I hope that this can help you

Categories