开发者

Get specific value from Object in spring controller

开发者 https://www.devze.com 2023-03-05 06:54 出处:网络
I have a Student Class, StudentDao Class, StudentDetails Class and StudentController Student Class have following instances:

I have a Student Class, StudentDao Class, StudentDetails Class and StudentController

Student Class have following instances:

 private Strin开发者_运维知识库g studentId;
 private String studentName;
 private String studentGrade;

StudentDao gets these details from DB, StudentDetails Class returns a list of these details in following method:-

public List<Student> getSpecificStudentInfo(String studentId)
{
    List<Student> studentInfo=studentDao.getSpecificStudentInfo(studentId);     
    return studentInfo;

}

In my controller I use HashMap to get student details like

public Map<String, Object> referenceData(HttpServletRequest req)throws ServletException, IOException 
{

    String studentId=req.getParameter("studentId");
    Map<String, Object> studentRecord = new HashMap<String, Object>();
studentRecord.put("students",studentDetails.getSpecificStudentInfo(studentId));
    return studentRecord;
}

I m able to display these values in Jsp using students.studentName, students.studentGrade, etc. which is 1 requirement.

But my problem is that I want to use studentName and studentGrade further in my controller in referenceData method (before the return statement ofcourse) but I m not getting it the right way.


i don't think that i did understand your question. in referenceData, you have studentId already from request. You could still extract grade using a loop over list.

public Map<String, Object> referenceData(HttpServletRequest req)throws ServletException, IOException 
{

    String studentId=req.getParameter("studentId");
    Map<String, Object> studentRecord = new HashMap<String, Object>();
    List<Student> listOfStudents = studentDetails.getSpecificStudentInfo(studentId); 
    String studentGrad = getGradeFor(studentId); 
studentRecord.put("students",listOfStudents);
    return studentRecord;
}
/* check nulls, empty list etc. */
public String getGradeFor(List<Student> listOfStudent, String id) {
       for (Student student: listOfStudent) {
            if (student.getId().equals(id)) return student.getGrade();
       }
       return null;
}

or you could build your database query more effectively and thus you get only one object in your list. that will be the student which you are looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号