GVKun编程网logo

servlet 解析演进(7)-session(3)("/servlet/session")

7

在本文中,我们将带你了解servlet解析演进在这篇文章中,我们将为您详细介绍servlet解析演进的方方面面,并解答7-session常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的Htt

在本文中,我们将带你了解servlet 解析演进在这篇文章中,我们将为您详细介绍servlet 解析演进的方方面面,并解答7-session常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的HttpServletRequest getSession()、HttpServletRequest.getSession特性和Session周期、java servlet拾遗(3)-servlet 线程安全问题、java web(三):ServletContext、session、ServletConfig、request、response对象

本文目录一览:

servlet 解析演进(7)-session(3)(

servlet 解析演进(7)-session(3)("/servlet/session")

public class StandardManager
    extends ManagerBase
    implements LifecyclePropertyChangeListenerRunnable {
     //检验过期时间的时间间隔
    private int checkInterval = 60;
//类描述信息(名称/版本号)
    private static final String info = "StandardManager/1.0";
     //为支持该组件的生命周期事件触发器
    protected LifecycleSupport lifecycle = new LifecycleSupport(this);
    //允许的session活跃数。如果为-1则数量无限制
    private int maxActiveSessions = -1;
    //描述类名称(为日志准备)
    protected static String name = "StandardManager";
    //session持久化到磁盘的路径名称(如果是相对路径则会根据javax.servlet.context.tempdir)
    //绝对定位session位置
    private String pathname = "SESSIONS.ser";
    //容器是否被启动
    private boolean started = false;
   //后台线程
    private Thread thread = null;
   //后台线程是否完成标示
    private boolean threadDone = false;
   //为后台线程注册的名称
    private String threadName = "StandardManager";
    public int getCheckInterval() {
        return (this.checkInterval);
    }
    public void setCheckInterval(int checkInterval) {
        int oldCheckInterval = this.checkInterval;
        this.checkInterval = checkInterval;
        support.firePropertyChange("checkInterval",
                                   new Integer(oldCheckInterval),
                                   new Integer(this.checkInterval));
    }
    //设置管理器关联的容器,如果是上下文类型则会启动属性变更监听事件
    public void setContainer(Container container) {
        // De-register from the old Container (if any)
        //写在旧的容器,触发属性变更监听器的remove事件
        if ((this.container != null) && (this.container instanceof Context))
            ((Context) this.container).removePropertyChangeListener(this);
        //为父类设置容器信息
        super.setContainer(container);
       //注册新的容器
        // Register with the new Container (if any)
        if ((this.container != null) && (this.container instanceof Context)) {
            setMaxInactiveInterval
                ( ((Context) this.container).getSessionTimeout()*60 );
            ((Context) this.container).addPropertyChangeListener(this);
        }
    }
    //返回类描述信息
    public String getInfo() {
        return (this.info);
    }
    public int getMaxActiveSessions() {
        return (this.maxActiveSessions);
    }
    public void setMaxActiveSessions(int max) {
        int oldMaxActiveSessions = this.maxActiveSessions;
        this.maxActiveSessions = max;
        support.firePropertyChange("maxActiveSessions",
                                   new Integer(oldMaxActiveSessions),
                                   new Integer(this.maxActiveSessions));
    }
    //返实现类的short name
    public String getName() {
        return (name);
    }
//返回持久化session路径
    public String getPathname() {
        return (this.pathname);
    }
    public void setPathname(String pathname) {
        String oldPathname = this.pathname;
        this.pathname = pathname;
        support.firePropertyChange("pathname", oldPathname, this.pathname);
    }
//根据Mnager的属性指定的缺省的设置创建并返回新的session对象。该session id将在该
    //方法中被设置。如果session无法正确创建,则返回null
    public Session createSession() {
        if ((maxActiveSessions >= 0) &&
          (sessions.size() >= maxActiveSessions))
            throw new IllegalStateException
                (sm.getString("standardManager.createSession.ise"));
        return (super.createSession());
    }
    //重新加载持久化文件里面的session信息。如果不支持持久化,则会返回
    public void load() throws ClassNotFoundException, IOException {
        if (debug >= 1)
            log("Start: Loading persisted sessions");
       //初始化数据结构
        recycled.clear();
        sessions.clear();
        // 开启指定路径的文件
        File file = file();
        if (file == null)
            return;
        if (debug >= 1)
            log(sm.getString("standardManager.loading", pathname));
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Loader loader = null;
        ClassLoader classLoader = null;
        try {
            //设置文件输入流
            fis = new FileInputStream(file.getAbsolutePath());
            //设置输入流二进制缓存
            BufferedInputStream bis = new BufferedInputStream(fis);
            if (container != null)
              //获取容器的加载器
                loader = container.getLoader();
            if (loader != null)
                //获取容器加载器中的类加载器
                classLoader = loader.getClassLoader();
            if (classLoader != null) {
                if (debug >= 1)
                    log("Creating custom object input stream for class loader "
                        + classLoader);
                //bis子类对象
                ois = new CustomObjectInputStream(bis, classLoader);
            } else {
                if (debug >= 1)
                    log("Creating standard object input stream");
                ois = new ObjectInputStream(bis);
            }
        } catch (FileNotFoundException e) {
            if (debug >= 1)
                log("No persisted data file found");
            return;
        } catch (IOException e) {
            log(sm.getString("standardManager.loading.ioe", e), e);
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException f) {
                    ;
                }
                ois = null;
            }
            throw e;
        }
       //加载之前卸载的活跃sessions信息
        synchronized (sessions) {
            try {
                //获得被卸载的数量
                Integer count = (Integer) ois.readObject();
                int n = count.intValue();
                if (debug >= 1)
                    log("Loading " + n + " persisted sessions");
                for (int i = 0; i < n; i++) {
                    StandardSession session = new StandardSession(this);
                    //从ois中获取属性值并设置到session中
                    session.readObjectData(ois);
                    //设置管理器
                    session.setManager(this);
                    sessions.put(session.getId(), session);
                    //将session置为活跃
                    ((StandardSession) session).activate();
                }
            } catch (ClassNotFoundException e) {
              log(sm.getString("standardManager.loading.cnfe", e), e);
                if (ois != null) {
                    try {
                        //关闭输入流
                        ois.close();
                    } catch (IOException f) {
                        ;
                    }
                    ois = null;
                }
                throw e;
            } catch (IOException e) {
              log(sm.getString("standardManager.loading.ioe", e), e);
                if (ois != null) {
                    try {
                      //关闭一次出错在关闭一次
                        ois.close();
                    } catch (IOException f) {
                        ;
                    }
                    ois = null;
                }
                throw e;
            } finally {
                // 关闭输入流
                try {
                    if (ois != null)
                        ois.close();
                } catch (IOException f) {
                    // ignored
                }
                // 删除持久化文件
                if (file != null && file.exists() )
                    file.delete();
            }
        }
        if (debug >= 1)
            log("Finish: Loading persisted sessions");
    }
//在不同的持久化机制中保存现有的活跃session信息,如果不支持持久化则返回
    public void unload() throws IOException {
        if (debug >= 1)
            log("Unloading persisted sessions");
        // 打开持久化文集
        File file = file();
        if (file == null)
            return;
        if (debug >= 1)
            log(sm.getString("standardManager.unloading", pathname));
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            //文件输出流
            fos = new FileOutputStream(file.getAbsolutePath());
            //ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream
            //该类实现缓冲的输出流。通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,
            // 而不必针对每次字节写入调用底层系统。
            oos = new ObjectOutputStream(new BufferedOutputStream(fos));
        } catch (IOException e) {
            log(sm.getString("standardManager.unloading.ioe", e), e);
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException f) {
                    ;
                }
                oos = null;
            }
            throw e;
        }
        // 在写入session信息之前,首先写入活跃session个数信息。和读取过程对应
        ArrayList list = new ArrayList();
        synchronized (sessions) {
            if (debug >= 1)
                log("Unloading " + sessions.size() + " sessions");
            try {
                //将活跃的session个数信息写入到写出流
                oos.writeObject(new Integer(sessions.size()));
                Iterator elements = sessions.values().iterator();
                while (elements.hasNext()) {
                    StandardSession session =
                        (StandardSession) elements.next();
                    //将session信息放入到list中
                    list.add(session);
                    //将session置为非活跃
                    ((StandardSession) session).passivate();
                    //序列化session各个字段,并输出到输出流
                    session.writeObjectData(oos);
                }
            } catch (IOException e) {
                log(sm.getString("standardManager.unloading.ioe", e), e);
                if (oos != null) {
                    try {
                        oos.close();
                    } catch (IOException f) {
                        ;
                    }
                    oos = null;
                }
                throw e;
            }
        }
        // Flush and close the output stream
        try {
            //flush 缓冲区,让缓冲区数据全部写出去
            oos.flush();
            //关闭输出流
            oos.close();
            //将对象引用也置为null(值得学习借鉴)
            oos = null;
        } catch (IOException e) {
            if (oos != null) {
                try {
                    //关闭时候出错再关一次
                    oos.close();
                } catch (IOException f) {
                    ;
                }
                oos = null;
            }
            throw e;
        }
        // 将我们刚刚持久化的所有session置为过期Expire all the sessions we just wrote
        if (debug >= 1)
            log("Expiring " + list.size() + " persisted sessions");
        Iterator expires = list.iterator();
        while (expires.hasNext()) {
            StandardSession session = (StandardSession) expires.next();
            try {
                session.expire(false);
            } catch (Throwable t) {
                ;
            }
        }
        if (debug >= 1)
            log("Unloading complete");
    }
    // ------------------------------------------------------ Lifecycle Methods
    /**
     * Add a lifecycle event listener to this component.
     *
     * @param listener The listener to add
     */
    public void addLifecycleListener(LifecycleListener listener) {
        lifecycle.addLifecycleListener(listener);
    }
    /**
     * Get the lifecycle listeners associated with this lifecycle. If this 
     * Lifecycle has no listeners registered, a zero-length array is returned.
     */
    public LifecycleListener[] findLifecycleListeners() {
        return lifecycle.findLifecycleListeners();
    }
    /**
     * Remove a lifecycle event listener from this component.
     *
     * @param listener The listener to remove
     */
    public void removeLifecycleListener(LifecycleListener listener) {
        lifecycle.removeLifecycleListener(listener);
    }
    /**
     * Prepare for the beginning of active use of the public methods of this
     * component.  This method should be called after <code>configure()</code>,
     * and before any of the public methods of the component are utilized.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    public void start() throws LifecycleException {
        if (debug >= 1)
            log("Starting");
        // Validate and update our current component state
        if (started)
            throw new LifecycleException
                (sm.getString("standardManager.alreadyStarted"));
        lifecycle.fireLifecycleEvent(START_EVENT, null);
        started = true;
        // Force initialization of the random number generator
        if (debug >= 1)
            log("Force random number initialization starting");
        String dummy = generateSessionId();
        if (debug >= 1)
            log("Force random number initialization completed");
        // Load unloaded sessions, if any
        try {
            load();
        } catch (Throwable t) {
            log(sm.getString("standardManager.managerLoad"), t);
        }
        // Start the background reaper thread
        threadStart();
    }
    /**
     * Gracefully terminate the active use of the public methods of this
     * component.  This method should be the last one called on a given
     * instance of this component.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that needs to be reported
     */
    public void stop() throws LifecycleException {
        if (debug >= 1)
            log("Stopping");
        // Validate and update our current component state
        if (!started)
            throw new LifecycleException
                (sm.getString("standardManager.notStarted"));
        lifecycle.fireLifecycleEvent(STOP_EVENT, null);
        started = false;
        // Stop the background reaper thread
        threadStop();
        // Write out sessions
        try {
            unload();
        } catch (IOException e) {
            log(sm.getString("standardManager.managerUnload"), e);
        }
        // Expire all active sessions
        Session sessions[] = findSessions();
        for (int i = 0; i < sessions.length; i++) {
            StandardSession session = (StandardSession) sessions[i];
            if (!session.isValid())
                continue;
            try {
                session.expire();
            } catch (Throwable t) {
                ;
            }
        }
        // Require a new random number generator if we are restarted
        this.random = null;
    }
    // ----------------------------------------- PropertyChangeListener Methods
    /**
     * Process property change events from our associated Context.
     *
     * @param event The property change event that has occurred
     */
    public void propertyChange(PropertyChangeEvent event) {
        // Validate the source of this event
        if (!(event.getSource() instanceof Context))
            return;
        Context context = (Context) event.getSource();
        // Process a relevant property change
        if (event.getPropertyName().equals("sessionTimeout")) {
            try {
                setMaxInactiveInterval
                    ( ((Integer) event.getNewValue()).intValue()*60 );
            } catch (NumberFormatException e) {
                log(sm.getString("standardManager.sessionTimeout",
                                 event.getNewValue().toString()));
            }
        }
    }
    //返回持久化文件路径下的文件对象
    private File file() {
//持久化路径为空则返回null
        if (pathname == null)
            return (null);
        //创建持久化文件
        File file = new File(pathname);
        //如果不是绝对路径,则根据上下文中的工作路径
        if (!file.isAbsolute()) {
            if (container instanceof Context) {
                ServletContext servletContext =
                    ((Context) container).getServletContext();
                File tempdir = (File)
                    servletContext.getAttribute(Globals.WORK_DIR_ATTR);
                if (tempdir != null)
                    file = new File(tempdir, pathname);
            }
        }
//        if (!file.isAbsolute())
//            return (null);
        return (file);
    }
//将所有的过期session置为无效
    /**
     * Invalidate all sessions that have expired.
     */
    private void processExpires() {
//获取当前时间
        long timeNow = System.currentTimeMillis();
//获取到所有的活跃session
        Session sessions[] = findSessions();
//遍历session容器
        for (int i = 0; i < sessions.length; i++) {
            StandardSession session = (StandardSession) sessions[i];
            //如果该session信息无效,则继续
            if (!session.isValid())
                continue;
            //获取session的最长非活跃事件
            int maxInactiveInterval = session.getMaxInactiveInterval();
            //如果小于 0 ,则session始终保持活跃
            if (maxInactiveInterval < 0)
                continue;
            int timeIdle = // 计算session未被访问的时间间隔
                (int) ((timeNow - session.getLastAccessedTime()) / 1000L);
            //如果时间间隔大于最大非活跃时间间隔
            if (timeIdle >= maxInactiveInterval) {
                try {
                    //将session置为过期
                    session.expire();
                } catch (Throwable t) {
                    log(sm.getString("standardManager.expireException"), t);
                }
            }
        }
    }
    //将线程休眠指定时间
    private void threadSleep() {
        try {
            Thread.sleep(checkInterval * 1000L);
        } catch (InterruptedException e) {
            ;
        }
    }
//开启一个后台线程,周期性地检查session过期时间
   private void threadStart() {
//如果线程不为空,则返回。说明该线程任务尚未完成。不能开启新的任务
        if (thread != null)
            return;
//设置后台线程属性
        threadDone = false;
        threadName = "StandardManager[" + container.getName() + "]";
        thread = new Thread(this, threadName);
        thread.setDaemon(true);
        thread.setContextClassLoader(container.getLoader().getClassLoader());
        thread.start();
    }
//关闭周期性检查session过期时间的线程
    private void threadStop() {
        if (thread == null)
            return;
        threadDone = true;
        thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException e) {
            ;
        }
        thread = null;
    }
    // ------------------------------------------------------ Background Thread
    /**
     * The background thread that checks for session timeouts and shutdown.
     */
    public void run() {
        // Loop until the termination semaphore is set
        while (!threadDone) {
            threadSleep();
            processExpires();
        }
    }

调用关系代码:

//invoke: http://localhost:8080/myApp/Session
    //System.getProperty("user.dir")工作目录
    System.setProperty("catalina.base", System.getProperty("user.dir"));
    //连接器
    Connector connector = new HttpConnector();
    //servlet包装容器
    Wrapper wrapper1 = new SimpleWrapper();
    wrapper1.setName("Session");
    wrapper1.setServletClass("SessionServlet");
//上下文容器
    Context context = new StandardContext();
    // StandardContext''s start method adds a default mapper
  //设置上下文的uri路径
    context.setPath("/myApp");
    //设置上下文的文件路径(可以是相对路径、绝对路径、URL)
    context.setDocBase("myApp");
//将包装器放置到上下文的子容器中
    context.addChild(wrapper1);
//mapping 设置。
    context.addServletMapping("/myApp/Session""Session");
    //添加配置监听器,
    LifecycleListener listener = new SimpleContextConfig();
    ((Lifecycle) context).addLifecycleListener(listener);
    //加载器(里面包含类加载器)
    Loader loader = new WebappLoader();
    // associate the loader with the Context
    context.setLoader(loader);
  //连接器包含容器信息
    connector.setContainer(context);
//session管理器
    Manager manager = new StandardManager();
    //设置上下文的session管理器
    context.setManager(manager);
    try {
      //连接器初始化
      connector.initialize();
      //连接器开始
      ((Lifecycle) connector).start();
      //上下文容器开启
      ((Lifecycle) context).start();
      //可以再控制台输入数据触发容器关闭操作
      System.in.read();
      ((Lifecycle) context).stop();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }


HttpServletRequest getSession()

HttpServletRequest getSession()

1、打开文档  http://tomcat.apache.org/tomcat-5.5-doc/servletapi/

2、Packages   javax.servlet.http

      Interface   HttpServletRequest

3、HttpSession  getSession 方法

4、无入参方法: 当前请求有session时返回,没有则创建一个

5、有入参的方法: 

    true: 同不传入参,有则返回,无则创建新的session

    false: 传false 且当前请求不存在session,则返回null 

 

HttpServletRequest.getSession特性和Session周期

HttpServletRequest.getSession特性和Session周期

request.getSession()和HttpServletRequest.getSession(boolean)的区别Session的生命周期

 

HttpSession session=request.getSession();

1查询浏览器中是否有session对象,

2如果没有,就创建一个新的session对象

3如果有,就取出session对象

 

HttpSession session=HttpServletRequest.getSession(boolean);

当boolean为true时,和request.getSession()一样

当boolen为false时,只查询,没有查到,返回null

 

 

HttpSession 的生命周期:

 

java servlet拾遗(3)-servlet 线程安全问题

java servlet拾遗(3)-servlet 线程安全问题

Servlet容器启动时,会对每一个Servlet对象实例化一次,而且是仅仅一次,在运行的时候,不管多少个请求都是同时执行这一个Servlet对象实例。 也就是说Servlet对象是单实例多线程,这个时候,就需要注意到并发安全问题。

 

一、为什么不安全

    先看两个定义:

  • 实例变量:实例变量在类中定义。类的每一个实例都拥有自己的实例变量,如果多个线程同时访问该实例的方法,而该方法又使用到实例变量,那么这些线程同时访问的是同一个实例变量,会共享该实例变量。
  • 局部变量:局部变量在方法中定义。每当一个线程访问局部变量所在的方法时,在线程的堆栈中就会创建这个局部变量,线程执行完这个方法时,该局部变量就被销毁。所有多个线程同时访问该方法时,每个线程都有自己的局部变量,不会共享。

例如:

public class MyServlet extends HttpServlet{
 private static final long serialVersionUID = 1L;
 
 private String userName1 = null;//实例变量
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException{
  userName1 = req.getParameter("userName1");
 
  String userName2 = req.getParameter("userName2");//局部变量
 
  //TODO 其他处理
 }
}

userName1则是共享变量,多个线程会同时访问该变量,是线程不安全的。

userName2是局部变量,不管多少个线程同时访问,都是线程安全的。

 

二、怎么解决

  • 如果不涉及到全局共享变量,全部放到局部变量,最好的做法
  • 如果使用到全局共享的场景,可以使用加锁的方式,比如
public class MyServlet extends HttpServlet{
 private static final long serialVersionUID = 1L;
 
 private String userName1 = null;//实例变量
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException{
  synchronized (userName1) {
   userName1 = req.getParameter("userName1");
   //TODO
  }
 
 
  String userName2 = req.getParameter("userName2");//局部变量
 
  //TODO 其他处理
 }
}

或者使用线程安全的StringBuffer去代替String,

或者使用线程安全的容器比如:   java.util.concurrent.ConcurrentHashMap 等等

最好使用乐观锁的形式去加锁

 

java web(三):ServletContext、session、ServletConfig、request、response对象

java web(三):ServletContext、session、ServletConfig、request、response对象

  上一篇讲了Servlet:

    1)什么是Servlet【servlet本身就是一种Java类,这种Java类提供了web形式的方法,只要实现了servlet接口的类,都是一种servlet资源。】    

    2)三种方式创建Servlet(继承HTTPServlet使我们使用的)

    3)Servlet的生命周期【通过三个成员方法体现】

 


 

  

一:ServletContext对象

ServletContext对象被称作应用/servlet上下文。

  生命周期:

    启动tomcat服务器被创建

    关闭tomcat服务器被销毁【每个web项目有且只有一个ServletConfig对象】

  

  获取方式:this.getServletContext(); this.getServletConfig.getServletContext();request.getServletContext();

 

  作用范围:

    在整个项目运行期间,有且只有一个ServletConfig对象,为所有用户共享。

 

   

  使用:

    1)web项目共享数据   setAttribute(String key,Object value); //已键值对存放数据,整个项目运行期间都存在

      getAttribute(String key); //通过键获取数据

      removeAttribute(String kye); //通过键移除数据

    

    2)全局初始化参数

       如果在web.xml中配置

          <context-param>

            <param-name>id</param-name>

            <param-value>11</param-value>

    

            <param-name>name</param-name>

            <param-value>jack</param-value>

 

            <param-name>age</param-name>

            <param-value>18</param-value>

          </context-param>

      this.getServletContext().getInitParameter("id"); // 11

      this.getServletContext().getInitParameter("name"); // jack

      this.getServletContext().getInitParameter("age"); // 18

      this.getServletConfig().getInitParameterNames(); //获得全局参数所有<param-name>值

    

    3)获取web项目资源

      this.getServletContext().getRealPath("WEB-INF/web.xml");    //获取web项目下指定文件的绝对路径【D:\apache_tomcat\apache-tomcat-7.0.62-windows-x64\apache-tomcat-7.0.62\webapps\StudyServlet\WEB-INF\web.xml】

    

      InputStream getResourceAsStream(java.lang.String path); //获取web项目下指定资源的内容,返回的是字节输入流

    浏览器请求一个Servlet,然后通过上面方法把一个html页面写过去。页面代码:

      

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		ServletContext context = this.getServletContext();
		//ips.html在webContent目录下
		InputStream ips = context.getResourceAsStream("/ips.html");
		BufferedReader reader = new BufferedReader(new InputStreamReader(ips));
		String str = null;
		while((str = reader.readLine()) != null)
			response.getWriter().write(str);
		
}

 

   浏览器效果:

  

  效果达到了,但出现???,这是中文乱码问题,后面会通过response解决。

    

二:HttpSession对象。

  HpptSession对象和ServletContent对象类似,不过它的作用范围是一次会话期间,一次会话可以包括对此request请求。

  生命周期:第一次调用request.getSession(true);时被创建。【参数boolean类型,true是有session则返回,无则创建一个新的;false则返回一个null如果当前没有有效的session。无参的getSession是调用传入false的该方法】

调用session.invalidate()或自动超时则被销毁。默认超时时间30分钟,超时时间指:【客户端不与服务器进行交互的时间】。【代码设置:session.setMaxInactiveInterval(60*30);单位:秒;web.xml中设置:

    <session-config> 

 

                      <session-timeout>1</session-timeout> 

 

                </session-config>

该标签与servlet标签处于同一级别。单位:分钟,必须为整数

  用途:一般用作一次会话期间保存数据,getAtrribute(),setAttribute(),removeAtrribute()用法和ServletContent对象用法一致。

 

 注意:服务器异常关闭不会销毁session,丢失session。服务器正常关闭不会销毁session,也不会丢失。

 

三:ServletConfig对象  

  在Servlet 的配置文件中,可以用一个或多个<init-param>标签为servlet配置一些初始化参数。

 

当servlet配置了初始化参数之后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给Servlet。进而,程序员通过Servlet对象得到当前servlet的初始化参数信息。

  上一篇我们说过,一般会重写无参的init方法,所以通过this.getServletConfig()获得对象。

  web.xml中:

  

 

  servlet中:

    

@Override
    public void init() throws ServletException {
    	ServletConfig config = this.getServletConfig();
    	config.getInitParameter("id"); //223
    	config.getInitParameter("age"); //jack
    	Enumeration<String> keys = config.getInitParameterNames();
    	while(keys.hasMoreElements())
    		System.out.println(keys.nextElement());
    	
    }

 

 

 

 

四:request对象、response对象

  request对象的作用范围是一次http请求响应之内,request也可以存放数据,和ServletContent和session对象类似,不过作用范围比它们两个小。

 

  request可以用过方法getParameter(String key):String;获取浏览器传递的参数【不管是在url后拼接参数的get提交方式或参数在请求体的post提交方式都是用该方法】,

getParameterNames():Enumeration<?>;可以获取所有的key值,没有参数则返回一个空的Enumeration。接收数据前可以调用setCharacterEncoding(charset);设置接收格式。

  request还可以用于服务器内部跳转【还是一次http请求响应,所以request在N次内部跳转中是同一个】。request.getRequestDispatcher("HelloWorld").forword(request,reponse);

可以跳转到WebContent目录下的一个html页面或者跳转到另一个Servlet请求处理。

 

  response对象作为响应向浏览器发送数据,可以通过setCharacterEncoding(charset)设置编码格式,setContentType("text/html;charset=utf-8")告诉浏览器已html文件解析。

getWriter()可以获得一个字符输入流,该流可以向浏览器写东西。

  response还可以用作客户端重定向,sendRedirect(path)。例如:跳转到WebContent目录下的one.html,response.sendRedirect("one.html");

跳转到另一个Servlet,response.sendRedirect("HelloWorld")。【注意:不要加"/"】

 

  "/"在服务器内部跳转和客户端重定向中怎么使用?代表这什么?

内部跳转加不加"/"不影响,客户端重定向不能加。"/"在服务器代表当前web项目【http://ip:port/项目名/】;

在客户端表示当前页面【http://ip:port/】。

 注意: 在WebContent下有一个one.html和一个HTML目录,HTML目录下有一个two.html,两个html页面代码一样。

    

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
	<a href="HelloWorld">点击超链接进行跳转</a>
</body>
</html>

 

 在浏览器分别访问http://127.0.0.1:7778/StudyServlet/one.html和http://127.0.0.1:7778/StudyServlet/HTML/two.html,然后点击超链接进行跳转。

在two.html中点击超链接发生错误,错误提示【HTTP Status 404 - /StudyServlet/HTML/HelloWorld】,404---没有该资源。为啥呐?因为在客户端页面发送请求是相对于

当前路径的,这可能不方便。可以通过base标签设置。<base href="http://127.0.0.1:7778/StudyServlet/"></base>,这样在一个页面访问另一个资源时就可以相对于base标签设置的了。

    等后面学了jsp可以不必限定死协议、ip、port、项目名。

       request.getScheme();//获取协议 http

      request.getServerName(); //获取ip,127.0.0.1

      request.getServerPort(); //获取端口,7778

      request.getContextPath(); //获取项目名,StudyServlet

 

response,response还有很多方法,具体可以查API。request和resonse的具体用法下一篇讲。

 

总结:

  1.SevletContext对象。获取途径,生命周期,作用范围,以及一些该对象的一些用法【存取数据,获取全局配置参数,获取web项目资源】

  2.HTTPSession对象。session对象和上面类似,只是作用范围变成了一次会话期间。

  3.ServletConfig对象一般用作来获取web.xml中servlet配置中<init-param>...</init-param>里的参数。如果servlet配置了<load-on-startup>正整数</load-on-startup>,

init方法就可以随服务器启动而被调用,继而可以在init中利用该对象做一些初始化配置。

  4.request和response对象。一般用来服务器内部跳转和客户端重定向。

当然还有其他用法。下一篇通过一个小项目讲解request和response一些具体用法:比如文件的上传和下载...

 

 

 

  

 

 

  

    

今天关于servlet 解析演进7-session的讲解已经结束,谢谢您的阅读,如果想了解更多关于HttpServletRequest getSession()、HttpServletRequest.getSession特性和Session周期、java servlet拾遗(3)-servlet 线程安全问题、java web(三):ServletContext、session、ServletConfig、request、response对象的相关知识,请在本站搜索。

本文标签: