Servlet会话不会持久化

时间:2015-02-20 11:53:45

标签: java session servlets cookies

我有两个servlet第一个servlet用于获取和转换根据类似于旧手机的小键盘给出的电话号码。电信号码(前四位数字)将保存在cookie中,而转换后的号码将保存在会话对象中(这是教授要求的)。

输入示例:0912 - ABCDEFG输出应为0912-2223334。

第二个servlet将通过requestDispatcher输出存储在cookie和会话对象中的数据,但是当输入也为null时,会话数据将变为null。

servlet1:

public class ConvertServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String num;
    private String telco;
    private HttpSession session;
    private Cookie cTelco;
    private RequestDispatcher rd;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        String convertedNum = "";
        session = request.getSession();
        num = request.getParameter("number");
        telco = request.getParameter("telco");
        rd = request.getRequestDispatcher("Display");

        if (num != null || num != "")
        {
            for (byte i = 0; i < num.length(); i++)
            {
                switch(num.charAt(i))
                {
                    case 'A':
                    case 'B':
                    case 'C': convertedNum += "2"; break;
                    case 'D': 
                    case 'E':
                    case 'F': convertedNum += "3"; break;
                    case 'G':
                    case 'H': 
                    case 'I': convertedNum += "4"; break;
                    case 'J':
                    case 'K':
                    case 'L': convertedNum += "5"; break;
                    case 'M':
                    case 'N':
                    case 'O': convertedNum += "6"; break;
                    case 'P':
                    case 'Q':
                    case 'R':
                    case 'S': convertedNum += "7"; break;
                    case 'T':
                    case 'U':
                    case 'V': convertedNum += "8"; break;
                    case 'W':
                    case 'X':
                    case 'Y':
                    case 'Z': convertedNum += "9"; break;
                }
            }

            session.setAttribute("number", telco+convertedNum);
            cTelco = new Cookie("telco", telco);
        }
        response.addCookie(cTelco);
        rd.forward(request, response);
    }

}

servlet2:

public class DisplayNumber extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.println("The converted number is " + request.getSession().getAttribute("number"));
    }

}

假设代码具有各自的import语句,只是为了减少帖子中的代码长度。

0 个答案:

没有答案