ServletContext是一个域对象.
* 作用范围:整个web工程.
* 创建:服务器启动的时候,tomcat服务器为每个web项目创建一个单独ServletContext对象.
* 销毁:服务器关闭的时候,或者项目从服务器中移除的时候.
样例:在Servlet中定义一个全局参数,统计成功登录人数。
在/WEB-INF/web.xml中配置<load-on-startup>参数
<servlet>
<description></description>
<display-name>UserLoginServlet</display-name>
<servlet-name>UserLoginServlet</servlet-name>
<servlet-class>com.servlet.UserLoginServlet</servlet-class>
<!-- 标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法)。值越小优先级越高(大于0的前提下) -->
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>UserLoginServlet</servlet-name>
<url-pattern>/UserLoginServlet</url-pattern>
</servlet-mapping>
UserLoginServlet.java
package com.servlet;
import java.io.IOException;
import javax.jws.soap.SOAPBinding.Use;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.domain.User;
import com.service.UserLoginService;
/**
* @author 侯青华
* @version 创建时间:2018年3月7日 下午7:03:24
* 用户登录servlet
*/
public class UserLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//重写init(),初始化ServletContext
@Override
public void init() throws ServletException {
//初始化一个变量count值为0
int count = 0 ;
//将这个值存入ServletContext中
this.getServletContext().setAttribute("count", count);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决向页面输出中文乱码问题(响应中文乱码问题)
response.setContentType("text/html;charset=utf-8");
//获取表单提交的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//封装对象到实体中
User user= new User();
user.setUsername(username);
user.setPassword(password);
//调用service层判断登录,返回User对象
UserLoginService userLoginService = new UserLoginService();
User existUser = userLoginService.login(user);
if(existUser == null) {
//登录失败
response.getWriter().println("用户或密码错误!3秒后跳回登录界面!");
//3秒后跳回登录页面
response.setHeader("Refresh", "3;url=/day/demo_login/login.htm");
}else {
//统计成功登陆人数
int count = (int) this.getServletContext().getAttribute("count");
count++;
this.getServletContext().setAttribute("count", count);
//显示成功登陆人数
count = (int) this.getServletContext().getAttribute("count");
response.getWriter().println("<h1>您是第"+count+"位登录成功的用户!3秒后进入主界面~</h1>");
//3秒后跳回登录页面
response.setHeader("Refresh", "3;url=/day/demo_login/index.html");
// //登陆成功
// response.setStatus(302); //重定向到登陆成功界面
// response.setHeader("Location", "/day/demo_login/loginSuccess.html");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}