一、ServletContext对象

每一个Web工程对应于一个ServletContext对象,此对象代表web应用,由服务器创建,可以解决不同用户的数据共享问题。

1、生命周期:

创建:web应用被加载到服务器或服务器开启。

销毁:web应用被移除或服务器关闭。

2、对象的获取:

(1)实现Servlet接口的类内部:

   public void init(ServletConfig servletConfig) throws ServletException {
ServletContext servletContext= servletConfig.getServletContext();
}

(2)getServletContext():

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext=getServletContext();
}

(3)通过Session获取:

 ServletContext servletContext=request.getSession().getServletContext();

3、ServletContext对象的应用:

(1)获得初始化参数(web.xml的全局数据):

    <servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
<context-param>//一组标签只能存储一组键值对
<param-name>zhai</param-name>
<param-value>zhai1997</param-value>
</context-param>
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext=getServletContext();
String paramvalue=servletContext.getInitParameter("zhai");//由键获取值
System.out.println(paramvalue);
}

如果数据不存在,返回NULL。

(2)获得工程发布后的绝对路径:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext=getServletContext();
String realpath=servletContext.getRealPath("/web.text");
System.out.println(realpath);
String realpath1=servletContext.getRealPath("/WEB-INF/wen-inf.text");
System.out.println(realpath1);
String realpath2=servletContext.getRealPath("../工程.text");
System.out.println(realpath2);
}

getRealPath的参数为相对于web的路径,因为发布到服务器的时候只发布web文件中的内容,因此:工程.text文件不能被访问到。

(3)域对象(作用范围为整个web应用)

Servlet1:创建ServletContext对象设置键和值(数据存储):

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext=getServletContext();
servletContext.setAttribute("name","zhai");
}

Servlet2:由键获取值:

   String attribute=(String)this.getServletContext().getAttribute("name");
System.out.println(attribute);
}

需要先访问Servlet1设置键和值,再去访问Servlet2获取值。如果不存在返回NULL。

二、ServletContext对象应用——三天免登录(记录访问次数)

1、用到的知识点:

(1)Cookie

(2)Session

(3)ServletContext

其中Cookie和Session是会话技术的组成部分,一次会话从打开浏览器的某个站点开始,到浏览器关闭为止。如打开浏览器中的淘宝时一次会话开始,关闭浏览器的时候此次会话结束。

要想实现三天免登录记录网站访问次数的功能,只有Cookie和Session技术是不行的,因为Cookie实现的的是免登录功能。通过创建Cookie,生成了Cookie文件,在下次登录时可以直接读取Cookie中的用户信息,不用重新输入账户和密码。Session的运用解决的是不同请求的数据共享问题,即创建了Session后,在访问不同的页面的时候,可以通过Request对象获取Session的值。

要想记录页面访问的次数,要用到ServletContext技术,可以解决不同用户的数据共享问题。即ServletContext中的值是所有用户共享的。可以获取或修改值。

2、过程分析:

第一次登录(没有Sessio和Cookie):

需要进行手动登录。

首次登录后(Cookie未过期之前)登录:

MainServlet的运行结果:

因为Session的运用在CookieServlet中存储的Session中的数据,在MainSewrvlet中依旧能够调用。

由于SertvletContext的运用,浏览量会递增,不会因为浏览器、服务器的关闭而造成数据从0开始增加。

3、代码分析:

CookieServlet:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");//设置浏览器编码格式
Cookie[] cookies=request.getCookies();
Connection con=null;
login log= null;
int successNum=;
try {
con= C3p0Utils.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "Select * from login";
List<login> list = qr.query(con, sql, new BeanListHandler<login>((login.class)));
if(cookies!=null) {//验证数据库中是否有与Cookie对应的用户
for (int i = ; i < list.size(); i++) {
log= list.get(i);
for (Cookie cookie : cookies) {
if((log.getAccount().equals(cookie.getName()))&&(log.getPassword().equals(cookie.getValue()))){
HttpSession httpSession=request.getSession();
httpSession.setAttribute("login",log);
ServletContext servletContext = this.getServletContext();//获取ServletContext对象
if((servletContext.getAttribute("contextNum"))!=null) {
int num=Integer.parseInt(servletContext.getAttribute("contextNum").toString());
num++;
servletContext.setAttribute("contextNum",num);//将int类型的num储存到contextNum
}else{
servletContext.setAttribute("num",);
} successNum++;
}
}
}
if(successNum>=){ response.sendRedirect("/Servlet_login_war_exploded/main");
}
else{
request.getRequestDispatcher("page").forward(request,response);
} }
else{
request.getRequestDispatcher("page").forward(request,response);
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}

有Cookie则用数据库校验,成功直接进入主页面,并生成Session和ServletContext,不成功则请求转发到登录页面重新进行登录。

MainServlet:

  login log= (login) request.getSession().getAttribute("login");
int num=(int)this.getServletContext().getAttribute("contextNum");

通过Session和ServletContext获取CookieServlet中的数据。

LogServlet:

try {
con=C3p0Utils.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "Select * from login where account=? and password=?";
Object[] select = {account,password};
log = qr.query(con, sql, new BeanHandler<login>((login.class)), select);
if(log!=null){
response.getWriter().write("nihao"+account);
Cookie cookie=new Cookie(account,password);
cookie.setPath("/Servlet_login_war_exploded/cookie");
cookie.setMaxAge(**);
response.addCookie(cookie);
}
else{
response.getWriter().write("wrong");
}

是在无Cookie或数据库校验失败的情况下调用的,数据库中有用户信息则生成Cookie。

4、问题分析(类型转换错误):

错误代码:

int num=(int) this.getServletContext().getAttribute("contextNum");

原因:this.getServletContext().getAttribute("contextNum")为Object类型,需要先转换为String类型,再转换为int类型:

int num=Integer.parseInt(servletContext.getAttribute("contextNum").toString());

ServletContext对象应用——三天免登录的更多相关文章

  1. Session的应用——三天免登录

    1.使用Cookie实现的登录的不足: protected void doGet(HttpServletRequest request, HttpServletResponse response) t ...

  2. Cookie的应用——Servlet实现三天免登录

    1.工程结构: 2.Servlet的运用: (1)登录界面: protected void doGet(HttpServletRequest request, HttpServletResponse ...

  3. cookie之三天免登录代码

    LoginCookie.java 1 package com.bjsxt.cookie; import java.io.IOException; import java.net.URLDecoder; ...

  4. ServletConfig对象和ServletContext对象

    (1)ServletConfig:用来保存一个Servlet的配置信息的(比如 : name, class, url ... ) 这些配置信息没什么大用处,我们还可以在ServletConfig中保存 ...

  5. 一、HttpServletRequest接口 二、HttpServletReponse接口 三、POST和GET请求方式及其乱码处理 四、ServletContext对象和ServletConfig对象

    一.HttpServletRequest接口 内部封装了客户端请求的数据信息 接收客户端的请求参数.HTTP请求数据包中配置参数 ###<1>常用方法 getContextPath()重要 ...

  6. Java第三阶段学习(十一、Servlet基础、servlet中的方法、servlet的配置、ServletContext对象)

    一.Servlet简介  1.什么是servlet: sun公司提供的一套规范(接口),用来处理客户端请求.响应给浏览器的动态资源.但servlet的实质就是java代码,通过java的API动态的向 ...

  7. 三:ServletContext对象

    一.ServletContext对象 1.什么是ServletContext对象 ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象 内部封装是该w ...

  8. Java Servlet(三):Servlet中ServletConfig对象和ServletContext对象

    本文将记录ServletConfig/ServletContext中提供了哪些方法,及方法的用法. ServletConfig是一个抽象接口,它是由Servlet容器使用,在一个servlet对象初始 ...

  9. 小谈-—ServletConfig对象和servletContext对象

    一.servletContext概述 servletContext对象是Servlet三大域对象之一,每个Web应用程序都拥有一个ServletContext对象,该对象是Web应用程序的全局对象或者 ...

随机推荐

  1. go 疑难杂症

    func Test_doSeond(t *testing.T) { msg := make([]Msg, 0) for i := 0; i < 5; i++ { m := Msg{ data: ...

  2. Pycharm专业版配置远程服务器并自动同步代码

    一.使用场景 如果每次都在本机上面写代码,然后传到服务器上面,在服务器上面运行就太麻烦了.这样的方式十分繁琐,效率很低. 因此,希望可以像下面一样操作: 可以直接在本机上码代码 自动将代码同步到远程服 ...

  3. Maven过滤属性文件,替换属性值

    pom.xml 1.resources: resources中是定义哪些目录下的文件会被配置文件中定义的变量替换,一般我们会把项目的配置文件放在src/main/resources下,像db,bean ...

  4. TCP协议(下)

    TCP滑动窗口 发送端 LastByteAcked:第一部分和第二部分的分界线 LastByteSent:第二部分和第三部分的分界线 LastByteAcked + AdvertisedWindow: ...

  5. java之hibernate之双向的多对一关联映射

    这篇讲解 双向的多对一关联映射 1.表结构和多对一时,一致 2.类结构 Book.java public class Book implements Serializable{ private int ...

  6. C# HtmlAgilityPack+Selenium爬取需要拉动滚动条的页面内容

    现在大多数网站都是随着滚动条的滑动加载页面内容的,因此单纯获得静态页面的Html是无法获得全部的页面内容的.使用Selenium就可以模拟浏览器拉动滑动条来加载所有页面内容. 前情提要 C#HtmlA ...

  7. C#判断字符串中包含某个字符的个数

    //定义字符串 var Email= "humakesdkj@idsk@"; //获取@字符出现的次数 int num = Regex.Matches(Email, "@ ...

  8. YII 的SPA 写法

    'use strict'; var findToolbar = function () { return document.querySelector('#yii-debug-toolbar'); } ...

  9. kubernetes第七章--管理存储资源

  10. ceph 接入OpenStack

    创建对应的pool: ceph osd pool create volumes 512 ceph osd pool create images 512 ceph osd pool create vms ...