04---servlet06(取得其他内置对象)

1、取得HttpSession实例
	·在servlet程序中要想得到一个session对象, 通过HttpSerlvetRequest接口完成,在此接口中提供了一下操作:
		public HttpSession getSession();
		public HttpSession getSession(boolean create);
	 servlet本身提供的只有request和response两个对象, 所以想去的session对象,只能依靠request对象;
		因为session属于HTTP协议的范畴,而且每次发送请求的时候服务器都会想客户端设置一个Cookie,
		所以,很自然的,session中又使用到了Cookie机制,但是Cookie又只能通过request取得,那么session
		就只能通过request取得了;

			package com.lid.servlet;
			import java.io.*;
			import javax.servlet.*;
			import javax.servlet.http.*;

			public class HttpSessionDemoServlet extends HttpServlet{
				public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
					HttpSession session=req.getSession();
					System.out.println("SESSION ID--->"+session.getId());
					session.setAttribute("username","lid-yuj");
					System.out.println("username属性内容:"+session.getAttribute("username"));
					}
				public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
					this.doGet(req,res);
					}
				}
		编译该servlet;然后在web.xml中配置servlet的映射:
			<servlet>
		 		<servlet-name>sessiondemo</servlet-name>
		 		<servlet-class>com.lid.servlet.HttpSessionDemoServlet</servlet-class>
		 	</servlet>
			<servlet-mapping>
		 		<servlet-name>sessiondemo</servlet-name>
		 		<url-pattern>/HttpSessionDemoServlet</url-pattern>
		 	</servlet-mapping>
		启动web服务器;
		此时可以取得session的对象;

2、取得application内置对象;
	在之前学application的时候我们知道application可以通过this.getServletContext()得到;
	HttpServlet的父类中提供了返回ServletContext对象的getServletContext()方法,
	而application内置对象就是ServletContext接口的实例化对象,所以利用此方法来完成取得;
		package com.lid.servlet;
		import java.io.*;
		import javax.servlet.*;
		import javax.servlet.http.*;

		public class ServletContextDemoServlet extends HttpServlet{
			public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
				ServletContext app=super.getServletContext();
				System.out.println("真是路径:"+app.getRealPath("/"));
				}
			public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
				this.doGet(req,res);
				}
			}
	编程上面的程序;在web.xml中配置servlet映射:
		<servlet>
	 		<servlet-name>servletcontextdemo</servlet-name>
	 		<servlet-class>com.lid.servlet.HttpSessionDemoServlet</servlet-class>
	 	</servlet>
		<servlet-mapping>
	 		<servlet-name>servletcontextdemo</servlet-name>
	 		<url-pattern>/ServletContextDemoServlet</url-pattern>
	 	</servlet-mapping>
	启动tomcat;


 

你可能感兴趣的:(04---servlet06(取得其他内置对象))