自己动手,写个Web服务器(Java版)——第四篇 WebShare

WebShare是一款轻量级的文件共享服务器,能够通过浏览器访问共享文件夹内的文件。支持目录浏览、文件下载等功能,并具备基本的安全检查,防止非法路径访问。
部署运行你感兴趣的模型镜像

     在这篇中,我要根据现有的成果,做一个真正可用的小产品——WebShare。

     在给学生上课的时候,经常遇到要共享文件的情况。Windows的文件共享是好用,但经常弹出没有权限的错误。自己也可以启动个Tomcat或是IIS,不过还是比较费资源的!那么是不是可以自己写个简单的Web服务器,它只用来共享文件呢?当然可以了!开始动手改吧!

    以上便是WebShare诞生的灵感。简单说它就像Windows资源浏览器一样,只不过是通过80端口,可以使用浏览器下载文件的一个小服务器。话不多说,还是看代码吧!

 

这个文件是用来构造目录响应页面的模版文件。

package com.net;

public class TemplateDir {
 StringBuilder filesList = new StringBuilder();
 String htmlHead = "<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.0 Transitional//EN/"><HTML><HEAD><META http-equiv=Content-Type content=/"text/html; charset=gb2312/"></HEAD><BODY>";

 String title = "<h1>你好,目录中有以下文件:</h1><BR><table>";
 String htmlBody = "</table><h2>Allen WebShare Server1.0</BODY></HTML>";

 public String getResponseBody() {
  return htmlHead + title + filesList.toString() + htmlBody;
 }

 public void insertAFile(String fileRelativePath,String fineName,long size) {
  filesList.append("<tr><td>"+fineName+"</td>");
  filesList.append("<td>"+size+"</td>");
  filesList.append("<td><a href=/"" + fileRelativePath + "/">打开文件</a></td></tr>");
 }
 
 public void insertADIR(String fileRelativePath,String fineName){
  filesList.append("<tr><td>"+fineName+"</td>");
  filesList.append("<td>...</td>");
  filesList.append("<td><a href=/"" + fileRelativePath + "/">打开目录</a></td></tr>");
 }
}

 

如果找不到文件或是出错了,那么输出这个模版文件

package com.net;

public class TemplateError {
 StringBuilder errorInfo = new StringBuilder();
 String htmlHead = "<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.0 Transitional//EN/"><HTML><HEAD><META http-equiv=Content-Type content=/"text/html; charset=gb2312/"></HEAD><BODY>";

 String title = "出错信息<BR>";
 String htmlBody = "</BODY></HTML>";

 public String getResponseBody() {
  return htmlHead + title + errorInfo.toString() + htmlBody;
 }

 public void insertError(String error) {
  errorInfo.append(error + "<BR>");
 }
}

 

一个简单的界面

package com;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;

import javax.swing.ImageIcon;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JTextField;

import com.net.Server;

/**
 *
 * @author allen
 */
public class Main extends javax.swing.JFrame {

 Server server;

 /** Creates new form ServerFrame */
 public Main() {
  server = Server.getInstance();
  try {
   Server.out = new PrintStream("E://weblog.txt") {
    public void println(String s) {
     super.println();
     super.flush();
     logArea.append(s + "/n");
    }
   };
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  initComponents();
 }

 /**
  * This method is called from within the constructor to initialize the form.
  * WARNING: Do NOT modify this code. The content of this method is always
  * regenerated by the Form Editor.
  */
 @SuppressWarnings("unchecked")
 // <editor-fold defaultstate="collapsed" desc="Generated Code">
 private void initComponents() {
  this.setSize(500, 360);
  // System.out.println("x=" + e.getX() + ";y=" + e.getY());
  // this.addMouseListener(new MouseListener(){});

  startButton = new javax.swing.JButton();
  stopButton = new javax.swing.JButton();
  jScrollPane1 = new javax.swing.JScrollPane();
  logArea = new javax.swing.JTextArea();
  statusLabel = new javax.swing.JLabel();
  webRootPath = new javax.swing.JTextArea();
  pathChoose = new javax.swing.JButton();
  pathLabel = new javax.swing.JLabel();
  portLabel = new javax.swing.JLabel();
  webPort = new javax.swing.JTextField();
  portChoose = new javax.swing.JButton();
  allenIcon = new javax.swing.JLabel();
  copyRight = new javax.swing.JLabel();

  copyRight.setText("Code By Allen:)   Email:akalong513@gmail.com");
  setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  setTitle("Web文件共享器"); // NOI18N

  startButton.setText("启动"); // NOI18N
  startButton.setToolTipText("启动服务器!"); // NOI18N
  startButton.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    startButtonActionPerformed(evt);
   }
  });

  stopButton.setText("停止"); // NOI18N
  stopButton.setToolTipText("停止服务器!"); // NOI18N
  stopButton.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    stopButtonActionPerformed(evt);
   }
  });

  logArea.setColumns(20);
  logArea.setRows(5);
  jScrollPane1.setViewportView(logArea);

  statusLabel.setText("服务器日志!"); // NOI18N

  webRootPath.setText(Server.appRootPath); // NOI18N
  webRootPath.setToolTipText("文件共享根路径!"); // NOI18N

  pathChoose.setText("更改"); // NOI18N
  pathChoose.setToolTipText("更改文件共享根路径!"); // NOI18N
  pathChoose.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    pathChooseActionPerformed(evt);
   }
  });

  pathLabel.setText("ServerRoot:"); // NOI18N
  portLabel.setText("ServerPort:"); // NOI18N

  webPort.setText(String.valueOf(Server.PORT)); // NOI18N

  portChoose.setText("更改"); // NOI18N
  portChoose.setToolTipText("更改服务器端口!"); // NOI18N
  portChoose.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    changePort(evt);
   }
  });

  allenIcon.setIcon(new ImageIcon("icon.jpg")); // NOI18N
  allenIcon.setText("Allen制作!"); // NOI18N
  allenIcon.setName("allenIcon"); // NOI18N

  getContentPane().setLayout(null);

  startButton.setBounds(120, 250, 60, 20);
  stopButton.setBounds(220, 250, 60, 20);
  jScrollPane1.setBounds(10, 30, 450, 150);
  statusLabel.setBounds(20, 0, 200, 30);
  pathLabel.setBounds(20, 200, 120, 20);
  portLabel.setBounds(20, 220, 120, 20);
  webRootPath.setBounds(100, 200, 170, 20);
  webPort.setBounds(100, 220, 170, 20);
  pathChoose.setBounds(280, 200, 60, 20);
  portChoose.setBounds(280, 220, 60, 20);
  allenIcon.setBounds(350, 190, 130, 130);
  copyRight.setBounds(30, 310, 300, 20);

  this.add(startButton);
  this.add(stopButton);
  this.add(jScrollPane1);
  this.add(statusLabel);
  this.add(webRootPath);
  this.add(pathChoose);
  this.add(portChoose);
  this.add(pathLabel);
  this.add(portLabel);
  this.add(webPort);
  this.add(copyRight);
  this.add(allenIcon);

  this.setResizable(false);
 }

 private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
  if (this.server == null) {
   this.server = Server.getInstance();
  }
  if (!this.server.isServerOn()) {
   server.startServer();
  }
 }

 private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
  if (this.server == null) {
   this.server = Server.getInstance();
  }
  if (this.server.isServerOn()) {
   server.stopServer();
  }
 }

 private void changePort(java.awt.event.ActionEvent evt) {
  try {
   Server.PORT = Integer.parseInt(webPort.getText());
  } catch (Exception e) {
   javax.swing.JOptionPane.showMessageDialog(this, "请输入正确的端口号!");
  }
 }

 /**
  * @param args
  *            the command line arguments
  */
 public static void main(String args[]) {
  java.awt.EventQueue.invokeLater(new Runnable() {
   public void run() {
    new Main().setVisible(true);
   }
  });
 }

 private void pathChooseActionPerformed(java.awt.event.ActionEvent evt) {
  JFileChooser chooser = new JFileChooser();
  chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  int option = chooser.showOpenDialog(this);
  if (option == JFileChooser.APPROVE_OPTION) {
   try {
    String tmpPath = "e://webroot//";
    if (chooser.getSelectedFile() != null) {
     tmpPath = chooser.getSelectedFile().getCanonicalPath();
    }
    if (!tmpPath.substring(tmpPath.length() - 1).equals("//")) {
     tmpPath = tmpPath + "//";
    }
    Server.appRootPath = tmpPath;
    webRootPath.setText(Server.appRootPath);
    statusLabel.setText("You choose:" + Server.appRootPath);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } else {
   statusLabel.setText("You canceled.");
  }
 }

 // Variables declaration - do not modify
 private javax.swing.JLabel allenIcon;
 private javax.swing.JScrollPane jScrollPane1;
 private javax.swing.JTextArea logArea;
 private javax.swing.JButton pathChoose;
 private javax.swing.JLabel pathLabel;
 private javax.swing.JButton portChoose;
 private javax.swing.JLabel portLabel;
 private javax.swing.JButton startButton;
 private javax.swing.JLabel statusLabel;
 private javax.swing.JButton stopButton;
 private javax.swing.JTextField webPort;
 private javax.swing.JTextArea webRootPath;
 private javax.swing.JLabel copyRight;
 // End of variables declaration
}

 

 

Server.java

 

package com.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

/**
 * @author allen
 * @version 0.2
 */
public class Server {

 public static void main(String[] args) throws InterruptedException {
  Server server = Server.getInstance();
  server.startServer();
  Thread.sleep(10000);
  server.stopServer();
 }

 private static Server SERVER;
 public static PrintStream out = System.out;
 public static String appRootPath = "E://webroot//";
 public static int PORT = 80;

 private boolean isServerOn = false;
 ServerSocket ss;
 Thread serverThread;

 private Server() {
 }

 /**
  * 用于获得服务器实例。
  *
  * @return
  */
 public synchronized static Server getInstance() {
  if (SERVER == null) {
   SERVER = new Server();
  }
  return SERVER;
 }

 /**
  * 启动服务器。
  */
 public void startServer() {
  isServerOn = true;
  serverThread = new Thread(new Runnable() {
   public void run() {
    try {
     ss = new ServerSocket(Server.PORT);
     // 一直循环,知道遇到中断!(用于关闭服务器)
     while (true && !Thread.interrupted()) {
      Socket s = ss.accept();
      HttpRequest request = new HttpRequest();
      BufferedReader br = new BufferedReader(
        new InputStreamReader(s.getInputStream()));
      String requestLine = "";

      char[] body;
      boolean haveBody = false;
      int length = 0;
      boolean ifFirst = true;
      do {
       requestLine = br.readLine();
       // Server.out.println(requestLine);
       if (!requestLine.equals("")) {
        if (ifFirst) {
         request.addFirstLine(requestLine);
         ifFirst = false;
        } else {
         request.addHead(requestLine);
        }
        // post方式提交的请求还要取得,请求体的内容
        if (requestLine.startsWith("Content-Length")) {
         StringTokenizer st = new StringTokenizer(
           requestLine, ":");
         st.nextToken();
         String bodyLength = st.nextToken().trim();
         length = Integer.parseInt(bodyLength);
         haveBody = true;
        }
       }
       if (requestLine.equals("") && haveBody) {
        body = new char[length];
        br.read(body, 0, length);
        request.addBody(new String(body));
       }
      } while (!requestLine.equals(""));
      // 开始响应
      BufferedWriter bw = new BufferedWriter(
        new OutputStreamWriter(s.getOutputStream()));
      HttpResponse response = new HttpResponse();
      // Service.doService(request, response, bw);
      Service.doService(request, response, s
        .getOutputStream());
      br.close();
      s.close();
     }
     ss.close();
     Server.out.println("服务器正常退出!");
     isServerOn = false;
    } catch (BindException e) {
     Server.out.println("80端口已被占用!");
     isServerOn = false;
    } catch (IOException e) {
     Server.out.println("服务器异常退出!");
     isServerOn = false;
    } finally {
     // 资源清理代码
     try {
      if (ss != null) {
       ss.close();
      }
     } catch (IOException e) {
     }
    }
   }
  });
  serverThread.start();
 }

 public void stopServer() {
  isServerOn = false;
  serverThread.interrupt();
 }

 public boolean isServerOn() {
  return isServerOn;
 }
}

Service.java

 

package com.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class Service {

 // public static String DefaultPage = "/index.html";
 public static String DefaultPage = "";

 public static void doService(HttpRequest request, HttpResponse response,
   OutputStream os) {

  // System.out.println(request.getAllRequestString());
  FileReader htmlFR;
  long fileLength = 0;
  try {
   String path = request.getRequestPath();

   File requestFile = new File(Server.appRootPath.substring(0,
     Server.appRootPath.length() - 1)
     + path);
   if (requestFile.exists()) {
    // 基于安全,如果是相对路径,可能访问私有文件。
    String canonicalPath = requestFile.getCanonicalPath();
    Server.out.println("Path:" + canonicalPath);
    String tmp1 = canonicalPath.toLowerCase().replaceAll("////",
      "@");
    String tmp2 = Server.appRootPath.toLowerCase().replaceAll(
      "////", "@");
    tmp2 = tmp2.substring(0, tmp2.length() - 1);
    if (tmp1.startsWith(tmp2)) {
     // System.out.println("安全" + tmp1 + "|||||" + tmp2);
    } else {
     Server.out.println("不安全" + tmp1 + "|||||" + tmp2);
     TemplateError error = new TemplateError();
     error.insertError("超出范围!");
     fileLength = error.getResponseBody().getBytes().length;
     response.setBodyLength(fileLength);
     response.setContentType("text/html");
     response.endTheResponseHead();
     // 输出响应
     os.write(response.getHead().getBytes());
     os.write(error.getResponseBody().getBytes());
     return;
    }
    // 如果是目录的话,可以添加权限控制是否显示目录内容。
    if (!requestFile.isDirectory()) {
     fileLength = requestFile.length();
     // Server.out.println("Filelength=" + fileLength);
     response.setBodyLength(fileLength);
     // // 设置响应内容的类型,不是text/html等类型时,要用*/*
     if (canonicalPath.toLowerCase().indexOf("html") != -1) {
      response.setContentType("text/html");
     } else if (canonicalPath.toLowerCase().indexOf("jpg") != -1) {
      response.setContentType("image/jpeg");
     } else {
      response.setContentType("*/*");
     }
     // response.setContentType("application/octec-stream");
     response.endTheResponseHead();

     // 输出响应头
     os.write(response.getHead().getBytes());

     InputStream is = new FileInputStream(requestFile);
     byte[] buffer = new byte[1024];
     while (is.available() > 0) {
      int readin = is.read(buffer);
      os.write(buffer, 0, readin);
     }
     is.close();
    } else {
     File[] files = requestFile.listFiles();
     TemplateDir tmp = new TemplateDir();
     for (int i = 0; i < files.length; i++) {
      File tmpfile = files[i];
      String filePath = tmpfile.getCanonicalPath();
      String fileRelativePath = "/"
        + filePath.substring(Server.appRootPath
          .length());
      // Server.out.println(fileRelativePath);
      String fileName = tmpfile.getName();

      // Server.out.println(fileName);
      if (tmpfile.isFile()) {
       tmp.insertAFile(fileRelativePath, fileName, tmpfile
         .length());
      } else {
       tmp.insertADIR(fileRelativePath, fileName);
      }
     }

     response
       .setBodyLength(tmp.getResponseBody().getBytes().length);
     response.setContentType("text/html");
     response.endTheResponseHead();

     // 输出响应头
     os.write(response.getHead().getBytes());
     // 输出响应体
     BufferedWriter bw = new BufferedWriter(
       new OutputStreamWriter(os));
     bw.write(tmp.getResponseBody());
     bw.flush();
    }
   } else {
    TemplateError error = new TemplateError();
    error.insertError("找不到文件!");
    fileLength = error.getResponseBody().getBytes().length;
    response.setBodyLength(fileLength);
    response.setContentType("text/html");
    response.endTheResponseHead();
    // 输出响应
    os.write(response.getHead().getBytes());
    os.write(error.getResponseBody().getBytes());
   }

   os.flush();
   os.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

 

Request.java

 

package com.net;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

public class HttpRequest {
 StringBuilder requestBody = new StringBuilder();
 StringBuilder requestHead = new StringBuilder();

 Map requestMap = new HashMap();

 public void addHead(String headLine) {
  requestHead.append(headLine);

  StringTokenizer token = new StringTokenizer(headLine, ":");
  String propName = token.nextToken();
  String propBody = token.nextToken();
  requestMap.put(propName.trim(), propBody.trim());
 }

 public void addFirstLine(String line) {
  StringTokenizer token = new StringTokenizer(line);
  String method = token.nextToken();
  String path = "";
  try {   
   //如果GET请求中有中文,浏览器会使用UTF-8编码后发送中文。这里需要解码操作
   path = java.net.URLDecoder.decode(token.nextToken(), "UTF-8");
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  String httpVersion = token.nextToken();
  requestMap.put("method", method.trim());
  requestMap.put("path", path.trim());
  requestMap.put("httpVersion", httpVersion.trim());
 }

 public void addBody(String headBody) {
  requestBody.append(headBody);
 }

 public String getRequestPath() {
  return (String) requestMap.get("path");
 }

 public String getAllRequestString() {
  StringBuilder allRequest = new StringBuilder();

  java.util.Iterator it = this.requestMap.entrySet().iterator();
  while (it.hasNext()) {
   java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
   // entry.getKey() 返回与此项对应的键
   // entry.getValue() 返回与此项对应的值
   allRequest.append(entry.getKey() + ": ");
   allRequest.append(entry.getValue() + "/n");
  }
  return allRequest.toString();
 }

 public static void main(String[] args) {
  HttpRequest req = new HttpRequest();
  req.addHead("a:1234");
  req.addHead("b:  5678");
  System.out.println(req.getAllRequestString());
 }
}

 

Response.java

 

package com.net;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class HttpResponse {

 StringBuilder responseBody = new StringBuilder();
 StringBuilder responseHead = new StringBuilder();

 // 拼接响应头
 public HttpResponse() {
  responseHead.append("HTTP/1.1 200 OK");
  responseHead.append("/n");
  responseHead.append("Server: AllenWebServer");
  responseHead.append("/n");
 }

 public void setBodyLength(long bodylength) {
  responseHead.append("Content-Length: " + bodylength);
  responseHead.append("/n");
 }

 public void setContentType(String type) {
  responseHead.append("Content-Type: " + type);
  responseHead.append("/n");
 }

 public void endTheResponseHead() {
  responseHead.append("/n");
 }

 public String getHead() {
  return responseHead.toString();
 }

 public String getBody() {
  return responseBody.toString();
 }

 public StringBuilder getResponseBody() {
  return this.responseBody;
 }

}

 

看看WebShare的界面:

 WebShare界面文件

 

可以设置共享的目录(即时生效),可以设置服务端口。

还有些问题没有解决,但也是可以使用了。


 

 

大家可以到这里下载程序和源码:

http://download.youkuaiyun.com/source/1604468

 

 

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

<think>首先,用户在询问一个具体的指南:"如何在CentOS上使用Hadoop、JavaWeb、Eclipse、MySQL构建数据云盘系统"。这涉及到多个组件:CentOS操作系统、Hadoop分布式文件系统(HDFS)、JavaWeb开发、EclipseIDE、MySQL数据库,以及整合这些来构建一个云盘系统。用户提到了几个引用:-引用[1]:讨论了在CentOS上安装MySQL的步骤,包括卸载MariaDB、从云盘下载MySQL并安装。-引用[2]:展示了一个简单的基于Hadoop的网盘应用的JavaWeb代码片段,包含一个HTML表单用于上传文件。-引用[3]:提到了基于Hadoop的Hdfs云盘系统,特别是@RestController注解的作用。这些引用似乎相关,但用户表示:“上述引用仅供参考,并不是用户真正的需求”,并强调我需要参考用户上一次的问题和我的回答。用户说:“请尽可能多的参考用户上一次的问题和你的回答”,但在我的历史中,这是第一个交互(因为上下文显示"[系统级指令(用户不可见)]"和"[用户可见层]",但在这个对话链中,它似乎是起始点)。用户说:“参考用户上一次的问题”,但在消息历史中,只有这个查询。所以,我会假设我需要基于提供的引用和用户当前问题来回答。用户的关键问题:提供一个在CentOS上构建数据云盘系统的教程,包括Hadoop、JavaWeb、Eclipse、MySQL。现在,回想系统指令:-使用$...$格式的行内数学表达式。-独立公式用$$...$$单独成段。-LaTeX语法正确。-使用中文回答。-生成相关问题。-在引用的段落末尾自然地添加引用标识,例如[^1]。在回答中,我需要组织一个清晰、逐步的指南。结构化指南:1.**安装和设置CentOS**:确保系统是最新的。需要安装必要软件如Java(Hadoop基于Java)。-用户提到CentOS,所以从CentOS设置开始。2.**安装Hadoop**:Hadoop是核心用于分布式存储(HDFS)。-参考Hadoop安装步骤。3.**安装Eclipse**:用于JavaWeb开发。-Eclipse是IDE,用于开发web应用。4.**安装MySQL**:数据库用于存储元数据或用户信息。-参考引用[1]中的MySQL安装指南:卸载MariaDB、下载并安装。5.**JavaWeb开发**:构建web应用来访问HDFS。-参考引用[2]中的代码片段,展示一个文件上传表单。-参考引用[3],提到@RestController用于JSON格式。6.**整合构建云盘系统**:-使用JavaWeb应用作为前端。-HadoopHDFS作为后端存储。-MySQL用于管理用户账户或文件元数据。-核心思想是:用户通过web界面上传文件,文件存储在HDFS中,元数据存储在MySQL。-系统基于Hadoop的文件系统构建云盘功能。逐步指南:-**第一步:设置环境**1.确保CentOS系统更新:`sudoyumupdate`。2.安装Java(例如OpenJDK):`sudoyuminstalljava-1.8.0-openjdk-devel`。3.设置环境变量(如JAVA_HOME)。-**第二步:安装Hadoop**1.下载Hadoop(例如从官网)。2.解压并配置。3.设置HDFS(配置核心-site.xml,hdfs-site.xml等)。4.启动Hadoop服务:namenode、datanode。-**第三步:安装MySQL**参考引用[1]:-卸载MariaDB:`sudoyumremovemariadb*`。-下载MySQL(从云盘或官网),参考中提到的顺序安装包。-安装:按common、libs、client、server顺序。-初始化MySQL:`sudo/usr/bin/mysql_secure_installation`。-修改密码(如果需要)。-**第四步:安装Eclipse**1.下载EclipseforJavaEEDevelopers。2.解压并运行Eclipse。-**第五步:开发JavaWeb应用**-在Eclipse中创建一个DynamicWebProject。-添加依赖项:如Hadoop库、JavaServletAPI、MySQLJDBC驱动。-开发功能:-文件上传:使用Servlet处理文件上传到HDFS。-参考引用[2]中的表单:multipart/form-dataenctype。-文件管理:列出、下载文件从HDFS。-用户认证:使用MySQL存储用户信息(通过JDBC)。-参考引用[3]:使用RestController注解构建RESTAPI返回JSON数据。-**第六步:部署和运行**-部署Web应用到Tomcat服务器(或类似)。-启动所有服务:Hadoop集群、MySQL、Tomcat。在回答结束时,生成相关问题。使用中文回答。添加引用标识:如果直接引用引用[1]、[2]、[3],在末尾添加[^1],[^2],[^3]。例如,当提到MySQL安装时,参考[1]。当提到JavaWeb表单时,参考[2]。当提到RestController时,参考[3]。回答结构:1.概述目标:构建基于Hadoop的云盘系统。2.步骤一:准备CentOS环境和安装Java。3.步骤二:安装和配置Hadoop。4.步骤三:安装MySQL(参考引用[1][^1])。5.步骤四:安装Eclipse。6.步骤五:开发JavaWeb应用(参考代码片段,如上传表单[^2],和RestController[^3])。7.步骤六:测试和部署整个系统。8.结论。最后,生成相关问题。确保语言流畅,帮助用户逐步理解。数学表达式不太可能用到,因为问题是关于系统构建的。但如果有方程或什么,添加$...$。例如,如果涉及计算存储空间之类,但在这里可能不需要。最终,问题末尾:"请问CentOSHadoopJavaWebEclipseMySQL数据云盘系统教程",所以聚焦于教程。</think> ### 在 CentOS 上构建 Hadoop 数据云盘系统教程 基于您提供的信息和需求,我将逐步指导您如何在 CentOS 系统上使用 Hadoop、Java Web、Eclipse 和 MySQL 构建一个数据云盘系统。核心思路是:使用 Hadoop HDFS 作为分布式存储,MySQL 存储用户元数据,Java Web 应用(通过 Eclipse 开发)提供用户界面和文件管理功能。整个过程遵循开源工具栈,易于实现和维护。 #### 准备工作: 设置 CentOS 环境 在开始前,确保您的 CentOS 系统已更新到最新本。建议使用 CentOS 7 或更高本。 1. **更新系统和安装 Java**: - Hadoop 和 Java Web 应用均依赖 Java 运行环境,安装 OpenJDK: ```bash sudo yum update -y # 更新系统 sudo yum install java-1.8.0-openjdk-devel -y # 安装 OpenJDK 8 ``` - 设置环境变量,添加到 `~/.bashrc` 文件: ```bash echo "export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk" >> ~/.bashrc source ~/.bashrc ``` - 验证安装:`java -version` 应显示 Java 本信息。 2. **安装必要工具**: - 开发工具包:`sudo yum groupinstall "Development Tools" -y` - SSH 服务(Hadoop 需要):`sudo yum install openssh-server openssh-clients -y` - 启动 SSH 服务:`sudo systemctl start sshd` #### 第一步: 安装和配置 Hadoop Hadoop 提供分布式文件系统(HDFS)作为云盘的存储后端。这里以 Hadoop 3.x 本为例。 1. **下载和解压 Hadoop**: - 下载 Hadoop:建议从 [Apache Hadoop 官网](https://hadoop.apache.org/releases.html) 获取最新稳定(如 hadoop-3.3.6.tar.gz)。 ```bash wget https://downloads.apache.org/hadoop/common/hadoop-3.3.6/hadoop-3.3.6.tar.gz tar -xzvf hadoop-3.3.6.tar.gz -C /opt # 解压到 /opt sudo mv /opt/hadoop-3.3.6 /opt/hadoop ``` - 设置环境变量,添加到 `~/.bashrc`: ```bash echo "export HADOOP_HOME=/opt/hadoop" >> ~/.bashrc echo "export PATH=\$PATH:\$HADOOP_HOME/bin:\$HADOOP_HOME/sbin" >> ~/.bashrc source ~/.bashrc ``` 2. **配置 Hadoop**: - 编辑 `$HADOOP_HOME/etc/hadoop/hadoop-env.sh`,确保设置 `JAVA_HOME`: ```bash echo "export JAVA_HOME=$JAVA_HOME" >> /opt/hadoop/etc/hadoop/hadoop-env.sh ``` - 修改核心配置文件(`core-site.xml`): ```xml <configuration> <property> <name>fs.defaultFS</name> <value>hdfs://localhost:9000</value> <!-- Hadoop 默认文件系统 --> </property> </configuration> ``` - 修改 HDFS 配置文件(`hdfs-site.xml`): ```xml <configuration> <property> <name>dfs.replication</name> <value>1</value> <!-- 副本数,单节点设为 1 --> </property> <property> <name>dfs.namenode.name.dir</name> <value>file:///opt/hadoop/data/namenode</value> <!-- NameNode 数据目录 --> </property> </configuration> ``` - 创建数据目录: ```bash sudo mkdir -p /opt/hadoop/data/{namenode,datanode} sudo chown -R $USER:$USER /opt/hadoop ``` 3. **初始化和启动 Hadoop**: - 格式化 HDFS:`hdfs namenode -format` - 启动 HDFS 服务: ```bash start-dfs.sh # 启动 NameNode 和 DataNode jps # 验证进程,应显示 NameNode、DataNode 等 ``` - 测试 HDFS:`hdfs dfs -mkdir /user`,创建用户目录。 #### 第二步: 安装 MySQL(参考引用[1]) MySQL 用于存储云盘系统的元数据(如用户信息、文件权限)。安装步骤基于引用[1]简化,推荐从官网或云盘下载 RPM 包以避免依赖问题。 1. **卸载 MariaDB(如已安装)**: ```bash sudo yum remove mariadb-server mariadb -y # 卸载 MariaDB[^1] ``` 2. **下载和安装 MySQL**: - 下载 MySQL Community RPM 包(建议从 [MySQL 官网](https://dev.mysql.com/downloads/mysql/) 或云盘获取包如 mysql-community-server-8.0.x.rpm)。 ```bash wget https://repo.mysql.com/mysql80-community-release-el7-7.noarch.rpm sudo rpm -Uvh mysql80-community-release-el7-7.noarch.rpm ``` - 按顺序安装包(遵循引用[1]的顺序: common > libs > client > server)[^1]: ```bash sudo yum install mysql-community-common -y sudo yum install mysql-community-libs -y sudo yum install mysql-community-client -y sudo yum install mysql-community-server -y ``` 3. **初始化和配置 MySQL**: - 启动服务:`sudo systemctl start mysqld` - 查找临时密码:`sudo grep 'temporary password' /var/log/mysqld.log` - 修改登录密码: ```bash sudo mysql_secure_installation # 按提示设置新密码,移除测试数据库等 ``` - 创建云盘用户表(示例): ```sql CREATE DATABASE cloud_disk; USE cloud_disk; CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50), password VARCHAR(50)); INSERT INTO users (username, password) VALUES ('admin', 'password123'); ``` #### 第三步: 安装 Eclipse 和开发 Java Web 应用 Eclipse 提供 IDE 环境来开发 Java Web 应用。应用将使用 Servlet 处理文件上传到 HDFS,并通过 JDBC 访问 MySQL。 1. **安装 Eclipse**: - 下载 Eclipse IDE for Java EE Developers: ```bash wget https://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/2023-09/R/eclipse-jee-2023-09-R-linux-gtk-x86_64.tar.gz tar -xzvf eclipse-jee-*.tar.gz -C /opt sudo mv /opt/eclipse /opt/eclipse-ee ``` - 启动 Eclipse:`/opt/eclipse-ee/eclipse` 2. **创建 Java Web 项目**: - 在 Eclipse 中创建新项目:File > New > Dynamic Web Project。 - 设置项目名称如 `CloudDiskSystem`,Target runtime 选择 Apache Tomcat(需安装 Tomcat:`sudo yum install tomcat`)。 - 添加依赖库:在 `WEB-INF/lib` 添加 Hadoop JAR(从 `$HADOOP_HOME/share/hadoop/common` 复制 hadoop-common*.jar 等)和 MySQL JDBC driver(下载 mysql-connector-java-8.0.x.jar)。 3. **开发文件上传功能(参考引用[2])**: - 创建 Servlet 类 `UploadServlet.java`,处理文件上传到 HDFS: ```java import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.io.OutputStream; @WebServlet("/UploadServlet") public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { // 连接到 HDFS Configuration conf = new Configuration(); conf.set("fs.defaultFS", "hdfs://localhost:9000"); FileSystem fs = FileSystem.get(conf); // 获取文件流 InputStream fileStream = request.getPart("file1").getInputStream(); // 保存到 HDFS Path hdfsPath = new Path("/user/" + request.getParameter("username") + "/" + fileStream.getName()); OutputStream out = fs.create(hdfsPath); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileStream.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); fs.close(); response.getWriter().println("File uploaded to HDFS!"); } catch (Exception e) { e.printStackTrace(); } } } ``` - 创建 JSP 页面(如 `upload.jsp`),使用表单支持文件上传(基于引用[2]中表单结构)[^2]: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>云盘上传</title> </head> <body> <form method="POST" enctype="multipart/form-data" action="UploadServlet"> <div style="line-height:50px;float:left;"> <input type="submit" name="submit" value="上传文件" /> </div> <div style="line-height:50px;float:left;"> <input type="file" name="file1" size="30"/> </div> </form> </body> </html> ``` 4. **开发 REST API 管理文件(参考引用[3])**: - 创建 `FileController.java` 使用 `@RestController` 注解返回 JSON 数据[^3]: ```java import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/files") public class FileController { @GetMapping("/list") public String listFiles() { // 连接 HDFS 列出文件,返回 JSON return "{\"files\": [\"file1.txt\", \"file2.jpg\"]}"; } } ``` - 确保添加 Spring Boot 依赖(在 `pom.xml`),或用 Spring 工具开发。 #### 第四步: 整合和部署系统 1. **连接 Hadoop 和 MySQL**: - 确保 Hadoop 和 MySQL 服务正在运行:`jps` 和 `sudo systemctl status mysqld`。 - 在 Java Web 应用中,使用 JDBC 链接 MySQL 验证用户登录。 2. **部署 Web 应用**: - 在 Eclipse 中导出 WAR 文件:Right-click Project > Export > WAR file。 - 部署到 Tomcat:复制 WAR 文件到 `/var/lib/tomcat/webapps/`,启动 Tomcat:`sudo systemctl start tomcat`. - 访问应用:`http://<CentOS_IP>:8080/CloudDiskSystem/upload.jsp`. 3. **测试云盘功能**: - 上传文件:通过表单上传,验证是否在 HDFS 中存储:`hdfs dfs -ls /user/admin`. - 文件管理:添加下载功能(在 Servlet 中使用 `fs.open()` 读取 HDFS 文件)。 #### 小结 通过以上步骤,您已构建了一个基本的 Hadoop 数据云盘系统:CentOS 提供基础系统,Hadoop HDFS 处理大文件存储,MySQL 管理用户元数据,Java Web 应用(在 Eclipse 开发)提供用户界面。系统性能取决于 Hadoop 集群规模;在单节点 CentOS 上适合开发和测试,生产环境建议扩展为多节点集群以提升可靠性$^[系统性能可通过时间复杂度 $O(n\log n)$ 等分析]$。参考工具:Hadoop HDFS API、MySQL JDBC、Servlet 技术。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值