zoukankan      html  css  js  c++  java
  • Web常用对象(2)

    一、Session

      1、介绍

        HttpSession是一个纯粹的接口,session本身就属于HTTP协议的范畴。

        session的作用就是为了标识一次会话,或者说确认一个用户;并且在一次会话(一个用户多次请求)期间共享数据。

      2、创建对象和属性操作

        

      3、表示会话JSESSIONID

        每当一次请求到达服务器,如果访问了session,服务器会第一步查看是否从客户端回传一个名为JSESSION的Cookie,如果没有则认为这是一次新的会话,会创建一个新的session对象,并用唯一的JSESSIONID为此次会话做一个标志,如果有则认为这是之前标志过的一次会话,返回该对象,达到数据共享

      4、session作用域

        和request域一样可以通过setAttribute(name,value);方法向域对象中添加数据,通过getAttribute(name)从域对象中获取数据,通过removeAttribute(name)从域对象中移除数据。

        

      

      5、session的销毁

        因为session底层依赖Cookie实现,并且该Cookie的有效时间为关闭浏览器,所以关闭浏览器session失效

        当非正常关闭服务器时,session销毁;当正常关闭服务器时,session将被序列化到磁盘上,下次启动服务自动加载到内存。

          序列化:把对象和其状态存到本地磁盘

        1)默认时间到期

          Tomcat中session默认存活时间为30min,一旦有操作session会重新计时。

        2)自己设定到期时间

          ·可以在Tomcat中的web.xml文件中进行修改

          ·session.setMaxInactiveInterval(int);  以秒为单位

        3)立刻失效

          session.invalidate();

        session的销毁或失效意味着本次会话技术,数据共享结束。

    二、ServletContext对象

      1、介绍

        每一个web应用有且仅有一个ServletContext对象,又称Application对象,该对象是与应用程序相关的,当WEB容器启动时,会为每一个WEB应用程序创建一个对应的ServletContext对象。

      2、ServletContext对象的作用

        1)作为域对象用来共享数据,此时数据在整个应用程序中共享

        2)该对象中保存了当前应用程序的相关信息,可以通过方法获取。

           

      3、ServletContext对象的四种获取方法

        

      4、作为域对象

        通过向ServletContext中存取数据,可以使得整个应用程序共享某些数据,不建议存放过多数据,因为ServletContext中的数据一旦存储进去没有手动移除会一直保存

        

    三、文件上传下载

      1、文件上传

        前台页面:

          请求方式为POST,form表单的enctype必须设为“multipart/form-data”.

        后台:需要commos-io和commons-fileupload两个jar包(2.5版本的动态web项目)    

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 设定编码,可以获取中文文件名
            request.setCharacterEncoding("UTF-8");
            // 获取tomcat下的upload目录的路径
            String path = getServletContext().getRealPath("/upload");
            // 临时文件目录
            String tempPath = getServletContext().getRealPath("/temp");
            // 检查我们是否有文件上传请求
            // boolean isMultipart = ServletFileUpload.isMultipartContent( req);
            // 1、声明DiskFileItemFactory工厂类,用于在指定磁盘上设置一个临时目录
            DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));
            // 2、声明ServletFileUpload,接收上面的临时文件。也可以默认值
            ServletFileUpload up = new ServletFileUpload(disk);
            // 3、解析request
            try {
                List<FileItem> list = up.parseRequest(request);
                if (list.size() > 0) {
                    for (FileItem file : list)
                        // 判断是否是普通的表单项
                        if (file.isFormField()) {
                            String fieldName = file.getFieldName();
                            // 中文乱码,此时还需要指定获取数据的编码方式
                            // String value = file.getString();
                            String value = file.getString("UTF-8");
                            System.out.println(fieldName + "=" + value);
                        } else { // 说明是一个文件
                            // 获取文件本身的名称
                            String fileName = file.getName();
                            System.out.println(file.getFieldName());
                            // 处理文件名称
                            fileName = fileName.substring(fileName.lastIndexOf("\") + 1);
                            System.out.println("old Name : " + fileName);
                            // 修改名称
                            String extName = fileName.substring(fileName.lastIndexOf("."));
                            String newName = UUID.randomUUID().toString().replace("-", "") + extName;
                            // 保存新的名称,并写出到新文件中
                            file.write(new File(path + "/" + newName));
                            System.out.println("文件名是: " + fileName);
                            System.out.println("文件大小是: " + file.getSize());
                            file.delete();
                        }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    Upload

      2、文件下载

        前台:

          设置download属性

        后台实现下载:

          

    public class DownloadServlet extends HttpServlet {
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            // 设置请求 响应编码
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
    
            // 获取文件名
            String fileName = req.getParameter("fileName");
            // 判断文件名是否为空
            if (fileName == null || fileName.length() < 1) {
                PrintWriter out = resp.getWriter();
                out.write("<h1>请输入文件名</h1><a href='download.html'>返回</a>");
                out.close();
                return;
            }
            // 获取存放文件的目录
            String path = getServletContext().getRealPath("/upload/");
            // 获取文件的路径
            String filePath = path + fileName;
            // 通过路径获得file对象
            File file = new File(filePath);
            // 判断file对象是不是存在而且是文件
            if (file.exists() && file.isFile()) {
                // 下载
                // 1、设置响应类型
                resp.setContentType("application/x-msdownload");
                // 2、设置下载的弹出框信息
                resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                // 3、获取字节输入流
                InputStream is=new FileInputStream(filePath);
                // 3、获取字节输出流
                ServletOutputStream out=resp.getOutputStream();
                byte[] bs=new byte[1024];
                int len=0;
                while ((len=is.read(bs))!=-1) {
                    out.write(bs,0,len);
                }
                out.close();
                is.close();
            } else {
                PrintWriter out = resp.getWriter();
                out.write("<h1>文件不存在</h1><a href='download.html'>返回</a>");
                out.close();
            }
        }
    }
  • 相关阅读:
    orale数据库的SQL查询
    pl/sql 过程 函数(写一个过程,输入部门编号,在控制台打印这个部门的名称,总人数,平均工资(基本工资+奖金))
    游标练习
    oracle 中使用 pl/sql代码块
    oracle 中怎样实现分页和去处重复
    小米的登陆页面
    tomcat建立双向https安全连接
    简单标签处理过程
    java反射机制
    tomcat配置加密的连接器https
  • 原文地址:https://www.cnblogs.com/dhome/p/9557536.html
Copyright © 2011-2022 走看看