在Servlet程序中要想取得一个session对象,则可以通过HttpServletRequest接口完成。
HttpSessionDemoServlet
package im.weitang;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class HttpSessionDemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
System.out.println("SESSION ID = " + session.getId());
session.setAttribute("username", "张三");
System.out.println("username = " + session.getAttribute("username"));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
修改web.xml,添加如下代码
<servlet>
<description></description>
<display-name>HttpSessionDemoServlet</display-name>
<servlet-name>HttpSessionDemoServlet</servlet-name>
<servlet-class>im.weitang.HttpSessionDemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HttpSessionDemoServlet</servlet-name>
<url-pattern>/HttpSessionDemoServlet</url-pattern>
</servlet-mapping>
程序运行后,Tomcat后台输出了:
SESSION ID = 5B9A2ED83C1C7507736B2836498F59BB
username = 张三