会话变量不会通过servlet提交更改

时间:2017-07-19 16:38:12

标签: javascript java jsp servlets

我有一个从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);
    }
}

2 个答案:

答案 0 :(得分:0)

你的代码有点&#34;脏&#34;。首先:你为什么要编写这样的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);

答案 1 :(得分:-1)

检查您在服务器端获得的jsessionid值。如果两者都不同,那么尝试通过传递false而不是true来获取会话。

request.getSession(false);

还可以转到tomcat manager应用程序并监视活动会话。

希望这会有所帮助。