(1)关于对ServletContext的理解:
(2)向servletcontext中添加属性
- package com.tsinghua;
- import javax.servlet.http.*;
- import javax.servlet.*;
- import java.io.*;
- public class ServletContextTest1 extends HttpServlet {
- //处理get请求
- //req: 用于获得客户端(浏览器)的信息
- //res: 用于向客户端(浏览器)返回信息
- 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: 用于获得客户端(浏览器)的信息
- //res: 用于向客户端(浏览器)返回信息
- 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: 用于获得客户端(浏览器)的信息
- //res: 用于向客户端(浏览器)返回信息
- 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: 用于获得客户端(浏览器)的信息
- //res: 用于向客户端(浏览器)返回信息
- public void doPost(HttpServletRequest req,HttpServletResponse res){
- this.doGet(req,res);
- }
- }