ServletContext的常见使用方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zoweiccc/article/details/83660455

ServletContext的使用:

每个web工程都只有一个ServletContext对象,所以在哪里获得的ServletContext对象都是同一个.

作用:
1.可以获取全局配置参数
2.可以获取web应用中的资源
    1)获取资源在tomcat里面的绝对路径,使用getRealPath()方法,先获取路径再获取流对象.
    2)使用getResourceAsStream(),根据相对路径直接获取流对象
    3)通过classloader(类加载器JDBC)去获取web工程下的资源
3.存取数据,在多个servlet间共享数据
    样例:定义一个登陆的页面;定义一个servlet;针对成功或者失败跳转到不同页面;

ServletContext在服务器启动时,会为托管的每一个web应用程序,创建一个ServletContext对象;从服务器移除托管或者关闭服务器时销毁.
作用范围:在同一个项目里面都可以取.

获取全局配置参数与获取web应用中的资源的实现案例

package cw.Servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet06 extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//1.获取全局配置参数
		ServletContext context=getServletContext();	//创建对象
		String rrrr=context.getInitParameter("rrrr");
		System.out.println("rrrr"+"..."+rrrr);
		
		//2.获取web应用中的资源
		/*
		 * 这里如果想获取web工程下的资源,用普通的FileInputStream写法是不对的
		 * 因为路径不正确,这里的相对路径是根据jre来确定的,但是这里是一个web工程
		 * jre后面由tomcat管理,所以这里真正的相对路径是tomcat里的bin目录
		 */
		/*
		Properties pro=new Properties();	//创建属性对象
		InputStream is=new FileInputStream("src/config.properties");
		pro.load(is);
		String name=pro.getProperty("address");
		System.out.println(name);
		*/
		//应该使用ServletContext
		//1)第一种方式,使用getRealPath()方法,先获取路径再获取流对象
		ServletContext sc2=getServletContext();	//获取ServletContext对象
		String path=sc2.getRealPath("file/config.properties");		//获取给定的文件在服务器上面的绝对路径
		
		Properties pro=new Properties();		//创建属性对象
		InputStream is=new FileInputStream("path");
		pro.load(is);
		
		String name=pro.getProperty("address");	//获取address属性的值
		System.out.println(name);
		is.close();
		
		//2)第二种方式,使用getResourceAsStream(),根据相对路径直接获取流对象
		ServletContext sc3=getServletContext();	
		Properties pro2=new Properties();
		//获取web工程下的资源转换成流对象,前面隐藏当前工程的根目录
		InputStream is2=sc3.getResourceAsStream("file/config.properties");
		pro2.load(is2);
		String name2=pro2.getProperty("address");
		System.out.println(name2);
		is2.close();
		
		//3).通过classloader(类加载器JDBC)去获取web工程下的资源
		Properties pro3=new Properties();
			//获取该java文件的class,然后获取到加载这个class到虚拟机中的那个类加载器对象
		
		//默认的classloader的路径是下面这个路径,我们必须得回到JavaWeb_1这个目录下,才能进入file目录
		//E:\tomcat\apache-tomcat-7.0.57\wtpwebapps\JavaWeb_1\WEB-INF\classes
		InputStream is3=this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
		pro3.load(is3);
		String name3=pro3.getProperty("address");
		System.out.println(name3);
		is3.close();
		
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		System.out.println("bb");
	}
}

实现存取数据,在多个servlet间共享数据的样例

此功能实现了实现登陆功能,并且记录登陆的次数返回到网页.

login.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>请输入登陆信息</h2>
	<form action="LoginServlet" method="get">
		账号:<input type="text" name="username" />
		密码:<input type="text" name="password" />
		<input type="submit" name="登陆" />
	</form>	
</body>
</html>

LoginServlet.java

package cw.Servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
/*
	request:包含请求信息

	response:响应数据给浏览器
	
*/
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1.获取数据
		String name=request.getParameter("username");
		String password=request.getParameter("password");
		System.out.println("username="+name+"..."+"password="+password);
		//2.校验数据
		//向客户端输出内容
		PrintWriter pw=response.getWriter();
		if("admin".equals(name)&&"123".equals(password)){
			System.out.println("登陆成功");
			pw.write("login success...");
			
			//成功的次数累加
			Object obj=getServletContext().getAttribute("count");//获取以前存取的count值
			
			Integer count=0;
			if(obj!=null){
				count=(Integer)obj;
			}
			System.out.println("已登陆成功的次数是:"+count);
			getServletContext().setAttribute("count", count+1);
			
			response.setStatus(302);	//设置状态码,重新定位目标位置
			//定位跳转的位置是哪一个页面
			response.setHeader("Location", "login_success.html");	//成功就跳转到login_success.html
		}
		else{
			System.out.println("登陆失败");
			pw.write("login failed...");
		}
			
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

login_success.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>登陆成功!</h2>
	<a href="CountServlet">获取网站登陆成功总数</a>
</body>
</html>

CountServlet.java

package cw.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CountServlet
 */
public class CountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.取出相应的值
		Integer count=(Integer)getServletContext().getAttribute("count");
		//2.输出到界面
		response.getWriter().write("login success times:"+count);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

猜你喜欢

转载自blog.csdn.net/zoweiccc/article/details/83660455