2017-07-19 40 views
0

我有一個servlet從HTML下拉頁面獲取參數。點擊按鈕時,數據被髮送到servlet。它首次發送數據,但如果我留在頁面上並從下拉菜單 中選擇不同的值並單擊提交按鈕,則新數據未設置到會話變量中。會話變量不會通過servlet提交

我的servlet位於下面。我需要修改DoGet方法嗎?同樣,它第一次工作,但會話變量之後不會改變。

@WebServlet("/ListStudentServlet") 
public class ListStudentServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 

    public ListStudentServlet() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
    } 

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

     String sessid = request.getParameter("studentid"); 
     ArrayList<FactStudentDataBean> result = new ArrayList<>(); 
     try (Connection con = JdbcUtil.getConnection()) { 

      String sql= "select F.Sessionid " 
        + "from FACT_STUDENT F " 
        + "where studentid = '"+sessid+"';"; 
      try (Statement st = con.createStatement()) { 

       ResultSet rs = st.executeQuery(sql); 
       while (rs.next()){ 
        result.add(new FactStudentDataBean(rs.getString(1))); 
       } 
       for (FactStudentDataBean factStudentDataBean : result) {  
        sessid = factStudentDataBean.getSessid();  
       }   
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 

     //Trying to set the session variable below, works the first time but anything after doesn't change 
     HttpSession session = request.getSession(true); 
     session.setAttribute("sessid", sessid); 
    } 
} 
+0

'request.getSes sion(true)'如果會話尚不存在,則創建一個新會話。會話cookie是否被設置爲下一次提交? –

+0

我該如何設置? – thedude865

回答

-1

檢查您在服務器端獲得的jsessionid值。如果兩者都不同,則通過傳遞false來代替true來嘗試獲取會話。

request.getSession(false); 

還轉到tomcat管理器應用程序和監視活動會話。

希望這會有所幫助。

+0

我嘗試將它設置爲(false),但仍然沒有任何結果。新數據不會發送回HTML – thedude865

0

你的代碼有點「髒」。首先:您爲什麼要寫這樣這個sql查詢?:

String sql= "select F.Sessionid " 
       + "from FACT_STUDENT F " 
       + "where studentid = '"+sessid+"';"; 

,不喜歡這個?:

String sql= "select F.Sessionid from FACT_STUDENT F where studentid = '"+sessid+"';"; 

二:請儘量使用prepareStatement而不是createStatement(爲了解釋什麼我告訴請看這樣一個問題:prepareStatement vs executeStatement

而對於現在的答案:我思,你必須使用session.getAttribute("sessid", sessid);

+0

,您是錯誤的。這不是你如何應用session.getAttribute。它不需要兩個變量作爲參數。 – thedude865