Преамбула Пишу чат. Есть несколько сервлетов и есть фильтр, который не позволяет обращатся к сервлетам если нет сессии. Сервлеты по надобности диспатчерятся на jspx страницы. В программе только два места, где явно идет работа с сессией: это собственно фильтр и LoginServlet.
Амбула Дважды обратившись, например, к сервлету на терминале пишется :
| Код | 18:50:18,484 INFO [STDOUT] requestURL: /vchat/login 18:50:18,484 INFO [STDOUT] sesion= null 18:50:28,765 INFO [STDOUT] requestURL: /vchat/login 18:50:28,765 INFO [STDOUT] sesion= org.apache.catalina.session.StandardSessionFacade@1ed7afd
|
ОТКУДА ВЗЯЛАСЬ СЕССИЯ ??????
Вот код фильтра: (LoginServlet развернут на /vchat/login
| Код | public class SessionCheckerFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { }
public void destroy() { }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String contextPath = req.getContextPath(); HttpSession session = req.getSession(false); System.out.println("requestURL: "+req.getRequestURI()); System.out.println("sesion= "+ session); if (req.getRequestURI().equals(contextPath+"/login")) { chain.doFilter(request, response); } else { if (session == null) { res.sendRedirect(contextPath + "/login"); } else { chain.doFilter(request, response); } } } }
|
По идее он не создает сессии.
Вот код LoginServlet
| Код | public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String contextPath=request.getContextPath(); String username = request.getParameter("username"); int minimumNicknameLength = Integer.parseInt(getServletContext().getInitParameter("MinimumNicknameLength")); if( username != null && username.length() >= minimumNicknameLength && username.indexOf(" ")==-1) { try { ChatRoomList roomList = (ChatRoomList)getServletContext().getAttribute("roomList"); boolean ifExists = roomList.chatterExists(username); if(ifExists) { request.setAttribute("error", 1); request.setAttribute("userexists", 1); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jspx/login.jspx"); dispatcher.forward(request, response); } else { System.out.println("session ok"); HttpSession session = request.getSession(true); System.out.println("session ok"); int timeout = Integer.parseInt(getServletContext().getInitParameter("SessionTimeout")); timeout=timeout*60; session.setMaxInactiveInterval(timeout); session.setAttribute("username", username); Chatter chatter = new Chatter(username, "m", new java.util.Date().getTime()); ChatRoom chatRoom = roomList.getRoom("StartUp"); chatRoom.addChatter(chatter);
response.sendRedirect(contextPath+"/rooms"); } } catch(Exception e) {}; } else { request.setAttribute("error", 1); request.setAttribute("badname", 1); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jspx/login.jspx"); dispatcher.forward(request, response); //response.sendRedirect(contextPath+"/login.jspx"); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jspx/login.jspx"); //dispatcher.forward(request, response); } }
|
В моем случае здесь тоже не создается сессии ( на терминал ничего не выводится!!!)
Мои подозрения падают на jspx страницу, где я обращаюсь к атрибуту сессии ${username == null}. Точнее сказать не к атрибуту именно сессии, а атрибут ищется сначала в реквесте, потом в сессии, потом в контексте.
МОЖЕТ ЛИ ТАКОЕ ОБРАЩЕНИЕ НЕЯВНО СОЗДАВАТЬ СЕССИЮ ?
Вот код jspx страницы ?
| Код | <?xml version="1.0" encoding="UTF-8"?> <jsp:root xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:fmt="http://java.sun.com/jsp/jstl/fmt" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:x="http://java.sun.com/jsp/jstl/xml" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" /> <jsp:directive.page errorPage="/WEB-INF/jspx/error.jspx"/> <fmt:setBundle basename="VChatBundle"></fmt:setBundle> <html> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="expires" content="Wed, 26 Feb 1997 08:21:57 GMT" /> <head> <title> <fmt:message key="vchat.title"></fmt:message> </title> </head> <body> <center> <c:choose> <c:when test="${username == null}" > <c:choose> <c:when test="${error != null}"> <c:if test="${badname != null}"> <fmt:message key="vchat.error.bad.name"/> <BR/> </c:if> <c:if test="${userexists != null}"> <fmt:message key="vchat.error.user.exists"/> </c:if> </c:when> <c:otherwise> <fmt:message key="vchat.greeting.welcome"/>, <fmt:message key="vchat.greeting.guest"/> !!! <BR/> </c:otherwise> </c:choose> <fmt:message key="vchat.greeting.entername"/> ! <form method="POST" action="${request.contextPath}/login"> Name: <input type="TEXT" name="username" size="25"/> <BR/>
<fmt:message key="vchat.botton.submit" var="submitText"/> <input type="SUBMIT" value="${submitText}"/>
<fmt:message key="vchat.botton.reset" var="resetText"/> <input type="RESET" value="${resetText}"/> </form> </c:when> <c:otherwise> <fmt:message key="vchat.greeting.welcome"/>, ${username} !!! <BR/> <form method="POST" action="${request.contextPath}/logout"> <fmt:message key="vchat.botton.logout" var="logout"/> <INPUT type="SUBMIT" value="${logout}"/> </form> </c:otherwise> </c:choose> </center> </body> </html> </jsp:root>
|
|