ServletContext加入和访问

(1)关于ServletContext认识:




(2)向servletcontext中加入属性

package com.tsinghua;

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class ServletContextTest1 extends HttpServlet {
	

	//处理get请求
	//req: 用于获得client(浏览器)的信息
	//res: 用于向client(浏览器)返回信息
	public void doGet(HttpServletRequest req,HttpServletResponse res){
		
		//业务逻辑 
		
		try {
					
			//中文乱码
			res.setContentType("text/html;charset=gbk");
			
			PrintWriter pw=res.getWriter();
			
			//1得到servletcontext
		
			ServletContext sc=this.getServletContext();
			
			//2加入属性 
			sc.setAttribute("myInfo","我是xx");
			
			pw.println ("给sevlet context中加入一个属性 myInfo 该属性相应的值是一个字符串我是xx<br>");
			
			
			//比較session
			HttpSession hs=req.getSession(true);
			hs.setAttribute("test","中国人");
			hs.setMaxInactiveInterval(60*3);
			pw.println("向session中加入一个test属性 他的值是 中国人<br>");	
			
			
			//===当然也能够在servletcontext中放入一个对象
//			Cat myCat=new Cat("小明",30);
//			
//			sc.setAttribute("cat1",myCat);
//			
//			
//			pw.println ("给sevlet context中加入一个属性 cat1 该属性相应的值是一个猫对象<br>");
			
	    }
	    catch (Exception ex) {
	    	
	    	ex.printStackTrace();
	    }
	}
	
	//处理post请求
	//req: 用于获得client(浏览器)的信息
	//res: 用于向client(浏览器)返回信息
	public void doPost(HttpServletRequest req,HttpServletResponse res){
		
		this.doGet(req,res);
		
	}
}

class Cat{
	
	private String name;
	private int age;
	public Cat(String name,int age){
		
		this.name=name;
		this.age=age;
	}
	
	public String getName(){
		return this.name;
	}
	
	public int getAge(){
		
		return this.age;
	}
}

(3)从servletcontext中得到属性

package com.tsinghua;

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;


public class ServletContextTest2 extends HttpServlet {
	

	//处理get请求
	//req: 用于获得client(浏览器)的信息
	//res: 用于向client(浏览器)返回信息
	public void doGet(HttpServletRequest req,HttpServletResponse res){
		
		//业务逻辑 
		
		try {
					
			//中文乱码
			res.setContentType("text/html;charset=gbk");
			
			PrintWriter pw=res.getWriter();
			
			//1得到servlet context
			
			ServletContext sc=this.getServletContext();
			
			//2得到属性和它相应的值
			
			String info=(String)sc.getAttribute("myInfo");
			
			pw.println ("从servlet context中得到属性 myinfo 它相应的值是"+info+"<br>");
			
			
		
			
			//比較session
			HttpSession hs=req.getSession(true);
			String val=(String)hs.getAttribute("test");
			pw.println("session 中的 test="+val+"<br>");
			
			
			//得到另外一个属性
//			Cat myCat=(Cat)sc.getAttribute("cat1");
//			
//			pw.println ("从servlet context中得到属性 cat1 他的名字是"+
//			myCat.getName()+" 他的年龄是"+myCat.getAge()+"<br>");
			
		
				
	    }
	    catch (Exception ex) {
	    	
	    	ex.printStackTrace();
	    }
	}
	
	//处理post请求
	//req: 用于获得client(浏览器)的信息
	//res: 用于向client(浏览器)返回信息
	public void doPost(HttpServletRequest req,HttpServletResponse res){
		
		this.doGet(req,res);
		
	}
}



版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/bhlsheji/p/4643443.html