Servlet的作用域是干嘛的?答案就是共享数据而存在的,如图:

  下面通过代码演示来具体讲解一下三大作用域

我们新建两个类

  1. package main.com.vae.scope;
  2.  
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9.  
  10. @WebServlet("/scope")
  11. public class ScopeServlet extends HttpServlet {
  12.  
  13. @Override
  14. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  15. //Servlet的三大作用域讲解
  16. //1.request
  17. Integer numInRequest=(Integer)req.getAttribute("NUM_IN_REQUEST") ;
  18. if (numInRequest == null) {
  19. req.setAttribute("NUM_IN_REQUEST",1);
  20. }
  21. else {
  22. req.setAttribute("NUM_IN_REQUEST",numInRequest+1);
  23. }
  24. //2.Session
  25. Integer numInSession=(Integer)req.getSession().getAttribute("NUM_IN_SESSION") ;
  26. if (numInSession == null) {
  27. req.getSession().setAttribute("NUM_IN_SESSION",1);
  28. }
  29. else {
  30. req.getSession().setAttribute("NUM_IN_SESSION",numInSession+1);
  31. }
  32. //3.application
  33.  
  34. Integer numInApplication=(Integer) req.getServletContext().getAttribute("NUM_IN_APPLICATION");
  35. if (numInApplication == null) {
  36. req.getServletContext().setAttribute("NUM_IN_APPLICATION",1);
  37. }
  38. else {
  39. req.getServletContext().setAttribute("NUM_IN_APPLICATION",numInApplication+1);
  40. }
  41.  
  42. req.getRequestDispatcher("/result").forward(req,resp);
  43.  
  44. }
  45. }
  1. package main.com.vae.scope;
  2.  
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. import java.io.PrintWriter;
  10.  
  11. @WebServlet("/result")
  12. public class ResultServlet extends HttpServlet {
  13.  
  14. @Override
  15. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  16. resp.setContentType("text/html;charset=utf-8");
  17. PrintWriter out=resp.getWriter();
  18.  
  19. Integer numInRequest=(Integer) req.getAttribute("NUM_IN_REQUEST");
  20. Integer numInSession=(Integer) req.getSession().getAttribute("NUM_IN_SESSION");
  21. Integer numInApplication=(Integer) req.getServletContext().getAttribute("NUM_IN_APPLICATION");
  22.  
  23. out.println("Request="+numInRequest);
  24. out.println("Session="+numInSession);
  25. out.println("Application="+numInApplication);
  26. }
  27. }

运行,输入/scope。这个例子很好的讲解了三大作用域的本质

第一次访问,三大作用域都是1,按F5刷新几下

可以看到,Session和Application作用域在一直增加,我换一个火狐浏览器再访问这个Servlet试试

换个火狐浏览器访问了几次,Session从0开始计算了,而Application还是接着加的,我再返回Google浏览器试试

Google里面的session自己又加1了,Application是右边增加的基础上又加的。这就表达了一个本质

Request是一次请求

Session是一个会话

Application是多次会话(Tomcat开启到关闭)

ServletContext对象的获取以及常用的方法

代码如下:

  1. package main.com.vae.scope;
  2.  
  3. import javax.servlet.ServletContext;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.annotation.WebServlet;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.io.IOException;
  10. import java.util.Enumeration;
  11.  
  12. @WebServlet("/scd")
  13. public class ServletContextDemo extends HttpServlet {
  14.  
  15. @Override
  16. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  17. //获取ServletContext(就是Application)对象的3种方式
  18. //1.
  19. ServletContext app1=super.getServletContext();
  20. //2.
  21. ServletContext app2=req.getServletContext();
  22. //3.
  23. ServletContext app3=req.getSession().getServletContext();
  24.  
  25. //以上三种方式获取的ServletContext对象是相等的,是同一个
  26.  
  27. //ServletContext常用的方法
  28. //1.根据相对路径获取绝对路径。在做资源下载的时候有用
  29. String Path=super.getServletContext().getRealPath("/WEB-INF/web.html");
  30. System.out.println(Path);
  31. //2.返回响应的上下文路径,Tomcat7以上你不填path就是空的,Tomcat6你不填是一个 /
  32. System.out.println(req.getContextPath());
  33. System.out.println(super.getServletContext().getContextPath());
  34.  
  35. //3.获取全局参数
  36. System.out.println(super.getServletContext().getInitParameter("name"));
  37. Enumeration<String> enums=super.getServletContext().getInitParameterNames();
  38. while (enums.hasMoreElements()) {
  39. System.out.println("--->" + enums.nextElement());
  40. }
  41.  
  42. }
  43. }

浏览器访问之后,输出栏结果如下:

这里需要说一下,第一个方法没啥讲的,获取绝对路径。

第二个方法是这样的,获取当前项目的上下文路径,就是我们Tomcat的Server.xml里面配置的,如图:

这个path我们填的空,那就没显示。

第三个方法,配置全局参数,因为Servlet自己在Tomcat的web.xml里面配置的参数只能自己用,其他Servlet如果也使用了通用的参数还得自己写。

所以写一个全局参数比较好,全局参数在项目的WEB-INF文件夹下的web.xml里面写,这样写

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <web-app version="2.4"
  4. xmlns="http://java.sun.com/xml/ns/j2ee"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  7.  
  8. <!--全局的初始化参数-->
  9. <context-param>
  10. <param-name>name</param-name>
  11. <param-value>许嵩</param-value>
  12. </context-param>
  13. <context-param>
  14. <param-name>password</param-name>
  15. <param-value>514</param-value>
  16. </context-param>
  17.  
  18. </web-app>

完事。

Java Web之Servlet的三大作用域对象的更多相关文章

  1. JSP九大内置对象和四大作用域和Servlet的三大作用域对象

    一.JSP九大内置对象:内置对象(又叫隐含对象,有9个内置对象):不需要预先声明就可以在脚本代码和表达式中随意使用 内置对象特点: 由JSP规范提供,不用编写者实例化. 通过Web容器实现和管理 所有 ...

  2. servlet的三大作用域对象和jsp的九大内置对象及其四大作用域对象

    servlet的三大作用域对象: request(HttpServletRequest) session(HttpSession): application(ServletContext):tomca ...

  3. Servlet的三大作用域

    Servlet的三大作用域 一.request  请求对象 共享的数据:请求共享 特点:同一次请求中,共享数据可以获取(请求一旦结束,请求共享清除站)(请求转发能共享参数,重定向不行) 代码:req. ...

  4. jsp九个内置对象、四个域对象及Servlet的三大域对象

    一,什么是内置对象? 在jsp开发中会频繁使用到一些对象,如ServletContext HttpSession PageContext等.如果每次我们在jsp页面中需要使用这些对象都要自己亲自动手创 ...

  5. Java Web之Servlet中response、request乱码问题解决

    Java Web之Servlet中response.request乱码问题解决   一.request请求参数出现的乱码问题 get请求: get请求的参数是在url后面提交过来的,也就是在请求行中, ...

  6. java web中servlet、jsp、html 互相访问的路径问题

    java web中servlet.jsp.html 互相访问的路径问题 在java web种经常出现 404找不到网页的错误,究其原因,一般是访问的路径不对. java web中的路径使用按我的分法可 ...

  7. 使用Intellij idea新建Java Web项目(servlet) 原理及初步使用

    准备 JDK       (配置JDK_HOME\bin   和 CLASSPATH)   注:JDK8下载已经需要注册了,请使用JDK11(现在是官方长期支持的版本)     对于我们新手来说,JD ...

  8. JAVA WEB 用servlet实现分页,思路比较清晰和简单。

    JAVA WEB 用servlet实现分页,思路比较清晰和简单.借鉴了其他大佬的思路.特别感谢. 是我第一次发表博客,如果有什么错误,欢迎大家指出!,谢谢 一.思路分析 前台一定是有类似这种的界面 点 ...

  9. Java Web(二) Servlet详解

    什么是Servlet? Servlet是运行在Web服务器中的Java程序.Servlet通常通过HTTP(超文本传输协议)接收和响应来自Web客户端的请求.Java Web应用程序中所有的请求-响应 ...

随机推荐

  1. 【XSY2731】Div 数论 杜教筛 莫比乌斯反演

    题目大意 定义复数\(a+bi\)为整数\(k\)的约数,当且仅当\(a\)和\(b\)为整数且存在整数\(c\)和\(d\)满足\((a+bi)(c+di)=k\). 定义复数\(a+bi\)的实部 ...

  2. Configure an PPTP Server on Debian

    安装PPTP apt-get update apt-get upgrade apt-get install iptables pptpd vim 设置并修改配置文件vim /etc/pptpd.con ...

  3. 洛谷P3953 逛公园(NOIP2017)(最短/长路,拓扑排序,动态规划)

    洛谷题目传送门 又是一年联赛季.NOIP2017至此收官了. 这个其实是比较套路的图论DP了,但是细节有点恶心. 先求出\(1\)到所有点的最短路\(d1\),和所有点到\(n\)的最短路\(dn\) ...

  4. LVS搭建负载均衡(一)NAT模型

    应用场景:LVS配置负载均衡方式之一:nat 测试环境: 测试步骤: 1. 在主机lvs上安装ipvsadm lvs~]# yum install ipvsadm -y lvs~]# ipvsadm ...

  5. poj 3080 Blue Jeans (暴力枚举子串+kmp)

    Description The Genographic Project is a research partnership between IBM and The National Geographi ...

  6. A1142. Maximal Clique

    A clique is a subset of vertices of an undirected graph such that every two distinct vertices in the ...

  7. (九)逻辑运算,order by,desc

    逻辑运算 AND,OR,NOT ......where 表达式1  and 表达式2: ......where 表达式2  and 表达式1: SQL优化: SQL在解析where时是从右向左解析的. ...

  8. 若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet

    http://www.cnblogs.com/Steven7Gao/archive/2012/06/13/2547905.html 若要允许 GET 请求,请将 JsonRequestBehavior ...

  9. R语言实现两文件对应行列字符替换(解决正负链统一的问题)

    假设存在文件file1.xlsx,其内容如下: 存在文件file2.xlsx,其内容如下: 现在我想从第七列开始,将file2所有的字符替换成file1一样的,即第七.八.九.十列不需要改变,因为fi ...

  10. bcftools或vcftools提取指定区段的vcf文件(extract specified position )

    下载安装bcftools 见如下命令: bcftools filter 1000Genomes.vcf.gz --regions 9:4700000-4800000 > 4700000-4800 ...