简体   繁体   中英

Java, Spring MVC, repository, Maven,

Here is some file which I need to call.

1st user search it by there first_name or last_name or both.

After click on search button we call controller then through controller we call service and through service we call studentRepository and through that we call AbstractRepository.java 's method ie findByQuery but how to call that method and retrieve that instance and show the searched name on jsp file?

index.jsp

<form action="${pageContext.request.contextPath}/staff/student/searchStudent" method="post">
            <div class="form-group col-sm-3">
                <input type="text" name="firstName" class="form-control input-lg" placeholder="First Name" required/>
            </div>
            <div class="form-group col-sm-3">
                <input type="text" name="lastName"  class="form-control input-lg"placeholder="Last Name" required/>
            </div>
            
            <input type="submit" class="btn btn-primary" value="Search" /> 
        </form>

studentController.java

@RequestMapping(value = "/searchStudent", method = RequestMethod.POST)
public ModelAndView searchStudent(@RequestParam(name = "firstName", required = true) String firstName,
        @RequestParam(name = "lastName", required = true) String lastName, HttpServletRequest request) {

    studentService.search(firstName, lastName);
    ModelAndView mdlv = getView("add");
    
    return mdlv;
}

studentService.java

public Student search(String firstName, String lastName)
{
            
    Student student = studentRepository.searchByName(firstName,lastName);
    if(student != null)
    {
        System.out.println("Search Successfully done !");
    }
    else
    {
        System.out.println("Wrong entries");
    }
    
    
    
    return student;
    
}

studentRepository.java

    @Repository("studentRepository")
@Transactional
public class StudentRepository extends AbstractRepository<Student, Long> {

AbstractRepository.java

    public StudentRepository() {
        super(Student.class);
        }
    }

  public List<T> findByQuery(CriteriaQuery<T> query) {
    return this.entityManager.createQuery(query).getResultList();
}

In the StudentController (save the found student in the ModelAndView ):

Student student = studentService.search(firstName, lastName);
ModelAndView mdlv = getView("add");
mdlv.addObject("student", student);

return mdlv;

And then on the add view you can display the student using eg ${student.name} (assuming you have getter getName() ), or any other accessor/getter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM