提交响应后无法调用sendRedirect() [英] Cannot call sendRedirect() after the response has been committed

查看:6937
本文介绍了提交响应后无法调用sendRedirect()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个过滤器,用于检查会话是否存在.如果不存在,我会使用response.sendRedirect()将用户重定向到登录页面.

i have a filter that checks if a session exists. If it doesn't exist i redirect the user, with a response.sendRedirect(), to the login page.

在某些页面中它可以工作,而在其他页面中则不能.我收到此错误Cannot call sendRedirect() after the response has been committed.

In some pages it works, in others it doesnt'. I get this error Cannot call sendRedirect() after the response has been committed.

似乎如果我在jsp页面中删除了某些代码部分(如<%=variable%>),它会起作用. 但是,正如我所说,即使我有类似<%=variable%>的代码,它在其他jsp页面中也可以工作. 我真的不明白是什么问题.

It seems that if i delete some parts of code like <%=variable%> in my jsp pages it works. But, as i said, in other jsp pages it works even if i have code like <%=variable%>. I really can't understand what's the problem.

我在该论坛上阅读了一些类似的帖子,但没有找到解决方法.

I read some posts similar on this forum but i didn't find a solution.

这是我的过滤器

public class SessionFilter implements Filter {

    public void destroy() {}

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        try {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            String url = request.getServletPath();

            HttpSession session = request.getSession(false);

            /*caso in cui il webserver non abbia ancora creato la sessione*/
            if (null == session) {
                reindirizza = true;
            } else {
                /*caso in cui il webserver abbia creato la sessione e l'utente  sia loggato*/
                if(session.getAttribute("loggato")!=null && session.getAttribute("loggato").equals("si")) {
                    reindirizza = false;
                }
                /*caso in cui il webserver abbia creato la sessione e l'utente  non sia loggato*/
                else {
                    reindirizza = true;
                }
            }

            chain.doFilter(req, res);
            if(reindirizza) {
                response.sendRedirect("Gestione.jsp?message=Sessione scaduta o non valida. Effettuare il Login");
            }
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void init(FilterConfig config) throws ServletException { }
}

推荐答案

response.sendRedirect("jsppage")之后,您也应该像这样返回它

I also faced the same issue after response.sendRedirect("jsppage") you should return it like

return;

sendredirect方法之后添加上述语句,然后再无问题.

Add above statement after sendredirect method then No Issue.

这篇关于提交响应后无法调用sendRedirect()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆