day32 文件上传 提取代码 订单展示

2017-10-29  本文已影响0人  路人爱早茶

----------文件上传

----------html上传时候会分文件块自动,但接受需要手动(接受并写入服务器)
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
            //接受上传文件
            //1、创建磁盘文件项工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2、创建文件上传的核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            
            //3、解析request---获得文件项集合
            List<FileItem> parseRequest = upload.parseRequest(request);

            //4、遍历文件项集合
            for(FileItem item : parseRequest){
                //5、判断普通表单项/文件上传项
                boolean formField = item.isFormField();//是否是一个普通表单项
                if(formField){
                    //普通表单项
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    System.out.println(fieldName+":"+fieldValue);
                }else{
                    //文件上传项
                    //获得上传文件的名称
                    String fileName = item.getName();
                    //获得上传文件的内容
                    InputStream in = item.getInputStream();
                    //将in中的数据拷贝服务器上
                    String path = this.getServletContext().getRealPath("upload");
                    OutputStream out = new FileOutputStream(path+"/"+fileName);
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while((len=in.read(buffer))>0){
                        out.write(buffer, 0, len);
                    }
                    in.close();
                    out.close();
                }
            }
                } catch (FileUploadException e) {
            e.printStackTrace();
        }
            }
----------------------api运用
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            //1、创建磁盘文件项工厂
            //作用:设置缓存文件的大小  设置临时文件存储的位置
            String path_temp = this.getServletContext().getRealPath("temp");
            //DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024, new File(path_temp));
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024*1024);
            factory.setRepository(new File(path_temp));
            //2、创建文件上传的核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置上传文件的名称的编码
            upload.setHeaderEncoding("UTF-8");
            //ServletFileUpload的API
            boolean multipartContent = upload.isMultipartContent(request);//判断表单是否是文件上传的表单
            if(multipartContent){
                //是文件上传的表单
                //***解析request获得文件项集合
                List<FileItem> parseRequest = upload.parseRequest(request);
                if(parseRequest!=null){
                    for(FileItem item : parseRequest){
                        //判断是不是一个普通表单项
                        boolean formField = item.isFormField();
                        if(formField){
                            //username=zhangsan
                            String fieldName = item.getFieldName();
                            String fieldValue = item.getString("UTF-8");//对普通表单项的内容进行编码
                            
                            System.out.println(fieldName+"----"+fieldValue);
                            
                            //当表单是enctype="multipart/form-data"时 request.getParameter相关的方法
                            //String parameter = request.getParameter("username");
                            
                        }else{
                            //文件上传项
                            //文件的名
                            String fileName = item.getName();
                            //获得上传文件的内容
                            InputStream in = item.getInputStream();
                            String path_store = this.getServletContext().getRealPath("upload");
                            OutputStream out = new FileOutputStream(path_store+"/"+fileName);
                            IOUtils.copy(in, out);
                            in.close();
                            out.close();
                            
                            //删除临时文件
                            item.delete();                                           }
            }               }
            }else{
                //不是文件上传表单
                //使用原始的表单数据的获得方式 request.getParameter();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }}
Paste_Image.png Paste_Image.png
<body>
    <form action="/WEB32/fileuploadServlet2" method="post" enctype="multipart/form-data">
        <input type="text" name="username"><br>
        <input type="file" name="filename"><br>
        <input type="submit" value="上传文件">
    </form>
</body>

---------用户注销要记得把自动登录的cookie同样删掉

    //用户注销
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException{
        HttpSession session = request.getSession();
        //从session中将user删除
        session.removeAttribute("user");
        
        //将存储在客户端的cookie删除掉
        Cookie cookie_username = new Cookie("cookie_username","");
        cookie_username.setMaxAge(0);
        //创建存储密码的cookie
        Cookie cookie_password = new Cookie("cookie_password","");
        cookie_password.setMaxAge(0);
        response.addCookie(cookie_username);
        response.addCookie(cookie_password);
        response.sendRedirect(request.getContextPath()+"/login.jsp");           }   

------------------提取代码权限控制

---------xml--将需要过滤的都写在同一个虚拟目录下
    <!-- 用防护登录权限配置在自动登录的后面 -->
    <!-- <filter>
        <filter-name>UserLoginPrivilegeFilter</filter-name>
        <filter-class>com.itheima.web.filter.UserLoginPrivilegeFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>UserLoginPrivilegeFilter</filter-name>
        <url-pattern>/privilege/*</url-pattern>
    </filter-mapping> -->
    
-------filter
public class UserLoginPrivilegeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 校验用户是否登录----校验session是否存在user对象
        HttpSession session = req.getSession();
        // 判断用户是否已经登录 未登录下面代码不执行
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 没有登录
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
            return;
        }
        chain.doFilter(req, resp);  }

--------------我的订单集合

Paste_Image.png Paste_Image.png
-------两表联查(一对一)
public List<Map<String, Object>> findAllOrderItemByOid(String oid) throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select i.count,i.subtotal,p.pimage,p.pname,p.shop_price from orderitem i,product p where i.pid=p.pid and i.oid=?";
        List<Map<String, Object>> mapList = runner.query(sql, new MapListHandler(), oid);
        return mapList;
    }
------------------servlet
// 获得我的订单
    public void myOrders(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        ProductService service = new ProductService();
        // 查询该用户的所有的订单信息(单表查询orders表)
        // 集合中的每一个Order对象的数据是不完整的 缺少List<OrderItem> orderItems数据
        List<Order> orderList = service.findAllOrders(user.getUid());
        // 循环所有的订单 为每个订单填充订单项集合信息
        if (orderList != null) {
            for (Order order : orderList) {
                // 获得每一个订单的oid
                String oid = order.getOid();
                // 查询该订单的所有的订单项---mapList封装的是多个订单项和该订单项中的商品的信息
                List<Map<String, Object>> mapList = service.findAllOrderItemByOid(oid);
                // 将mapList转换成List<OrderItem> orderItems
                for (Map<String, Object> map : mapList) {

                    try {
                        // 从map中取出count subtotal 封装到OrderItem中
                        OrderItem item = new OrderItem();
                        // item.setCount(Integer.parseInt(map.get("count").toString()));
                        BeanUtils.populate(item, map);
                        // 从map中取出pimage pname shop_price 封装到Product中
                        Product product = new Product();
                        BeanUtils.populate(product, map);
                        // 将product封装到OrderItem
                        item.setProduct(product);
                        // 将orderitem封装到order中的orderItemList中
                        order.getOrderItems().add(item);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }   }   }   }
        // orderList封装完整了
        request.setAttribute("orderList", orderList);
        request.getRequestDispatcher("/order_list.jsp").forward(request, response);
    }
上一篇下一篇

猜你喜欢

热点阅读