取得Session
使用Servlet还可以取得session对象,通过HttpServletRequest接口即可完成。
使用的方法是:getSession()。
取得Session对象:
package com.zzh.Servlet;
import java.io.IOException;
import java.rmi.ServerException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServerException, IOException {
HttpSession session = req.getSession();
System.out.println("Session ID:" + session.getId());
session.setAttribute("name", "lunatictwo");
System.out.println("name属性内容:" + session.getAttribute("name"));
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServerException, IOException {
doGet(req, resp);
}
}配置web.xml文件:
session
com.zzh.Servlet.SessionServlet
session
/SessionServlet
tomcat后台显示:
取得ServletContext
package org.lxh.servletdemo ;
import java.io.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
public class ServletContextDemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
ServletContext app = super.getServletContext() ;
System.out.println("真实路径:" + app.getRealPath("/")) ;
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
this.doGet(req,resp) ;
}
}配置web.xml
applicationdemo
com.zzh.Servlet.ServletContextDemoServlet
applicationdemo
/ServletContextDemoServlet