【发布时间】:2019-07-08 21:59:34
【问题描述】:
在 Application.java 中,我从 MongoDB 数据库中读取了集合中的每个文档。我将所有这些文档存储在一个 ArrayList 中。我想知道如何将此 ArrayList 传递给 Controller 类?
这是一个 Spring Boot Web 应用程序。我正在使用 Spring MVC 来处理这个项目。
这个类是Application.java。我从 MongoDB 中取出所有鞋子并将它们存储在 list 变量中。
public class Application implements CommandLineRunner {
@Autowired
private ShoeRepository repository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
// fetch all shoes
List<Shoe> list = new ArrayList<>();
System.out.println("Shoes found with findAll():");
System.out.println("-------------------------------");
for (Shoe shoe : repository.findAll()) {
//System.out.println(customer);
list.add(shoe);
}
System.out.println("all shoes have been saved to the list");
}
}
这个类是我的控制器类:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class GreetingController {
@RequestMapping(value = "/greeting" ,method = RequestMethod.GET)
public String greeting(@RequestParam(name="name", required=true) List<Shoe> list, Model model) {
model.addAttribute("name", list.get(0).asin);
return "greeting";
}
}
谁能告诉我如何将Application类中的list变量传递给Controller类?我想在视图中可视化存储在列表变量中的数据。
【问题讨论】:
-
生活忙碌,但你有没有试过阅读:spring.io/guides/gs/accessing-data-mongodb
-
@emotionlessbananas。是的,我已经阅读了它,但它只向我展示了如何读取 Application.java 中的数据。如果我在 Application.java 中获取数据,我想知道如何将这些数据传递给控制器和视图?我想知道如何在 Controller 类的方法中读取数据?你能回答我的问题吗?
标签: java mongodb spring-boot spring-mvc