#java #mongodb #jsp
#java #mongodb #jsp
Вопрос:
я создаю crud-приложение springboot mongodb, в котором данные извлекаются из mongodb и отображаются в displayPlayers.jsp, но когда я выполняю findById(), это создает проблемы, поскольку это доступно только в optional() и не может быть повторено на странице jsp интерфейса.
Ниже приведен класс контроллера, displayPlayers.jsp , displaydetails.jsp, CsvServiceImpl.java
Класс контроллера
package com.durlabh.controllers;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.durlabh.document.Model;
import com.durlabh.repositories.ModelRepository;
import com.durlabh.services.CsvServiceImpl;
@Controller
public class MainController {
@Autowired
CsvServiceImpl csvFileServices;
@Autowired
ModelRepository modelRep;
@RequestMapping("/{id}")
public String displayDetails( @PathVariable(value="id")String id, ModelMap modelMap){
Optional<Model> detail = csvFileServices.getDetailsById(id);
// Optional<Model> detail = modelRep.findById(id);
modelMap.addAttribute("details", detail);
System.out.println("yeass");
return "/WEB-INF/jsps/displayDetails.jsp";
}
@RequestMapping("/players")
public String displayPlayers(ModelMap modelMap){
List<Model> mod= csvFileServices.getAll();
modelMap.addAttribute("mode", mod);
System.out.println("yes");
return "/WEB-INF/jsps/displayPlayers.jsp";
}
}
displayDetails.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Players:</h2>
<table>
<c:forEach items="${details}" var="detailss">
<tr>
<td>${detailss.age }</td>
<td>${detailss.height }</td>
<td>${detailss.weight}</td>
<td>${detailss.playedPositions }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
displayPlayers.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Players:</h2>
<table>
<c:forEach items="${mode }" var="modes">
<tr>
<td><a href="id=${modes.id}">${modes.name }</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
CsvServiceImpl.java
package com.durlabh.services;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.durlabh.document.Model;
import com.durlabh.repositories.ModelRepository;
import com.durlabh.utils.CsvUtil;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
@Service
public class CsvServiceImpl implements CsvService {
@Autowired
ModelRepository modelRep;
public void store(MultipartFile csvfile) {
Reader fileReader=null;
CsvToBean<Model> csvToBean=null;
List<Model> models=new ArrayList<Model>();
try (
Reader reader=new BufferedReader(new InputStreamReader(csvfile.getInputStream()))){
csvToBean=new CsvToBeanBuilder(reader).withType(Model.class).withIgnoreLeadingWhiteSpace(true).build();
models= csvToBean.parse();
modelRep.saveAll(models);
}catch(Exception e) {
throw new RuntimeException("Fail!->message=" e.getMessage()) ;
}
}
public List<Model> getAll() {
return modelRep.findAll();
}
@Override
public Optional<Model> getDetailsById(String id) {
Optional<Model> byId = modelRep.findById(id);
System.out.print(byId.get());
return byId;
}
}
findById доступен в optional(), а не в List, и я не могу выполнить итерацию элементов, связанных с этим идентификатором, на странице displaydetails.jsp
Ответ №1:
этот метод findById будет выполнять поиск только по уникальному ключу. поэтому он всегда будет возвращать только один объект. Вы должны определить другой метод, который будет запрашивать заданную переменную и возвращать список
Комментарии:
1. можете ли вы привести пример этого
2. для этого вы можете поделиться своим классом модели
3. я поделился классом модели в качестве ответа
4. В соответствии с вашей моделью id помечается @Id, что делает эту переменную уникальной. Поэтому поиск по идентификатору никогда не предоставит список в качестве вывода. Поскольку это уникальная переменная, у двух объектов не будет одинакового идентификатора
Ответ №2:
@Avesh Singh это мой класс модели
package com.durlabh.document;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.opencsv.bean.CsvBindByName;
@Document(collection="bet")
public class Model {
@Id
private String id;
@CsvBindByName
private Long ranking;
@CsvBindByName
private Long seasonid;
@CsvBindByName
private String seasonName;
@CsvBindByName
private Long tournamentId;
@CsvBindByName
private Long tournamentRegionId;
@CsvBindByName
private String tournamentRegionCode;
@CsvBindByName
private String regionCode;
@CsvBindByName
private String tournamentName;
@CsvBindByName
private String tournamentShortName;
@CsvBindByName
private String firstName;
@CsvBindByName
private String lastName;
@CsvBindByName
private Long playerId;
@CsvBindByName
private boolean isActive;
@CsvBindByName
private boolean isOpta;
@CsvBindByName
private Long teamId;
@CsvBindByName
private String teamName;
@CsvBindByName
private String playedPositions;
@CsvBindByName
private Long age;
@CsvBindByName
private Long height;
@CsvBindByName
private Long weight;
@CsvBindByName
private String positionText;
@CsvBindByName
private Long apps;
@CsvBindByName
private Long subOn;
@CsvBindByName
private Long minsPlayed;
@CsvBindByName
private double rating;
@CsvBindByName
private Long goal;
@CsvBindByName
private Long assistTotal;
@CsvBindByName
private Long yellowCard;
@CsvBindByName
private Long redCard;
@CsvBindByName
private double shotsPerGame;
@CsvBindByName
private double serialWonPerGame;
@CsvBindByName
private Long manOfTheMatch;
@CsvBindByName
private String name;
@CsvBindByName
private boolean isManOfTheMatch;
@CsvBindByName
private String playedPostionsShort;
@CsvBindByName
private double passSuccess;
public Model() {
}
public Model(String id,Long ranking, Long seasonid, String seasonName, Long tournamentId, Long tournamentRegionId,
String tournamentRegionCode, String regionCode, String tournamentName, String tournamentShortName,
String firstName, String lastName, Long playerId, boolean isActive, boolean isOpta, Long teamId,
String teamName, String playedPositions, Long age, Long height, Long weight, String positionText, Long apps,
Long subOn, Long minsPlayed, double rating, Long goal, Long assistTotal, Long yellowCard, Long redCard,
double shotsPerGame, double serialWonPerGame, Long manOfTheMatch, String name, boolean isManOfTheMatch,
String playedPostionsShort, double passSuccess) {
super();
this.id=id;
this.ranking = ranking;
this.seasonid = seasonid;
this.seasonName = seasonName;
this.tournamentId = tournamentId;
this.tournamentRegionId = tournamentRegionId;
this.tournamentRegionCode = tournamentRegionCode;
this.regionCode = regionCode;
this.tournamentName = tournamentName;
this.tournamentShortName = tournamentShortName;
this.firstName = firstName;
this.lastName = lastName;
this.playerId = playerId;
this.isActive = isActive;
this.isOpta = isOpta;
this.teamId = teamId;
this.teamName = teamName;
this.playedPositions = playedPositions;
this.age = age;
this.height = height;
this.weight = weight;
this.positionText = positionText;
this.apps = apps;
this.subOn = subOn;
this.minsPlayed = minsPlayed;
this.rating = rating;
this.goal = goal;
this.assistTotal = assistTotal;
this.yellowCard = yellowCard;
this.redCard = redCard;
this.shotsPerGame = shotsPerGame;
this.serialWonPerGame = serialWonPerGame;
this.manOfTheMatch = manOfTheMatch;
this.name = name;
this.isManOfTheMatch = isManOfTheMatch;
this.playedPostionsShort = playedPostionsShort;
this.passSuccess = passSuccess;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getRanking() {
return ranking;
}
public void setRanking(Long ranking) {
this.ranking = ranking;
}
public Long getSeasonid() {
return seasonid;
}
public void setSeasonid(Long seasonid) {
this.seasonid = seasonid;
}
public String getSeasonName() {
return seasonName;
}
public void setSeasonName(String seasonName) {
this.seasonName = seasonName;
}
public Long getTournamentId() {
return tournamentId;
}
public void setTournamentId(Long tournamentId) {
this.tournamentId = tournamentId;
}
public Long getTournamentRegionId() {
return tournamentRegionId;
}
public void setTournamentRegionId(Long tournamentRegionId) {
this.tournamentRegionId = tournamentRegionId;
}
public String getTournamentRegionCode() {
return tournamentRegionCode;
}
public void setTournamentRegionCode(String tournamentRegionCode) {
this.tournamentRegionCode = tournamentRegionCode;
}
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public String getTournamentName() {
return tournamentName;
}
public void setTournamentName(String tournamentName) {
this.tournamentName = tournamentName;
}
public String getTournamentShortName() {
return tournamentShortName;
}
public void setTournamentShortName(String tournamentShortName) {
this.tournamentShortName = tournamentShortName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getPlayerId() {
return playerId;
}
public void setPlayerId(Long playerId) {
this.playerId = playerId;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isOpta() {
return isOpta;
}
public void setOpta(boolean isOpta) {
this.isOpta = isOpta;
}
public Long getTeamId() {
return teamId;
}
public void setTeamId(Long teamId) {
this.teamId = teamId;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getPlayedPositions() {
return playedPositions;
}
public void setPlayedPositions(String playedPositions) {
this.playedPositions = playedPositions;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
public Long getHeight() {
return height;
}
public void setHeight(Long height) {
this.height = height;
}
public Long getWeight() {
return weight;
}
public void setWeight(Long weight) {
this.weight = weight;
}
public String getPositionText() {
return positionText;
}
public void setPositionText(String positionText) {
this.positionText = positionText;
}
public Long getApps() {
return apps;
}
public void setApps(Long apps) {
this.apps = apps;
}
public Long getSubOn() {
return subOn;
}
public void setSubOn(Long subOn) {
this.subOn = subOn;
}
public Long getMinsPlayed() {
return minsPlayed;
}
public void setMinsPlayed(Long minsPlayed) {
this.minsPlayed = minsPlayed;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public Long getGoal() {
return goal;
}
public void setGoal(Long goal) {
this.goal = goal;
}
public Long getAssistTotal() {
return assistTotal;
}
public void setAssistTotal(Long assistTotal) {
this.assistTotal = assistTotal;
}
public Long getYellowCard() {
return yellowCard;
}
public void setYellowCard(Long yellowCard) {
this.yellowCard = yellowCard;
}
public Long getRedCard() {
return redCard;
}
public void setRedCard(Long redCard) {
this.redCard = redCard;
}
public double getShotsPerGame() {
return shotsPerGame;
}
public void setShotsPerGame(double shotsPerGame) {
this.shotsPerGame = shotsPerGame;
}
public double getSerialWonPerGame() {
return serialWonPerGame;
}
public void setSerialWonPerGame(double serialWonPerGame) {
this.serialWonPerGame = serialWonPerGame;
}
public Long getManOfTheMatch() {
return manOfTheMatch;
}
public void setManOfTheMatch(Long manOfTheMatch) {
this.manOfTheMatch = manOfTheMatch;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isManOfTheMatch() {
return isManOfTheMatch;
}
public void setManOfTheMatch(boolean isManOfTheMatch) {
this.isManOfTheMatch = isManOfTheMatch;
}
public String getPlayedPostionsShort() {
return playedPostionsShort;
}
public void setPlayedPostionsShort(String playedPostionsShort) {
this.playedPostionsShort = playedPostionsShort;
}
public double getPassSuccess() {
return passSuccess;
}
public void setPassSuccess(double passSuccess) {
this.passSuccess = passSuccess;
}
@Override
public String toString() {
return "Model [id=" id ", ranking=" ranking ", seasonid=" seasonid ", seasonName=" seasonName
", tournamentId=" tournamentId ", tournamentRegionId=" tournamentRegionId
", tournamentRegionCode=" tournamentRegionCode ", regionCode=" regionCode ", tournamentName="
tournamentName ", tournamentShortName=" tournamentShortName ", firstName=" firstName
", lastName=" lastName ", playerId=" playerId ", isActive=" isActive ", isOpta=" isOpta
", teamId=" teamId ", teamName=" teamName ", playedPositions=" playedPositions ", age="
age ", height=" height ", weight=" weight ", positionText=" positionText ", apps="
apps ", subOn=" subOn ", minsPlayed=" minsPlayed ", rating=" rating ", goal=" goal
", assistTotal=" assistTotal ", yellowCard=" yellowCard ", redCard=" redCard
", shotsPerGame=" shotsPerGame ", serialWonPerGame=" serialWonPerGame ", manOfTheMatch="
manOfTheMatch ", name=" name ", isManOfTheMatch=" isManOfTheMatch ", playedPostionsShort="
playedPostionsShort ", passSuccess=" passSuccess "]";
}
}