servlet本身提供的只有request和response对象,如果要取得session对象,只能依靠request对象,因为session属于HTTP协议范畴,而且在每次发送请求的时候,服务器都会自动为客户端设置一个cookie,所以,很自然的,session中要使用cookie机制,但是cookie又只能通过request取得,所以自然session也只能通过request取得。
取得session对象:
package org.lxh.servletdemo ;
import java.io.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
public class HttpSessionDemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
HttpSession ses = req.getSession() ;
System.out.println("SESSION ID --> " + ses.getId()) ;
ses.setAttribute("username","李兴华") ; // 设置session属性
System.out.println("username属性内容:" + ses.getAttribute("username")) ;
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
this.doGet(req,resp) ;
}
}
web.xml:
<servlet>
<servlet-name>sessiondemo</servlet-name>
<servlet-class>
org.lxh.servletdemo.HttpSessionDemoServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sessiondemo</servlet-name>
<url-pattern>/HttpSessionDemoServlet</url-pattern>
</servlet-mapping>
2. 取得application:
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:
<servlet>
<servlet-name>applicationdemo</servlet-name>
<servlet-class>
org.lxh.servletdemo.ServletContextDemoServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>applicationdemo</servlet-name>
<url-pattern>/ServletContextDemoServlet</url-pattern>
</servlet-mapping>
总结:
1. 通过req.getSession() 可以取得session,可以进行登录验证操作
2. 通过getServletContext()取得application