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



我有一个从HTML下拉页面获取参数的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);
}
}

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

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

request.getSession(false);

还可以转到雄猫管理器应用程序并监视活动会话。

希望这会有所帮助。

最新更新