[Solved] Cannot call sendRedirect() after the response has been committed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<%      
        JudgeName judge = new JudgeName();
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("userName");
        if (name != null) {
            session.setAttribute("name", name);
            session.setMaxInactiveInterval(30);
        else {
            response.sendRedirect("index.jsp");
            /* return; */
        }
        String pwd = request.getParameter("pwd");
        if (judge.isExists(name)) {
            if (pwd.equals("12345")) {
                response.sendRedirect("succeed.jsp");
                /*return;*/
            else {
                session.setAttribute("msg""password error");
                response.sendRedirect("failed.jsp");
                /*return;*/
            }
        else {
            session.setAttribute("msg""用户名不存在");
            response.sendRedirect("failed.jsp");<br>              /*return;*/
            
        }
    
    %>

The main function of this page is to compare the data of request to judge, by the form form into the page and will not error, but due to the logic of confusion caused by direct access to the page will occur twice the redirection of response, so the error is reported

Logical errors cause the response may be executed twice, two solutions.

1. Modify the logic

2. add return after the response.

3. but you can not add return after the last response; otherwise, an error is reported.

 

The following is the modified code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%
        JudgeName judge = new JudgeName();
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("userName");
        String pwd = request.getParameter("pwd");
        if (name != null && pwd != null) {
            session.setAttribute("name", name);
            session.setMaxInactiveInterval(30);
            
            if (judge.isExists(name)) {
                if (pwd.equals("12345")) {
                    response.sendRedirect("succeed.jsp");
                    
                else {
                    session.setAttribute("msg""password error");
                    response.sendRedirect("failed.jsp");
                }
                
            else {
                session.setAttribute("msg""用户名不存在");
                response.sendRedirect("failed.jsp");
            }
        else {
            response.sendRedirect("index.jsp");
        }
    %>

Similar Posts: