session和application内置对象

一、Session内置对象

  分析得知request内置对象中的属性只是在当次请求中有效,经过客户端跳转之后就无效,因为客户端跳转属于第二个请求,也就是说request只代表当次请求的对象,如果要让客户端跳转之后保存的属性还有效,则可以使用session内置对象。用户的信息保存在request内置对象中是不合理的,应该保存到表示 一个用户的内置对象中,就是session内置对象,因为Session就算客户端跳转了,保存的属性是有效的。session内置对象的类型是:HttpSession,其常见的方法有:

1.public void setAtrribute(String name, Object value)     保存属性

2.public Object getAttribute(String name)  根据属性名取得值,只能取得使用setAttribute()保存的数据值

3.public void invalidate()    销毁当前session,一般用来实现用户注销功能

4.public String getId()   取得Session的编号,其实这个编号和浏览器中的名字叫做 JSESSIONID cookie的值是一样的

二、application内置对象

  我们知道repuest内置对象保存的属性只是在当次请求有效,经过客户端跳转之后就无效了,保存在session内置对象中属性范围当前用户有效,关闭当前浏览器就失效。如果要让关闭浏览器后属性还有效则该属性应该保存在一个更大内置对象中,该对象就是application内置对象,是一个表示服务器范围的内置对象。application内置对象的类型是:ServletContext

常见的方法有:

1.Object getAttribute(String name) 返回给定名的属性值

2.Enumeration getAttributeNames() 返回所有可用属性名的枚举

扫描二维码关注公众号,回复: 5975957 查看本文章

3.void setAttribute(String name,Object obj) 设定属性的属性值

4.void removeAttribute(String name) 删除一属性及其属性值

5.String getServerInfo() 返回JSP(Servlet)引擎名及版本号

6.String getRealPath(String path) 返回一虚拟路径的真实路径

7.ServletContext getContext(String uripath) 返回指定WebApplication的application对象

下面的demo实现的在线人数的监听

public class OnlineNumber extends HttpServlet{
    //保存用户名
    private Set<String> names= new HashSet<String>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String pathInfo = req.getPathInfo();
        System.out.println(pathInfo);
        if ("/login".equals(pathInfo)) {
            this.login(req, resp);
        
        }else if ("/logout".equals(pathInfo)) {
            this.logout(req, resp);
        }
    }
    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        System.out.println(username);
        //如果为null则表示还没有登录
        if (req.getSession().getAttribute("username")==null) {
            if (!"".equals(username)) {//只有输入的用户名不能为空字符串才能进行操作
                req.getSession().setAttribute("username", username);
                //将用户名保存到Set集合中
                names.add(username);
                //再将names集合保存到application内置对象中
                req.getServletContext().setAttribute("users", names);
                req.getServletContext().setAttribute("count", names.size());
            }
        }
        //继续跳转到在线显示的页面
        resp.sendRedirect("/MvcPro/pages/onlinelogin.jsp");
    }
    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        names.remove(req.getSession().getAttribute("username"));
        //销毁当前用户的session内置对象
        req.getSession().invalidate();
        try {
            req.getServletContext().setAttribute("count", names.size());
            resp.sendRedirect("/MvcPro/pages/onlinelogin.jsp");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<base href= "/MvcPro/">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>
        在线人数为:${count==null ? 0 : count} 
    </h1>
        ${users}
    <form action="online/login" method="POST">
        <fieldset>
           <legend>请登录</legend>
            用户名:<input type="text" name="username" ><br/><br/>
            <input style="margin-left:60px" type="submit" value="提交">
        </fieldset>
    </form>
    <a href="online/logout" >注销</a>
</body>
</html>

web.xml配置

<servlet-name>onlineServlet</servlet-name>
<servlet-class>com.sxt.mvcpro.controller.OnlineNumber</servlet-class>

<servlet-name>onlineServlet</servlet-name>
<url-pattern>/online/*</url-pattern>

Session与Application区别

1.session是会话变量,只要同一个浏览器没有被关闭,session对象就会存在。因此在同一个浏览器窗口中,无论向服务器发送多少请求,session对象只有一个。但是如果在一个会话中,客户端长时间不向服务器发出请求,session对象就会自动消失。这个时间取决于服务器,但是我们可以通过编写程序进行修改这个session的生命周期的时间。session.setMaxInactiveInterval(10000);//用来设置session的有效期为10000秒,超出这个范围将失效。

并且通过session对象可以存储或者读取客户的相关信息,例如用户名或购物信息等,可以通过session对象的setAttribute(String name,Object obj)方法和getAttribute(String name)的方法实现。注意的是getAttribute()方法的返回值是Object类型,如果将获取到的信息赋给String类型的变量,则需要进行强制类型转换或者调用其的toString()方法。

session.setAttribute("user","小名");
String user=(String)session.getAttribute("user");

2.application它类似于系统的全局变量,用于保存所有程序中的公有数据。它在服务器启动时自动创建,在服务器停止时销毁。当application对象没有被销毁的时候,所有用户都可以享用该application对象。它的生命周期可以说是最长的。也就是说同时再打开另一个浏览器,他们使用的都是同一个application对象。




猜你喜欢

转载自www.cnblogs.com/whymoney1000/p/10752431.html
今日推荐