当前位置: 代码迷 >> java >> 在使用RequestMethod.GET刷新页面时,数据反复地从数据库返回到JSP。
  详细解决方案

在使用RequestMethod.GET刷新页面时,数据反复地从数据库返回到JSP。

热度:31   发布时间:2023-08-02 10:24:15.0

我正在尝试使用ModelMap将数据从DAO传递到JSP。 它可以工作,但是当我刷新该页面时,每次刷新都会重复出现相同的数据。 我希望刷新页面时不会一次又一次出现数据。 帮我解决这个问题。

    @Autowired
    private SelectInfo selectInfo; /* Instance of SelectInfo DAO class injected here, here the method of fetching data from databse is defined and fetched data is passed to GetInfo bean*/

    @Autowired
    private GetDetail getDetails; /* GetDetail is the bean where the values are stored which are coming from database */

    @RequestMapping(value="/selectInfo", method=RequestMethod.GET)

    public String registerComplete(ModelMap model,HttpSession session,HttpServletResponse res) {

    if(session.getAttribute("user")==null) {
           return "redirect:/";
    }else {     

    selectInfo.getInfo(); /*getInfo is the method defined in SelectInfo class which fetch data from database*/

    /* the values are adding in modelmap using getter method from GetInfo bean */
    model.put("cities", getDetails.getCities());
    model.put("theaters", getDetails.getTheaters());
    model.put("movies", getDetails.getMovies());
    model.put("dates", getDetails.getDates());
    model.put("timings", getDetails.getTimings());

    return "cities";
    }

因此,您不想在页面刷新时每次都调用数据库吗? 我认为您可以尝试在这种情况下进行缓存。 请在此处查看示例: :

您可以在控制器方法上添加注释。

@RequestMapping(value="/selectInfo", method=RequestMethod.GET)
@Cacheable
public String registerComplete(ModelMap model,HttpSession session,HttpServletResponse res) {
    //your code goes here
}

如果使用modelMap方式传递数据,则每次页面加载或刷新时都会传输数据。 为了一次加载数据,请使用和

在控制器类中创建新方法以返回数据

@RequestMapping(value="/cities", method=RequestMethod.GET)
public @ResponseBody Object registerComplete(){
  return getDetails.getCities()
}

在javascript中,检查sessionStorage是否为null,然后使用ajax加载数据。

$(document).ready(function(){

    if(sessionStorage.cities ==null){

        $.ajax({
            type : 'GET',
            url : "/cities",
            contentType:'application/json',
            data:JSON.stringify(data),
            success : function(response) {
                sessionStorage.cities =response;
            }
        });

    }

}) ;

这样,您可以限制每次刷新时的数据加载

缓存是避免不必要的数据库访问的自然方法。 Spring使用@Cacheable注释为此提供了支持。

如果您使用的是Spring Boot,那么事情会更轻松。 确保您的依赖项中包含spring-boot-starter-cache ,或者其中一个spring starters取决于spring-boot-starter-cache 然后,您可以像这样注释DAO方法:

@Component
public class SelectInfo {
  ...
  @Cacheable("dbInfo")
  public <returnType> getInfo() {
    // Implementation of the method
  }
  ...
}

建议将Cacheable批注放在DAO中的方法之上,因为它负责获取要缓存的实际数据。

如果您没有使用Spring Boot,则必须包括一个Cache Provider并为该提供程序配置一个bean。 可以在Spring Caching Docs 找到如何执行此操作的详细信息。