I am trying to execute Spring boot application hosted on a tomcat server online. The issue is when I try to get, delete or post data, a user controller it generates this message.
{
"timestamp": "2021-01-24T06:45:42.144+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/tool/api/v1/users"
}
the weird issue is that when I run the server locally http://localhost:8080/api/v1/users I get data
but when I try hosting the war file and hitting the endpoint http://31.134.12.356:9080/tool/api/v1/usersi end up with the error above.
My Users Controller
#RequestMapping("/api/v1")
#RestController
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#GetMapping("/users")
public Iterable<User> getAllUsers() {
return userRepository.findAll();
}
#GetMapping("/users/{id}")
public User getUserById(#PathVariable("id") String id) {
return userRepository.findById(id).get();
}
#GetMapping("/users/{username}")
public User getUserByUsername(#PathVariable("username") String username) {
return userRepository.findByUsername(username).get();
}
#PostMapping(value = "/users")
public ResponseEntity<Object> saveUser(#RequestBody SaveUserRequest userRequest) {
//save user details
User user = new User(userRequest.getUsername(),
userRequest.getDisplayName(), userRequest.getEmail(), userRequest.getIdentityProvider());
Set<String> strRoles = userRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Role is not found."));
roles.add(userRole);
}
});
}
user.setRoles(roles);
user.setId(java.util.UUID.randomUUID().toString());
user.setLastLoggedOn(new Date());
userRepository.save(user);
return ResponseEntity.ok(user);
}
}
The weird issue is that I have other endpoints and they are working fine, the users rest api is the one not being found. I have added tool in the api as it is the name of the war file, I have multiple war files running on the tomcat.
ServletInitializer
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MonitoringToolApplication.class);
}
}
Main class
#SpringBootApplication
#ComponentScan({ "com.example.tool.demo.controller"})
#EntityScan(basePackages = "com.example.tool.demo.model")
public class MonitoringToolApplication {
public static void main(String[] args) {
SpringApplication.run(MonitoringToolApplication.class, args);
}
}
my pom file
<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.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.tool</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Example</name>
<description>example</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>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-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!-- <scope>provided</scope>-->
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</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>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application.properties file
#Example Tool connection string
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=example_tools
spring.datasource.username=sa
spring.datasource.password= user2k!!__
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.SQLServer2012Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql = true
Please help me out with the issue. Many thanks in advance.
When deploying the project on the server side, exclude the embedded tomcat in the pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
Related
I'm making a POST request to authenticate the API that I'm implementing, but I have the following problem:
My username is not being returned:
however, my password is, and I'm not understanding why:
Below I will be sending my source code for better understanding...
Class: AuthController.java
#RestController
#RequestMapping("/auth")
public class AuthController {
#Autowired
AuthenticationManager authenticationManager;
#Autowired
JwtTokenProvider jwtTokenProvider;
#Autowired
UserRepository repository;
#ApiOperation(value = "Authenticate a user by credentials") //Swagger endpoint description
#PostMapping(value="/signin", produces = { "application/json", "application/xml", "application/x-yaml" }, consumes = {
"application/json", "application/xml", "application/x-yaml" })
public ResponseEntity singin(#RequestBody AccountCredentialsVO data) throws Exception {
try {
var username = data.getUserName();
var password = data.getPassword();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
var user = repository.findByUserName(username);
var token = "";
if(user != null) {
token = jwtTokenProvider.createToken(username, user.getRoles());
}else {
throw new UsernameNotFoundException("Username " + username + " not found!");
}
Map<Object, Object> model = new HashMap<>();
model.put("username", username);
model.put("token", token);
return ok(model);
} catch (Exception e) {
throw new BadCredentialsException("Invalid username/password supplied!");
}
}
}
Class: AccountCredentialsVO.java
public class AccountCredentialsVO implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "username")
private String username;
private String password;
public String getUserName() {
return username;
}
public void setUserName(String userName) {
this.username = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
return Objects.hash(password, username);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccountCredentialsVO other = (AccountCredentialsVO) obj;
return Objects.equals(password, other.password) && Objects.equals(username, other.username);
}
}
The pom.xml:
<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">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.andrefilipeos</groupId>
<artifactId>rest-with-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<description>Creating API RESTFul with Spring Boot 2.x</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
</properties>
<dependencies>
<!-- for Spring-boot Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- for Tests Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
<version>6.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- for XML support-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<!-- for YML or YAML support-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<!-- for HATEOAS Support -->
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<!-- for Swagger Support -->
<!-- http://localhost:8080/v2/api-docs -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- it's format all API documentation organized -->
<!-- http://localhost:8080/swagger-ui.html -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- for Security Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- for Tokens Support -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<!-- for Migration support $mvn flyway:migrate -->
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<configuration>
<url>jdbc:mysql://localhost:3306/rest_with_springboot?useTimezone=true&serverTimezone=UTC&useSSL=false</url>
<user>root</user>
<password>admin123</password>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
My POST request:
http://localhost:8080/auth/signin
With XML (application/xml):
<AccountCredentialsVO>
<username>leandro</username>
<password>admin123</password>
</AccountCredentialsVO>
With JSON (application/json):
{
"username":"leandro",
"password":"admin123"
}
And unfortunately with both requests I'm getting the same result of null username!
I'm trying to make a Spring Boot Application with simple login page but when i try to use #Autowired with a interface that i created seems to be a problem. I read 7-8 similar questions but the answers that i find there was useless for me. #Autowired works fine when i use it on interface that expends JpaRepository.
my structure is:
My packages are on the same level as my Application file .
Here is my controller
#Controller
#RequestMapping(value = "/users")
public class LoginContoller {
#Autowired
UsersRepositoryCustom usersRepositoryCustom;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginForm(){
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public #ResponseBody
String verifyLogin(#RequestParam String name, #RequestParam String password) {
System.out.println("Controller: name: " + name + " pass " + password);
Users users=usersRepositoryCustom.loginUser(name, password);
if (users==null) {
System.out.println("login control user null");
return "login";
}
return "users/all";
}
}
Repository:
#Repository
public interface UsersRepositoryCustom {
Users loginUser(String name, String password);
}
I do not think it helps but here is the implementation
public abstract class UserImpl implements UsersRepositoryCustom {
#Autowired
UsersRepository usersRepository;
#Override
public Users loginUser(String name, String password) {
System.out.println("UserImpl: nume: " + name + " pass " + password);
Users user=usersRepository.findByUsername(name);
if (user != null && user.getPassword().equals(password)) {
System.out.println("User Login"+user.getId()+" "+user.getUsername());
return user;
}
return null;
}
}
Application.properties:
server.port=8080
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3308/assignment-one-db
spring.datasource.username=root
spring.datasource.password=789456123
spring.jpa.hibernate.ddl-auto= update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.asg1</groupId>
<artifactId>asg1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>asg1</name>
<description>assignment1</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</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-thymeleaf</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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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>
I try to use #EnableJpaRepositories, #EnableAutoConfiguration but it was useless
Here is the error:
Description:
Field usersRepositoryCustom in com.asg1.asg1.controllers.LoginContoller required a bean of type 'com.asg1.asg1.repository.UsersRepositoryCustom' 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.asg1.asg1.repository.UsersRepositoryCustom' in your configuration.
Process finished with exit code 1
I am using Spring Boot and JSP to learn some quick tutorials in Spring Security but my controller mappings and index.jsp are not working. It seems it can't locate the JSP pages. Here is my config and project structure:
springsecurity-for-reactive-apps [boot] - Project folder
- src/main/java
- com.springsecurity
- SpringsecurityForReactiveAppsApplication.java
- com.springsecurity.config
- ApplicationConfig.java
- SecurityWebApplicationInitializer.java
- SpringMvcWebApplicationInitializer.java
- SpringSecurityConfig.java
- WebApplicationConfig.java
- src
- main
- webapp
- WEB-INF
- view
- home.jsp
- index.jsp
com.springsecurity package contains
#SpringBootApplication
public class SpringsecurityForReactiveAppsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringsecurityForReactiveAppsApplication.class, args);
}
}
com.springsecurity.config package contains the following classes
#Configuration
public class ApplicationConfig {
#Value("${spring.datasource.driver-class-name}")
private String DB_DRIVER;
#Value("${spring.datasource.password}")
private String DB_PASSWORD;
#Value("${spring.datasource.url}")
private String DB_URL;
#Value("${spring.datasource.username}")
private String DB_USERNAME;
#Autowired
private Environment env;
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
}
And SecurityWebApplicationInitializer class is
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
}
SpringMvcWebApplicationInitializer class is
public class SpringMvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebApplicationConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
And my configuration class is
#Configuration
#EnableWebSecurity
//#EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class })
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled"
+ " from users where username = ?")
.authoritiesByUsernameQuery("select username, authority "
+ "from authorities where username = ?")
.passwordEncoder(new BCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().hasAnyRole("ADMIN", "USER")
.and()
.httpBasic(); // Use Basic authentication
}
}
And
#Configuration
#EnableWebMvc
#ComponentScan(basePackages= {"com.springsecurity"})
public class WebApplicationConfig implements WebMvcConfigurer{
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp().prefix("/WEB-INF/view/").suffix(".jsp");
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
- com.springsecurity.controller contains:
#Controller
public class HomeController {
#GetMapping("/home")
public String home(Model model, Principal principal) {
System.out.println("___________home()___________________");
return "home";
}
#GetMapping("/error")
public String error(Model model, Principal principal) {
System.out.println("___________ERROR-<<error___________________");
return "home";
}
}
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>
<groupId>com.springsecurity</groupId>
<artifactId>springsecurity-for-reactive-apps</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springsecurity-for-reactive-apps</name>
<description>Spring security for reactive applications</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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>
<!-- Spring dependencies START-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!-- Servlet and JSP related dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- For datasource configuration -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
<!-- We will be using MySQL as our database server -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- Spring dependencies END -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When I go to http://localhost:8080, I get this page
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 18 03:24:51 CEST 2018
There was an unexpected error (type=Not Found, status=404).
No message available
The error page is mapped to show the home.jsp but I get the above page
1.viewResolver.setPrefix("/WEB-INF/views/"); views -> view
2.you can implements ErrorController in spring
#Controller
public class ViewController implements ErrorController {
#GetMapping("/home")
public String home(Model model) {
System.out.println("___________home()___________________");
return "home";
}
#GetMapping("/error")
public String error(Model model) {
System.out.println("___________ERROR-<<error___________________");
return "home";
}
#Override
public String getErrorPath() {
return "/error";
}
}
In your pom.xml remove
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
And add these dependency
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
As I know, to render jsp page in boot tomcat-embed-jasper is needed.
I am creating a basic spring boot REST API. My project has the following structure:
com.anonreporting.springboot
--- SpringBootAnonReporting.java , config.java
com.anonreporting.springboot.controller -- userController.java
com.anonreporting.springboot.domain -- User.java
com.anonreporting.springboot.service -- UserService.java UserServiceImpl.java
com.anonreporting.springboot.repository -- userRepository.java
SpringBootAnonReporting.java
#SpringBootApplication
public class SpringBootAnonReporting {
public static void main(String[] args) throws ParseException {
ApplicationContext applicationContext = SpringApplication.run(SpringBootAnonReporting.class, args);
for (String name : applicationContext.getBeanDefinitionNames()) {
System.out.println(name);
}
}
}
User.java is a POJO class.
UserController
#Controller
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value="/users",method=RequestMethod.GET)
ResponseEntity<Iterable<User>> listAllUsers()
{
return new ResponseEntity<Iterable<User>>(userService.listAllUsers(),HttpStatus.OK);
}
#RequestMapping(value="/newuser",method=RequestMethod.POST)
ResponseEntity registerUser(User user)
{
userService.saveUser(user);
return new ResponseEntity(HttpStatus.CREATED);
}
#RequestMapping(value="/get",method=RequestMethod.GET)
ResponseEntity<String> tryGet()
{
System.out.println("hihihih");
return new ResponseEntity<String>("HI",HttpStatus.OK);
}
}
UserService:
#Service
public interface UserService {
Iterable<User> listAllUsers();
User getUserById(String id);
User saveUser(User user);
void deleteUser(String id);
}
UserServiceImpl:
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Override
public Iterable<User> listAllUsers() {
// TODO Auto-generated method stub
return userRepository.findAll();
}
#Override
public User getUserById(String id) {
// TODO Auto-generated method stub
return userRepository.findOne(id);
}
#Override
public User saveUser(User user) {
// TODO Auto-generated method stub
return userRepository.save(user);
}
#Override
public void deleteUser(String id) {
// TODO Auto-generated method stub
userRepository.delete(id);
}
}
config.java
#Configurable
#Configuration
#EnableAutoConfiguration
#EnableTransactionManagement
public class Config {
public #Bean(destroyMethod = "close") AerospikeClient aerospikeClient() {
ClientPolicy policy = new ClientPolicy();
policy.failIfNotConnected = true;
policy.timeout = 2000;
return new AerospikeClient(policy, "172.28.128.3", 3000);
}
public #Bean AerospikeTemplate aerospikeTemplate() {
return new AerospikeTemplate(aerospikeClient(), "test");
}
}
UserRepository.java:
#Component
public interface UserRepository extends AerospikeRepository<User, String> {
}
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>
<groupId>com.example</groupId>
<artifactId>anonReporting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>anonReporting</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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>
<!-- https://mvnrepository.com/artifact/com.aerospike/aerospike-client -->
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>aerospike-client</artifactId>
<version>4.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons-core -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons-core</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aerospike/spring-data-aerospike -->
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>spring-data-aerospike</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-keyvalue -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
On running the code, the following error occurs:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in com.anonreporting.springboot.user.UserServiceImpl required a bean of type 'com.anonreporting.springboot.user.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.anonreporting.springboot.user.UserRepository' in your configuration.
What I have tried:
All other packages are a sub package of com.anonreporting.springboot, so i don't have to use component scan for them (correct me if i am wrong).
I have tried with componentScan as well with no success.
Moving everything in same package does help, but i want to structure it in this way only. I am using areospike with spring boot.
I have tried changing versions of dependencies also.
Any suggestions would be really helpful. Thank you
As far as I see you have not created UserRepository.java. Spring can not Autowire something that does not exist so you can try creating it in a package that is convenient for you. It should look something like this
#Repository
public interface UserRepository extends JpaRepository<User, Long>{}
You need to change annotation in your UserRepository.class from #Component to #Repository as spring-data is scanning for #Repository annotations.
The problem was with pom.xml only. I just replaced my pom with the following and everything worked.
<?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>com.example</groupId>
<artifactId>anonReporting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>anonReporting</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>spring-data-aerospike</artifactId>
<version>1.0.2.RELEASE</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>
</plugin>
</plugins>
</build>
</project>
I am trying to embed a spring cloud server with git hub. Following this link right here.
Also following the following documentation
pom.xml
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</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-security</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
...
</dependencies>
...
HelloWorldApplication.java
#SpringBootApplication
#EnableConfigServer
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
HelloWorldController.java
#RestController
#RequestMapping("/hello")
#RefreshScope
public class HelloWorldController {
#Value("${prop1:default}") private String prop1;
#Value("${prop2:default}") private String prop2;
#RequestMapping(value = "/world", method = RequestMethod.GET)
public String getHelloWorld() {
return new StringBuilder()
.append("Message: ")
.append(prop1).append(" ")
.append(prop2).append("!")
.toString();
}
}
application.properties
server.port=8080
bootstrap.properties
spring.application.name=root-server
spring.cloud.config.server.bootstrap=true
spring.cloud.config.server.prefix=/config
spring.cloud.config.server.git.uri= www.githubrepo/config
spring.cloud.config.server.git.username = username
spring.cloud.config.server.git.password = password
Spring cloud GIT Repository file
${user.home}/Desktop/config/root-server.properties
prop1=Hello
prop2=World
Output
localhost:8080/hello/world
Message: default default!
It should be Message: Hello World!