Reputation: 15646
Spring Boot 2
in build.gradle:
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'war' // to use JSP
}
group = 'ru.otus.sd'
version = '0.0.1'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper:9.0.30'
implementation 'com.google.code.gson:gson:2.7'
implementation 'javax.servlet:jstl:1.2'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
in application.yml:
server:
port: 8090
spring:
http:
converters:
preferred-json-mapper: gson
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
here my controller:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
@RestController
public class UserController {
@GetMapping("/users")
public List<User> getAllUsers() {
return Collections.singletonList(new User() {{
setId(1);
setName("Peter");
}});
}
}
Here model:
public class User {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "\nUser{" +
"id = " + id +
", name = '" + name + '\'' +
'}';
}
}
But when try to open http://localhost:8090/users
I get
[
null
]
Why not return this:
[
{
"id": 1,
"name": "Peter"
}
]
?
Upvotes: 0
Views: 104
Reputation: 226
Try to make the response object old-school. Create new array list, create new User, set its id, set its name, add it to the list and return the list
Upvotes: 1