使用弹簧闪光范围

时间:2017-06-19 08:04:20

标签: java spring spring-mvc spring-boot

我有一个控制器有两种方法。

第一种方法是从具有链接的数据库中获取结果。我没有直接暴露链接,因为我不希望任何用户修改链接并提交请求。

当用户点击链接时,我将在第二种方法中获取搜索结果列表中链接的索引,并且我希望搜索结果在第二种方法中可用。我尝试使用FlashMapRequestAttributes,但我丢失了数据。

我使用Thymleaf搭配弹簧靴1.5.3。以下是示例代码。

class MyObject {

    int id;
    String docId;

    //getters and setters
}

我的控制器

@RestController
public class DataController{

    @Autowired
    DataService dataService.

    @RequestMapping("/search" method=RequestMethod.POST)
    public String fetchData(Model model,RequestAttributes rs){
        List<MyObject> objectList=dataService.fetchData();
        rs.addFlashAttributes("list",dataService.fetchData());
        return VIEW_NAME;
    }


    @RequestMapping("/download/{id}", method=RequestMethod.GET)
    public String downloadData(@PathVariable int id,RequestAttributes rs){
        rs.getFlashAttribute("list").get(id);
        //some logic
    }
}

我得到get(id)的空指针异常,因为我无法获取我在方法1中添加的列表。

1 个答案:

答案 0 :(得分:0)

当您输入第二个请求的第二个方法时。在第一次调用中设置的所有请求范围数据(包括请求属性)都将丢失。 解决方案可能是使用会话,但对于每个用户,您将存储可能非常大的一些对象的列表。我会考虑其他解决方案:让你的ID到数据库ID在一个地方映射(数据服务)。

相关问题