每个web工程都只有一个ServletContext对象。 说白了也就是不管在哪个servlet里面,获取到的这个类的对象都是同一个。
如何得到对象
//1. 获取对象
ServletContext context = getServletContext();
有什么作用
1. 获取全局配置参数
<context-param>
<param-name>address
</param-name>
<param-value>深圳宝鸡
</param-value>
</context-param>
ServletContext sc = getServletContext();
String s = sc.getInitParameter("address");
System.out.println("ServletContext01 的 address:"+s);
2. 获取web工程中的资源
-
获取资源在tomcat里面的绝对路径
先得到路径,然后自己new InpuStream context.getRealPath("") //这里得到的是项目在tomcat里面的根目录。 D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\ String path = context.getRealPath("file/config.properties"); D:\tomcat\apache-tomcat-7.0.52\apache-tomcat-7.0.52\wtpwebapps\Demo03\file\config.properties
第一步:新建文件夹
name = zhangsan
第二步:编写servlet类
ServletContext sc = getServletContext();
String path = sc.getRealPath("File/config.properties");
System.out.println(path);
Properties properties = new Properties();
InputStream is = new FileInputStream(path);
properties.load(is);
String name = properties.getProperty("name");
System.out.println("name= "+ name);
第三步:编写web.xml
第四步:输出
- getResourceAsStream 获取资源流对象
直接给相对的路径,然后获取流对象。
try {
ServletContext sc = getServletContext();
Properties properties = new Properties();
//获取web工程下的资源,转化成流对象。前面 隐藏当前工程的根目录。
InputStream is = sc.getResourceAsStream("File/config.properties");
properties.load(is);
String name = properties.getProperty("name");
System.out.println("name22= "+ name);
is.close();
}catch(Exception e){
e.printStackTrace();
}
- 通过classloader去获取web工程下的资源
Properties properties = new Properties();
//类的加载器的路径和文件的相对路径不一样
InputStream is = this.getClass().getClassLoader().getResourceAsStream("../../File/config.properties")
properties.load(is);
String name = properties.getProperty("name");
System.out.println("name3= "+ name);
is.close();
}catch(Exception e){
e.printStackTrace();
3. 存取数据,servlet间共享数据(域对象)
ServletContext获取登录成功总数
步骤分析
- 定义一个登陆的html页面, 定义一个form表单
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>请输入一下内容,完成登录</h2>
<form action="LoginServlet" method="get">
账号:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="登录"/><br>
</form>
</body>
</html>
- 定义一个Servlet,名为LoginServlet,并接收客户端请求
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:"+username+","+"password:"+password);
- 针对成功或者失败,进行判断,然后跳转到不一样的网页
if("admin".equals(username)&&"123".equals(password)) {
//成功就跳转login_success.html
//设置状态码?重新定位 状态码
response.setStatus(302);
//定位跳转到哪一个界面
response.setHeader("Location", "login_success.html");
}
else {
String s = "login failed!";
pw.write(s);
}
- ServletContext存取值分析
示例
工程文件
CountServlet类
package com.demo01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.取值
int count = (int) getServletContext().getAttribute("count");
//2.输出到客户端
response.getWriter().write("当前登录总次数:"+count+"次");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
LoginServlet类
package com.demo01;
import java.io.IOException;
import java.io.PrintWriter;
import javax.script.ScriptContext;
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 LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* request :包含请求的信息
response :响应数据给浏览器,就靠这个对象
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取数据
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:"+username+","+"password:"+password);
//2.数据校验
//向客户端输送请求
PrintWriter pw = response.getWriter();
if("admin".equals(username)&&"123".equals(password)) {
//1.成功登录次数类加
//获取以前的值,再此基础上+1
Object obj = getServletContext().getAttribute("count");
//默认是0
int totalCount = 0;
if(obj != null) {
totalCount = (int)obj;
}
System.out.println("已知登录成功的次数:"+totalCount);
//给这个count赋值
getServletContext().setAttribute("count", totalCount+1);
//2.成功就跳转login_success.html
//设置状态码?重新定位 状态码
response.setStatus(302);
//定位跳转到哪一个界面
response.setHeader("Location", "login_success.html");
}
else {
String s = "login failed!";
pw.write(s);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.demo01.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>CountServlet</servlet-name>
<servlet-class>com.demo01.CountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CountServlet</servlet-name>
<url-pattern>/CountServlet</url-pattern>
</servlet-mapping>
</web-app>
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>请输入一下内容,完成登录</h2>
<form action="LoginServlet" method="get">
账号:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="登录"/><br>
</form>
</body>
</html>
login_success.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录成功了</h2>
<a href="CountServlet">获取网站登录成功的次数</a>
</body>
</html>
ServletContext 何时创建, 何时销毁?
服务器启动的时候,会为托管的每一个web应用程序,创建一个ServletContext对象
从服务器移除托管,或者是关闭服务器。
- ServletContext 的作用范围
只要在这个项目里面,都可以取。 只要同一个项目。 A项目存, 在B项目取,是取不到的? ServletContext对象不同。