How to initialize Spring Data JPA Page to null?

B37*_*378 2 spring http spring-mvc spring-security spring-data-jpa

This is a code snippet of my project. Here I'm trying to get paginated data using Spring Data JPA. The pagination part works fine. However when searchParameter is NULL then I just want to return empty create a blank page in my UI

public Page<AccessLog> getDataInRange(long fromTime, long toTime, String searchParameter, Integer start,
                                          Integer length) {
        Page<AccessLog> accessPage;
        if (searchParameter != null) {
            accessPage = accessRepository.findBySystemTimestampBetween(fromTime, toTime,
                    new PageRequest(start, length));
        } else
            accessPage = null;
        return accessPage;
    }
Run Code Online (Sandbox Code Playgroud)

However, this give an error when search parameter is null

执行 SpringSecurity 应用程序时出现异常 java.lang.NullPointerException: null

这是由于设置为 accessLogPage 的“空”值引起的。

有任何想法吗?

yue*_*n26 8

从 Spring Boot 2.0 开始,您可以使用Page.empty()返回 empty Page


Abd*_*han 1

searchParameter在控制器本身中处理。

在你的控制器中尝试这样的事情

@Controller
public class BaseController {

    @RequestMapping("/")
    public ModelAndView welcome(...) {

        //get your searchParameter here

        if(searchParameter == null) {
            return new ModelAndView("blank-page");
        }

        //call your service layer to fetch the data and then return the actual page

        ModelAndView modelAndView = new ModelAndView("actual-page");
        modelAndView.addObject("data", FETCHED_DATA_FROM_SERVICE_LAYER); 
        return new ModelAndView("actual-page");

    }

}
Run Code Online (Sandbox Code Playgroud)