-1

以下は、セッションを渡したい 2 つのサーブレットです。

問題は、SuccessPage サーブレットに移動するときにセッションの受け渡しが行われるが、Failure サーブレットに移動するときには行われないことです。

ログイン サーブレットdoGet()メソッド:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws    
ServletException, IOException{
    PrintWriter out=response.getWriter();
    response.setContentType("text/html");
    String userName=request.getParameter("userName");
    String userPass=request.getParameter("userPassword");
    String userRePass=request.getParameter("userRePassword");
    try{
        String query="Select VendorName from vendorinfo where VendorPass=?";
        connection1=Connection_Class.getInstance().getConnection();
        ptmt=connection1.prepareStatement(query);
        ptmt.setString(1,userPass);
        rs=ptmt.executeQuery();
        if(rs.next()&& userName.equalsIgnoreCase(rs.getString("VendorName"))){
        HttpSession session=request.getSession(true);
        session.setAttribute("loggedVendor",rs.getString(1));
        //this is working fine...im able to get the userName in the next servlet
        ServletContext context = getServletContext();
        RequestDispatcher dispatcher=context.getRequestDispatcher("/SuccessPage");
        dispatcher.forward(request,response);
        }
        else{  //this is not working .....whats the problem here ?
            request.setAttribute("wrongUser",userName);
            ServletContext context=getServletContext();
            RequestDispatcher dispatcher=context.getRequestDispatcher("/Failure");
            dispatcher.forward(request,response);
        }
    }
    catch(SQLException e){
        e.printStackTrace();
    }
}

失敗したサーブレットdoGet()メソッド:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws  
ServletException, IOException {
/*all i want to do here is that I want to get the userName from the previous servlet but its 
not displaying that and its displaying null */
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    out.println("<body bgcolor=#F3EEF0><h1>");
    out.println("<center>");
    HttpSession session=request.getSession(false);
    out.println("This is a failure page");
    out.println(session.getAttribute("wrongUser"));
    out.println("</center></h1></body>");
}

コードに何か問題がありますか?

4

1 に答える 1

1

最初のサーブレットのセッションではなく、キー「wrongUser」のデータをリクエストに配置しています。

 request.setAttribute("wrongUser",userName);

Failure Servlet のセッションから取得します。

session.getAttribute("wrongUser");

両方の場所で「セッション」を使用するか、両方の場所で「リクエスト」を使用します。したがって、request.setAttribute() を使用する場合は、request.getAttribute() を使用してください。session.setAttribute() を使用する場合は、session.getAttribute() を使用します。

推奨: request を使用して、不必要にセッションのロードを開始しないようにします。この要求/応答サイクルの範囲を超えて、この値は必要ありません。

于 2013-05-28T10:10:41.277 に答える