美文网首页
取得HttpSession实例

取得HttpSession实例

作者: kylelin | 来源:发表于2014-08-06 21:25 被阅读483次

    在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 = 张三
    

    相关文章

      网友评论

          本文标题:取得HttpSession实例

          本文链接:https://www.haomeiwen.com/subject/mgketttx.html