多个iframe中的Java servlet会话

时间:2015-06-19 20:42:08

标签: java session servlets iframe servlet-filters

我有一个网站,用四个iframe称之为www.main.com,将www.iframe.com/foo加载到每个iframe中。在初始加载www.iframe.com/foo时,我从servlet(foo)调用config.bar()来将一些用户数据加载到会话中。在我调用config.bar()之前,我正在检查配置是否已经加载到会话中,如果是,请跳过config.bar()中的fetch并从会话加载。

我的问题是,由于会话尚未在foo中建立,因此我获得了4个唯一的会话ID,因此对config.bar()进行4次调用。当我刷新www.main.com页面时,四个iframe会再次加载,但会分配第一个iframe的sessionid来加载(来自上一个请求)。

我尝试将逻辑移动到过滤器,希望它能做对,但它没有效果。是否可以在iframe中使用不同的URL加载servlet多次,并且在初始加载时只有一个会话ID?

这里有一些片段来展示我正在尝试做的事情:

www.iframe.com/foo:

//--FooController.java
@Controller
class FooController
{
    @RequestMapping(value = "/foo", method = RequestMethod.GET)
    public String foo(Model model, HttpServletRequest request)
    {
        Config c = request.getSession().getAttribute("config");
        reqest.setAttribute("bazz", bazz.doMagic(c));
        return "foo";
    }
}

//--ConfigFilter.java
public class ConfigFilter implements Filter
{
    @Autowired
    private ConfigService cs;

    public void init(FilterConfig config) throws ServletException
    {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;

        HttpSession sess = req.getSession();

        //first request these are different for each iframe
        //second request they all match
        System.out.println("sess="+sess.getId());

        //only fetch config if not in session    
        if(sess.getAttribute("config") == null) {
            sess.setAttribute("config", cs.getCfg());

        // Pass request back down the filter chain
        chain.doFilter(request,response);
    }

    public void destroy()
    {
    }
}

www.main.com:

<html>
<body>
    <iframe src="http://www.iframe.com/foo?page=1"></iframe>
    <iframe src="http://www.iframe.com/foo?page=2"></iframe>
    <iframe src="http://www.iframe.com/foo?page=3"></iframe>
    <iframe src="http://www.iframe.com/foo?page=4"></iframe>
</body>
</html>

0 个答案:

没有答案
相关问题