【发布时间】:2015-08-17 08:55:20
【问题描述】:
我的代码是
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=request.getSession(false);
if(session==null){
response.sendRedirect(request.getContextPath());
}else{
doPost(request,response);
}
}
这个 servlet 的 url 模式是 /loginServlet。 我编写了这段代码,以便如果用户登录并通过在 url 上按 enter 发出获取请求,则必须将请求转发到 doPost() 否则,如果用户未登录,则他会进入登录页面
但问题是它总是返回登录页面,这意味着 request.getSession(false) 总是返回 null
我该如何解决这个问题
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
String commun=request.getParameter("commun");
String password=request.getParameter("password");
Connection conn = null;
Statement statement = null;
try{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/community");
conn = ds.getConnection();
statement = conn.createStatement();
String sql = "select memberragas from windowragas where memberragas='"+name+"' and liquid_key='"+commun+"' and chabhiragas='"+password+"'";
ResultSet rs =statement.executeQuery(sql);
if(rs.next()){
System.out.println("welcome "+name+"");
HttpSession session=request.getSession();
session.setAttribute("name", name);
session.setAttribute("commun", commun);
RequestDispatcher rd = request.getRequestDispatcher("/homey");
rd.forward(request, response);
}else{
System.out.println("either ur username or password or community was wrong");
response.sendRedirect(request.getContextPath());
}
}
catch (NamingException ex) {
System.err.println(ex);
} catch (SQLException ex) {
System.err.println(ex);
}finally {
try {
if (statement != null) statement.close();
if (conn != null) conn.close(); // return to pool
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
在 doPost() 中我是第一次创建会话
【问题讨论】:
-
以上代码永远不会创建会话。尝试
request.getSession(true);,如果会话不存在,它将创建一个新会话,否则如果它已经创建,它将返回该会话对象 -
@Amit.rk3 先生,我不想创建会话,我只想知道是否已经有会话
-
如果它在那里我想将请求发送到 doPost() ,n 如果没有附加会话,那么它必须转到登录页面
-
用户登录时如何创建新会话?您确定在您尝试创建会话时会创建会话吗?
-
@user3443275 您可以在创建会话时发布代码吗?