/********************** private mothed start: **************************/        ////写log(此方法本应该synchronized,但synchronized后很多日志并没有记录进LOG,出现丢失,所以就拿掉了)
        private void printLog(String s)
        {
            log.print(DateFormat.getDateTimeInstance().format(new Date())+" ---- ");
            log.print(clientIP+":"+clientPort+" ("+clientName+") ");
            log.print(s);
            log.println(" (ConnectionID:"+ID+")");
            log.flush();
        }
        ////写出错log(此方法本应该synchronized,但synchronized后很多日志并没有记录进LOG,出现丢失,所以就拿掉了)
        private void printErrorLog(String s)
        {
            log.print("ERROR: "+DateFormat.getDateTimeInstance().format(new Date())+" ---- ");
            log.print(clientIP+":"+clientPort+" ("+clientName+") ");
            log.print(s);
            log.println(" (ConnectionID:"+ID+")");
            log.flush();
        }        
        ////读取请求信息,以空行表示结尾("\n\n")
        private String getRequestString() throws IOException
        {
            if (in.ready())
            {
                StringBuffer sb = new StringBuffer(500);
                String str = in.readLine();
                while(str!=null && !str.equals(""))
                {
                    sb.append(str+"\n");
                    str = in.readLine();
                }
                return sb.toString();
            }
            else return null;
        }        /************************* private method end ************************/

解决方案 »

  1.   

    /************************* protected method start: *******************/        /**执行GET*/
            protected void doGet()
              throws IOException
            {
                sendFile(getRequestFileName());
            }
            /**验证请求文件路径是否合法(是否超出rootPath范围)
            * @param path 相对路径*/
            protected boolean isAllowAccess(String path) throws IOException
            {
                return getAbsolutePath(path).indexOf(new File(rootPath).getCanonicalPath()) >= 0;
            }
            /**发送文件*/
            protected void sendFile(String fileName)
              throws IOException
            {
                if (!isAllowAccess(fileName))
                {
                    //超出rootPath范围,不允许访问
                    printLog(getRequestMethod()+" "+fileName+"  failed : 403 Forbidden!"); //写log
                    sendError(FORBIDDEN);
                }
                else
                {
                    String fileFullPath = getAbsolutePath(fileName);                if (fileName==null || fileName.charAt(0)!='/')  //请求文件名为null或第一个字符不是"/"
                    {
                        printLog(getRequestMethod()+" "+fileName+"  failed : 400 Bad Request!"); //写log
                        sendError(BAD_REQUEST);
                    }
                    //如果fileName以"/"结尾,则列出indexFiles中的文件
                    else if (fileName.endsWith("/"))
                    {
                        printLog(getRequestMethod()+" "+fileName); //写log                    sendIndexFile(fileName.substring(0, fileName.lastIndexOf('/')));
                    }
                    else
                    {
                        try
                        {
                            fin = new BufferedInputStream(new FileInputStream(fileFullPath));
                            int finLength = fin.available();
                            //如果finLength<0,相当于文件未找到,所以仍旧抛出FileNotFoundException
                            if (finLength < 0)  throw new FileNotFoundException();
                            else
                            {
                                printLog(getRequestMethod()+" "+fileName); //写log
                                out.println("HTTP/1.1 200 OK");
                                out.println("Server: Simple Web Server");
                                out.println("Date: "+DateFormat.getDateTimeInstance().format(new Date()));
                                out.println("Content-Type: "+new File(fileFullPath).toURL().openConnection().getContentType());
                                out.println("Accept-Ranges: bytes");
                                out.println("Content-Length: "+finLength);
                                out.println();
                                int b;
                                while ((b=fin.read()) != -1)  out.write(b);
                            }
                        }
                        catch (FileNotFoundException e)
                        {
                            printLog(getRequestMethod()+" "+fileName+"  failed : 404 Not Found!"); //写log                        //如果allowListFiles为true则列出未找到文件目录下的所有文件
                            if (allowListFiles)  listFiles(fileName.substring(0, fileName.lastIndexOf('/')));
                            else sendError(NOT_FOUND);
                        }
                    }
                }
            }
            /**寻找并发送indexFiles列表里的文件
            * @param dir 目录相对路径(结尾没有"/")*/
            protected void sendIndexFile(String dir) throws IOException
            {
                String index = null;
                //取得dir的绝对路径
                String path = getAbsolutePath(dir);
                //在dir目录下检索第一个存在的index文件            for (int i=0; i<indexFiles.length; i++)
                {
                    if (new File(path+File.separator+indexFiles[i]).exists())
                    {
                        index = path+File.separator+indexFiles[i];
                        break;
                    }
                }            if (index != null)
                {
                    try
                    {
                        fin = new BufferedInputStream(new FileInputStream(index));
                        int finLength = fin.available();
                        if (finLength >= 0)
                        {
                            printLog(getRequestMethod()+" "+dir+"/"+index.substring(index.lastIndexOf(File.separator)+1)+"  OK : 200"); //写log                        out.println("HTTP/1.1 200 OK");
                            out.println("Server: Simple Web Server");
                            out.println("Date: "+DateFormat.getDateTimeInstance().format(new Date()));
                            out.println("Content-Type: text/html");
                            out.println("Accept-Ranges: bytes");
                            out.println("Content-Length: "+finLength);
                            out.println();
                            int b;
                            while ((b=fin.read()) != -1)  out.write(b);
                        }
                    }
                    catch (FileNotFoundException e)
                    {
                        printLog(getRequestMethod()+" "+dir+"/"+index.substring(index.lastIndexOf(File.separator)+1)+"  failed : 404 Not Found!"); //写log                    //如果allowListFiles为true则列出未找到文件目录下的所有文件
                        if (allowListFiles)  listFiles(dir);
                        else sendError(NOT_FOUND);
                    }
                }
            }
      

  2.   


            /**发送错误*/
            protected void sendError(String errorType)
              throws IOException
            {
                //NOT_FOUND
                if (errorType.equals(NOT_FOUND))
                {
                    out.println("HTTP/1.1 404 Not Found");
                    out.println("Server: Simple Web Server");
                    out.println("Date: "+DateFormat.getDateTimeInstance().format(new Date()));
                    out.println("Content-Type: text/html");
                    try
                    {
                        String errorFile = properties.getProperty(NOT_FOUND);
                        if (errorFile == null)  throw new FileNotFoundException();
                        else
                        {
                            fin = new BufferedInputStream(new FileInputStream(errorFile));
                            int finLength = fin.available();
                            //如果finLength为0,相当于文件未找到,所以仍旧抛出FileNotFoundException
                            if (finLength <= 0)  throw new FileNotFoundException();
                            else
                            {
                                out.println("Accept-Ranges: bytes");
                                out.println("Content-Length: "+finLength);
                                out.println();
                                int b;
                                while ((b=fin.read()) != -1)  out.write(b);
                            }
                        }
                    }
                    catch (FileNotFoundException e)
                    {
                        out.println("Content-Length: "+default_NOT_FOUND.getBytes().length);
                        out.println();
                        out.println(default_NOT_FOUND);
                    }
                }
                //BAD_REQUEST
                else if (errorType.equals(BAD_REQUEST))
                {
                    out.println("HTTP/1.1 400 Bad Request");
                    out.println("Server: Simple Web Server");
                    out.println("Date: "+DateFormat.getDateTimeInstance().format(new Date()));
                    out.println("Content-Type: text/html");
                    try
                    {
                        String errorFile = properties.getProperty(BAD_REQUEST);
                        if (errorFile == null)  throw new FileNotFoundException();
                        else
                        {
                            fin = new BufferedInputStream(new FileInputStream(errorFile));
                            int finLength = fin.available();
                            //如果finLength为0,相当于文件未找到,所以仍旧抛出FileNotFoundException
                            if (finLength <= 0)  throw new FileNotFoundException();
                            else
                            {
                                out.println("Accept-Ranges: bytes");
                                out.println("Content-Length: "+finLength);
                                out.println();
                                int b;
                                while ((b=fin.read()) != -1)  out.write(b);
                            }
                        }
                    }
                    catch (FileNotFoundException e)
                    {
                        out.println("Content-Length: "+default_BAD_REQUEST.getBytes().length);
                        out.println();
                        out.println(default_BAD_REQUEST);
                    }
                }
                //FORBIDDEN
                else if (errorType.equals(FORBIDDEN))
                {
                    out.println("HTTP/1.1 400 Bad Request");
                    out.println("Server: Simple Web Server");
                    out.println("Date: "+DateFormat.getDateTimeInstance().format(new Date()));
                    out.println("Content-Type: text/html");
                    try
                    {
                        String errorFile = properties.getProperty(FORBIDDEN);
                        if (errorFile == null)  throw new FileNotFoundException();
                        else
                        {
                            fin = new BufferedInputStream(new FileInputStream(errorFile));
                            int finLength = fin.available();
                            //如果finLength为0,相当于文件未找到,所以仍旧抛出FileNotFoundException
                            if (finLength <= 0)  throw new FileNotFoundException();
                            else
                            {
                                out.println("Accept-Ranges: bytes");
                                out.println("Content-Length: "+finLength);
                                out.println();
                                int b;
                                while ((b=fin.read()) != -1)  out.write(b);
                            }
                        }
                    }
                    catch (FileNotFoundException e)
                    {
                        out.println("Content-Length: "+default_FORBIDDEN.getBytes().length);
                        out.println();
                        out.println(default_FORBIDDEN);
                    }
                }
            }        /************************* protected method end **********************/