玖叶教程网

前端编程开发入门

java之ServletContext(java之父找工作被拒)

ServletContext,Servlet的上下文环境。

  1. 一个Servlet仅有一个ServletContext对象(单例模式);
  2. ServletContext的生命周期始于Tomcat启动项目到项目被关闭;
  3. ServletContext主要用于多Servlet之间的数据传递。

ServletContext属于域对象,域对象一般有以下四种:

ServletContext

PageContext

ServletRequest

HttpSession

所谓域对象,可以可以在不同的Servlet中传递数据。

域对象的通用方法有三个:

  1. void setAttribut(String name,Object value);
  2. Object getAttribute(String name);
  3. void removeAttribute(String name);

ServletContext对象的获取:

public ServletContext getServletContext();

此方法在GeneriServlet类中,因此直接调用:this.getServletContext();

ServletContext对资源的获取:

String pathname = context.getRealPath("/xxx.xx"); // /web-inf/a.txt

Set<String> paths = context.getResourcePaths("/xxx"); //获取当前目录下的所有文件和文件夹,仅限当前目录

InputStream in = context.getResourceAsStream("/xxx.xx"); //获取资源流

实例:实现网站访问次数的统计及保存

@WebServlet(urlPatterns = {"/getCount"},     
            //初始化参数       
            initParams = {@WebInitParam(name = "name1",value = "a",description = ""),       
@WebInitParam(name = "name2",value = "b",description = "")},   loadOnStartup = 1)
public class MyServlet extends HttpServlet{   
 	 @Override    
    public  void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {       
      //请求和响应编码设置       
      req.setCharacterEncoding("utf-8");    
      resp.setContentType("text/html;charset=utf-8");    
      //获取属性count值,每次请求+1,然后回写并响应  
      ServletContext context = this.getServletContext();      
      Integer count = (Integer) (context.getAttribute("count"));       
      count++;       
      context.setAttribute("count",count);      
      //响应       
      resp.getWriter().print("response:"+count);   
      System.out.println(count);   
    }    

  @Override   
  public void init() throws ServletException { 
    ServletContext context = this.getServletContext();      
    /*        初始化方法中设置,仅运行一次       
    1.此方法服务器重启失效,要保存count值,需要输出到磁盘中保存          
    context中获取count属性值,如果为null则赋值0      
    2.在count.txt文件中获取数值,保存在count属性中  回写至context  */        
    String countPath = context.getRealPath("/count.txt");     
    File file = new File(countPath);    
    if(!file.exists()){       
      try {             
        file.createNewFile();    
      } catch (IOException e) {      
        e.printStackTrace();        
      }      
    }         
    Integer count = 0; 
    try(InputStream inputStream = context.getResourceAsStream("/count.txt"); 
    Scanner scanner = new Scanner(inputStream)){        
      while (scanner.hasNext()){              
        count = Integer.parseInt(scanner.next()) ;
      }       
    }catch (Exception e){   
      e.printStackTrace(); 
    }  
    //向ServletContext中存入count属性
    context.setAttribute("count",count); 
  }   

  @Override   
  public void destroy() {    
    //服务器异常关闭或者重启时会将count值写入磁盘      
    ServletContext context = this.getServletContext();    
    Integer count = (Integer) (context.getAttribute("count")); 
    //带资源的try语句会自动关闭        
    try(PrintStream ps = new PrintStream(context.getRealPath("/count.txt"));) {    
      ps.print(count);      
    } catch (FileNotFoundException e) {      
      e.printStackTrace();        
    }   
  }
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言