精华内容
下载资源
问答
  • Jsp+javaBean+mysql的网络云盘

    千次阅读 2016-05-08 15:52:06
    Jsp+javaBean+mysql的网络云盘 一文件上传:利用jspSmartUpload.jar shangchuan.jsp 上传文件 <!-- Begin extArray = new Array(".rar", ".zip",".txt"); function LimitAttach(form, file) { ...

    Jsp+javaBean+mysql的网络云盘


    一文件上传:利用jspSmartUpload.jar

    shangchuan.jsp
    <%@ page contentType="text/html; charset=gbk" language="java" import="java.sql.*" errorPage="" %>
    <%@ include file="config.jsp"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>上传文件</title>
    <SCRIPT LANGUAGE="JavaScript">
    <!-- Begin
    extArray = new Array(".rar", ".zip",".txt");
    function LimitAttach(form, file) {
    allowSubmit = false;
    if (!file)
     return;
    while (file.indexOf("\\") != -1)
    file = file.slice(file.indexOf("\\") + 1);
    ext = file.slice(file.indexOf(".")).toLowerCase();
    for (var i = 0; i < extArray.length; i++) {
    if (extArray[i] == ext) { 
    allowSubmit = true;
     break;
     }
    }
    if (allowSubmit)
     form.submit();
    else
    alert("对不起,只能上传以下格式的文件:  " 
    + (extArray.join("  ")) + "\n请重新选择符合条件的文件"
    + "再上传.");
    }
    //  End -->
    /*
    	验证大小
    */
      var isIE = /msie/i.test(navigator.userAgent) && !window.opera;          
      function fileChange(target) {      
           
        var fileSize = 0;           
        if (isIE && !target.files) {       
          var filePath = target.value;       
          var fileSystem = new ActiveXObject("Scripting.FileSystemObject");          
          var file = fileSystem.GetFile (filePath);       
          fileSize = file.Size;      
        } else {      
         fileSize = target.files[0].size;       
         }     
         var size = fileSize / 1024;      
         if(size>5000){    
          alert("附件不能大于5M");    
             
             
         }    
            
    }   
    </script>
    <link rel="stylesheet" type="text/css" href="styles.css">
    
    
      <style type="text/css">
    <!--
    body {
    	background-color:#6F00D2;
    	background-image: url(image/aaa.jpg);
    }
    
    .ww1 {
    	height: 30px;
    	width: 180px;
    }
    
    </style> 
    </head>
    
    <body>
    <div align="center">
     <h1 ><font color="#FF0066">文件上传</font></h1>  
    </div>
    <table width="810" height="241" border="1" align="center">
      <tr>
        <td align="center">
        <form method=post name=upform action="http://127.0.0.1:8080/Zhu/shangchuanb.jsp" enctype="multipart/form-data">
          <input type=file name=uploadfile οnchange="fileChange(this);"/> 
        
          <p>
          
          
          <button οnclick="LimitAttach(this.form, this.form.uploadfile.value)" style="background:  #2BA82E; padding: 7px 10px; border-radius: 4px; border: 1px solid  #2BA82E; border-image: none; color: rgb(255, 255, 255); font-weight: bold;" ><FONT  size="-3">上传</FONT></button>
           
          </p>
         
        </form></td>
      </tr>
      	
    </table>
    </body>
    </html>
    shangchuanb.jsp(限制了上传的大小为5M)
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ include file="config.jsp"%>
    
    <%@ page import="java.util.*,com.jspsmart.upload.SmartUpload"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
       
        
        <title>My JSP 'shangchuan2.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
    
      </head>
      
      <body>
       <%
       	String id = (String)session.getAttribute("user");
    	// 新建一个SmartUpload对象
    	SmartUpload su = new SmartUpload();
    	// 上传初始化
    	su.initialize(pageContext);
    	// 设定上传限制
    	// 1.限制每个上传文件的最大长度。
    	su.setMaxFileSize(5000000);
    	// 2.限制总上传数据的长度。
    	su.setTotalMaxFileSize(150000000);
    	// 3.设定允许上传的文件(通过扩展名限制)。
    	su.setAllowedFilesList("rar,zip");
    	// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。
    	su.setDeniedFilesList("exe,bat,jsp,htm,html,asp,php,com");
    	// 上传文件
    	su.upload();
    	// 将上传文件全部保存到指定目录
      
    	String cqutroot = dirPath.replace('\\', '/');
    
    	su.save(cqutroot + "zhu/"+id);
    	//su.save("zhu/"+id);
    	su.save(su.getRequest().getParameter("zhu"));
    	out.print("<script>");
    	out.print("alert('文件上传成功!');");
    	out.print("location.href='chuandi.jsp';");
    	out.print("</script>");
    %>
      </body>
    </html>
    
    上传成功后,显示上传的文件chuandi.jsp
    <%@ page language="java" contentType="text/html; charset=gbk"
    	pageEncoding="GB18030" import="java.sql.*,java.util.*,java.io.*"%>
    
    <%@include file="config.jsp"%>
    
    <%	
    		String id = (String)session.getAttribute("user");
    	String Save_Location=getServletContext().getRealPath("/")+"zhu//";
        try{
    	if (!(new java.io.File(Save_Location).isDirectory())) {//如果文件夹不存在
    	new java.io.File(Save_Location).mkdir();      //不存在 文件夹,则建立此文件夹
    	new java.io.File((Save_Location)+id+"//").mkdir();    //创建文件夹,命名为当前用户的名字
        }
    	else  {//存在excel文件夹,则直接建立此文件夹    
    	new java.io.File((Save_Location)+id+"//").mkdir();      //创建文件夹,命名为当前用户的名字
    	}
    	}catch(Exception e){
    	e.printStackTrace();        //创建文件夹失败   
    	out.print("error");
    	return;
        }
        File userBox=new File((Save_Location)+id+"//");
        File userBoxfile[]=userBox.listFiles();
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    
    		<title>欢迎使用网络硬盘</title>
    		<meta http-equiv="pragma" content="no-cache">
    		<meta http-equiv="cache-control" content="no-cache">
    		<meta http-equiv="expires" content="0">
    		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    		<meta http-equiv="description" content="This is my page">
    		<link rel="stylesheet" type="text/css" href="styles.css">
    		<style type="text/css">
    <!--
    body 
    {
    	background-color: #D6D6D6;
    	background-image: url(image/e.jpg);
    }
    
    .ww1 {
    	height: 30px;
    	width: 180px;
    }
    #apDiv1 {
    	position: absolute;
    	left: 657px;
    	top: 70px;
    	width: 408px;
    	height: 247px;
    	z-index: 1;
    }
    -->
    </style>
    	</head>
    <body>
    
    	
    	      
    	<h3 align="right"> <a   href="update.jsp?userName=<%=session.getAttribute("user")%>">修改密码</a> <a href="out.jsp">退出登录</a></h3>  
    
    <h1 class="headerLogo"><a title="后台管理系统" target="_blank" href="welcome.jsp"><img alt="logo" src="images/333.jpg" width="183" height="200"></img> <br /></a></h1>
    		<br />
    	<table width="825" height="204" border="1" align="center">
    		<tr>
    			<td height="26" align="left">
    				<font color="red">欢迎
    				<%=session.getAttribute("user")%>的到来!</font><font color="#0000ff">                                        </font>        
    				
    				<br>
    		    </td>
    	    </tr>
    		<tr>
    			<td height="58" align="left" valign="top"><a href="shangchuan.jsp"><img src="image/ppp.png" width="100" height="35"></a>
    				<% for(int i=0;i<userBoxfile.length;i++){%>
      <tr><td height="22">
      
      
    					<p>
    					 <img alt="logo" src="image/yasuo.png" width="50" height="43"></img>
    					       
    						<font color="#FF00FF" size="7"><%=userBoxfile[i].getName()%></font></p></td><td height="25">
    							<span style="font-size: 9pt">
    										 
    						
    																
    			a href="dowload.jsp?filename=<%=userBoxfile[i].getName()%>"><img src="image/pp.png" width="60" height="25"></a>
    										
    										
    							</span></td>
    										
    										
    										
    					<td height="25"><span style="font-size: 9pt">
    											
    		<A style="background: #2BA82E; padding: 7px 10px; border-radius: 4px; border: 2px solid #2BA82E; border-image: none; color: rgb(255, 255, 255); font-weight: bold;" 
    
    href="shanchu.jsp?action=confirm&filename=<%=userBoxfile[i].getName()%>" target=_top> <font  size="-2" color="#FFFFFF">删除</font></A> 
    											</a>
    											
    											
    											</span>
    										</td>
    				
    	  </tr>
    					<%} %>
    			</td>
    		</tr>
        </table>
    
    
    	</body>
    </html>
    
    最后项目展示:

    展开全文
  • Jsp+javaBean+mysql的网络云盘 一文件上传:利用jspSmartUpload.jar shangchuan.jsp <%@ page contentType="text/html; charset=gbk" language="java" import="java.sql.*" errorPage="" %> <%@ ...

    Jsp+javaBean+mysql的网络云盘

    一文件上传:利用jspSmartUpload.jar

    shangchuan.jsp

    <%@ page contentType="text/html; charset=gbk" language="java" import="java.sql.*" errorPage="" %>
    <%@ include file="config.jsp"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>上传文件</title>
    <SCRIPT LANGUAGE="JavaScript">
    <!-- Begin
    extArray = new Array(".rar", ".zip",".txt");
    function LimitAttach(form, file) {
    allowSubmit = false;
    if (!file)
     return;
    while (file.indexOf("\\") != -1)
    file = file.slice(file.indexOf("\\") + 1);
    ext = file.slice(file.indexOf(".")).toLowerCase();
    for (var i = 0; i < extArray.length; i++) {
    if (extArray[i] == ext) { 
    allowSubmit = true;
     break;
     }
    }
    if (allowSubmit)
     form.submit();
    else
    alert("对不起,只能上传以下格式的文件:  " 
    + (extArray.join("  ")) + "\n请重新选择符合条件的文件"
    + "再上传.");
    }
    //  End -->
    /*
    	验证大小
    */
      var isIE = /msie/i.test(navigator.userAgent) && !window.opera;          
      function fileChange(target) {      
           
        var fileSize = 0;           
        if (isIE && !target.files) {       
          var filePath = target.value;       
          var fileSystem = new ActiveXObject("Scripting.FileSystemObject");          
          var file = fileSystem.GetFile (filePath);       
          fileSize = file.Size;      
        } else {      
         fileSize = target.files[0].size;       
         }     
         var size = fileSize / 1024;      
         if(size>5000){    
          alert("附件不能大于5M");    
             
             
         }    
            
    }   
    </script>
    <link rel="stylesheet" type="text/css" href="styles.css">
    
    
      <style type="text/css">
    <!--
    body {
    	background-color:#6F00D2;
    	background-image: url(image/aaa.jpg);
    }
    
    .ww1 {
    	height: 30px;
    	width: 180px;
    }
    
    </style> 
    </head>
    
    <body>
    <div align="center">
     <h1 ><font color="#FF0066">文件上传</font></h1>  
    </div>
    <table width="810" height="241" border="1" align="center">
      <tr>
        <td align="center">
        <form method=post name=upform action="http://127.0.0.1:8080/Zhu/shangchuanb.jsp" enctype="multipart/form-data">
          <input type=file name=uploadfile onchange="fileChange(this);"/> 
        
          <p>
          
          
          <button onclick="LimitAttach(this.form, this.form.uploadfile.value)" style="background:  #2BA82E; padding: 7px 10px; border-radius: 4px; border: 1px solid  #2BA82E; border-image: none; color: rgb(255, 255, 255); font-weight: bold;" ><FONT  size="-3">上传</FONT></button>
           
          </p>
         
        </form></td>
      </tr>
      	
    </table>
    </body>
    </html>

    shangchuanb.jsp(限制了上传的大小为5M)
     

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ include file="config.jsp"%>
    
    <%@ page import="java.util.*,com.jspsmart.upload.SmartUpload"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
       
        
        <title>My JSP 'shangchuan2.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
    
      </head>
      
      <body>
       <%
       	String id = (String)session.getAttribute("user");
    	// 新建一个SmartUpload对象
    	SmartUpload su = new SmartUpload();
    	// 上传初始化
    	su.initialize(pageContext);
    	// 设定上传限制
    	// 1.限制每个上传文件的最大长度。
    	su.setMaxFileSize(5000000);
    	// 2.限制总上传数据的长度。
    	su.setTotalMaxFileSize(150000000);
    	// 3.设定允许上传的文件(通过扩展名限制)。
    	su.setAllowedFilesList("rar,zip");
    	// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。
    	su.setDeniedFilesList("exe,bat,jsp,htm,html,asp,php,com");
    	// 上传文件
    	su.upload();
    	// 将上传文件全部保存到指定目录
      
    	String cqutroot = dirPath.replace('\\', '/');
    
    	su.save(cqutroot + "zhu/"+id);
    	//su.save("zhu/"+id);
    	su.save(su.getRequest().getParameter("zhu"));
    	out.print("<script>");
    	out.print("alert('文件上传成功!');");
    	out.print("location.href='chuandi.jsp';");
    	out.print("</script>");
    %>
      </body>
    </html>
    

    上传成功后,显示上传的文件chuandi.jsp
     

    <%@ page language="java" contentType="text/html; charset=gbk"
    	pageEncoding="GB18030" import="java.sql.*,java.util.*,java.io.*"%>
    
    <%@include file="config.jsp"%>
    
    <%	
    		String id = (String)session.getAttribute("user");
    	String Save_Location=getServletContext().getRealPath("/")+"zhu//";
        try{
    	if (!(new java.io.File(Save_Location).isDirectory())) {//如果文件夹不存在
    	new java.io.File(Save_Location).mkdir();      //不存在 文件夹,则建立此文件夹
    	new java.io.File((Save_Location)+id+"//").mkdir();    //创建文件夹,命名为当前用户的名字
        }
    	else  {//存在excel文件夹,则直接建立此文件夹    
    	new java.io.File((Save_Location)+id+"//").mkdir();      //创建文件夹,命名为当前用户的名字
    	}
    	}catch(Exception e){
    	e.printStackTrace();        //创建文件夹失败   
    	out.print("error");
    	return;
        }
        File userBox=new File((Save_Location)+id+"//");
        File userBoxfile[]=userBox.listFiles();
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    
    		<title>欢迎使用网络硬盘</title>
    		<meta http-equiv="pragma" content="no-cache">
    		<meta http-equiv="cache-control" content="no-cache">
    		<meta http-equiv="expires" content="0">
    		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    		<meta http-equiv="description" content="This is my page">
    		<link rel="stylesheet" type="text/css" href="styles.css">
    		<style type="text/css">
    <!--
    body 
    {
    	background-color: #D6D6D6;
    	background-image: url(image/e.jpg);
    }
    
    .ww1 {
    	height: 30px;
    	width: 180px;
    }
    #apDiv1 {
    	position: absolute;
    	left: 657px;
    	top: 70px;
    	width: 408px;
    	height: 247px;
    	z-index: 1;
    }
    -->
    </style>
    	</head>
    <body>
    
    	
    	      
    	<h3 align="right"> <a   href="update.jsp?userName=<%=session.getAttribute("user")%>">修改密码</a> <a href="out.jsp">退出登录</a></h3>  
    
    <h1 class="headerLogo"><a title="后台管理系统" target="_blank" href="welcome.jsp"><img alt="logo" src="images/333.jpg" width="183" height="200"></img> <br /></a></h1>
    		<br />
    	<table width="825" height="204" border="1" align="center">
    		<tr>
    			<td height="26" align="left">
    				<font color="red">欢迎
    				<%=session.getAttribute("user")%>的到来!</font><font color="#0000ff">                                        </font>        
    				
    				<br>
    		    </td>
    	    </tr>
    		<tr>
    			<td height="58" align="left" valign="top"><a href="shangchuan.jsp"><img src="image/ppp.png" width="100" height="35"></a>
    				<% for(int i=0;i<userBoxfile.length;i++){%>
      <tr><td height="22">
      
      
    					<p>
    					 <img alt="logo" src="image/yasuo.png" width="50" height="43"></img>
    					       
    						<font color="#FF00FF" size="7"><%=userBoxfile[i].getName()%></font></p></td><td height="25">
    							<span style="font-size: 9pt">
    										 
    						
    																
    			a href="dowload.jsp?filename=<%=userBoxfile[i].getName()%>"><img src="image/pp.png" width="60" height="25"></a>
    										
    										
    							</span></td>
    										
    										
    										
    					<td height="25"><span style="font-size: 9pt">
    											
    		<A style="background: #2BA82E; padding: 7px 10px; border-radius: 4px; border: 2px solid #2BA82E; border-image: none; color: rgb(255, 255, 255); font-weight: bold;" 
    
    href="shanchu.jsp?action=confirm&filename=<%=userBoxfile[i].getName()%>" target=_top> <font  size="-2" color="#FFFFFF">删除</font></A> 
    											</a>
    											
    											
    											</span>
    										</td>
    				
    	  </tr>
    					<%} %>
    			</td>
    		</tr>
        </table>
    
    
    	</body>
    </html>
    

    最后项目展示:

     

    展开全文
  • 云盘功能web

    2019-01-18 11:14:13
    采用java servlet和jsp开发具有上传和下载的功能,设计了移动端,可删除已上传文件。
  • 云盘管理系统HDFS.rar

    2019-10-06 11:34:32
    教师可以上传资源来建设自己的课程 ,学生通过App可以观看视频 、下载学习资源、提问、评论等...后端技术:Java、Servlet、JSP 前端技术:CSS、HTML、JQUERY、AJAX 数据库:MYSQL 开发工具:eclipse、Android studio、P
  • 基于Hadoop的数据云盘的实现

    万次阅读 热门讨论 2018-11-28 17:24:42
    环境:centos6.6 Tomcat7.0 ...基于Hadoop hdfs的集群分布式系统做成的这个简单的云盘实现; 首先启动centos,打开安装好的eclipse,file--&gt;New--&gt;Dynamic Application Project 注:如果没有这...

    环境:centos6.6   Tomcat7.0  eclipse  MySQL  

    首先介绍一下这个简单网盘的功能:实现用户的注册,登录;上传、下载、删除文件;

    基于Hadoop hdfs的集群分布式系统做成的这个简单的云盘实现;

    首先启动centos,打开安装好的eclipse,file-->New-->Dynamic Application Project

    注:如果没有这个项目,安装Java EE 

       

    项目名称自己设置,一直点击下一步,最后一步时,最后一步最好勾选创建web.xml,没有勾选后面自己在WEB-INF下new一个名为web.xml的xml File

               创建后如图 

    创建后,导入Hadoop下的jar包,位于安装Hadoop文件下下的share文件中,选中后粘贴到WEB-INF下的lib文件中

    eclipse中选中所有的jar包,右键-->Build Path-->Add to build path。或者是选中项目,按alt+enter,进入界面,左侧选择java build path ,右侧libraries, add jars,

    选择你要导入的jar包ok就好啦,

    接下来就是真正开始创建了,选中java Resources,右键new-->package,创建三个package,可自己命名,我这里分别是,com.Bean, com.model, com.controller

    右键com.controller,创建上传文件的名为uploadServlet.java类文件

    package com.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    
    public class UploadServlet extends HttpServlet{
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
    		this.doPost(request,response);
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
    		request.setCharacterEncoding("utf-8");
    		File file;
    		int maxFileSize = 50 * 1024 * 1024;  //50M
    		int maxMemSize = 50 * 1024 * 1024;  //50M
    		ServletContext context = getServletContext();
    		String filePath = context.getInitParameter("file-upload");
    		System.out.println("source file path:"+filePath+"");
    		//验证上传内容的类型
    		String contentType = request.getContentType();
    		if((contentType.indexOf("multipart/form-data") >= 0)){
    			DiskFileItemFactory factory = new DiskFileItemFactory();
    			//设置内存中存储文件的最大值
    			factory.setSizeThreshold(maxMemSize);
    			//本地存储的数据大于maxMemSize
    			factory.setRepository(new File("/soft/file-directory"));
    			//创建一个新的文件上传处理程序
    			ServletFileUpload upload = new ServletFileUpload(factory);
    			//设置最大上传文件大小
    			upload.setSizeMax(maxFileSize);
    			try{
    				//解析获取新文件
    				List fileItems = upload.parseRequest(request);
    				//处理上传的文件
    				Iterator i = fileItems.iterator();
    				System.out.println("begin to upload file to tomcat server</p>");
    				while(i.hasNext()){
    					FileItem fi = (FileItem)i.next();
    					if(!fi.isFormField()){
    						//获取上传文件的参数
    						String fieldName = fi.getFieldName();
    						String fileName = fi.getName();
    						String fn = fileName.substring(fileName.lastIndexOf("/")+1);
    						System.out.println("<br>"+fn+"<br>");
    						boolean isInMemory = fi.isInMemory();
    						long sizeInBytes = fi.getSize();
    						//写入文件
    						if(fileName.lastIndexOf("/") >= 0 ){
    							file = new File(filePath,fileName.substring(fileName.lastIndexOf("/")));
    						}else{
    							file = new File(filePath,fileName.substring(fileName.lastIndexOf("/")+1));
    						}
    						fi.write(file);
    						System.out.println("upload file to tomcat server success!");
    						System.out.println("begin to upload file to hadoop hdfs</p>");
    						String name = filePath + "/"+fileName;
    						//将tomcat上的文件上传到hadoop上
    						HdfsDAO hdfs = new HdfsDAO();
    						hdfs.copyFile(name);
    						System.out.println("upload file to hadoop hdfs success!");
    						FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    						request.setAttribute("documentList", documentList);
    						System.out.println("得到list数据"+documentList);
    						request.getRequestDispatcher("index.jsp").forward(request, response);
    					}
    				}
    			}catch(Exception ex){
    				System.out.println(ex);
    			}
    		}else{
    			System.out.println("<p>No file uploaded</p>");
    		}
    	}
    }

    继续在com.controller下创建名为downloadServlet.java类文件,

    package com.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    
    public class DownloadServlet extends HttpServlet{
    	private static final long serialVersionUID = 1L;
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		String local = "/soft/download-directory";//选择一个你centos下的目录作为你的下载文件存放地址
    		String filePath = new String(request.getParameter("filePath").getBytes("ISO-8859-1"),"GB2312");
    		HdfsDAO hdfs = new HdfsDAO();
    		hdfs.download(filePath, local);
    		FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    		request.setAttribute("documentList", documentList);
    		System.out.println("得到list数据"+documentList);
    		request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		this.doGet(request, response);
    	}
    }

    继续在com.controller下创建名为registerServlet.java的类文件,和注册你的用户有关的文件

    package com.controller;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    import com.simple.model.UserDAO;
    
    public class RegisterServlet extends HttpServlet{
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		this.doPost(request, response);
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		HttpSession session = request.getSession();
    		session.setAttribute("username", username);
    		UserDAO user = new UserDAO();
    		try{
    			user.insert(username, password);
    		}catch (SQLException e){
    			e.printStackTrace();
    		}
    		HdfsDAO hdfs = new HdfsDAO();
    		FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    		request.setAttribute("documentList", documentList);
    		request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    }

    继续在com.controller下创建名为loginServlet.java的类文件,和你的用户登录有关的文件

    package com.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    import com.simple.model.UserDAO;
    
    public class LoginServlet extends HttpServlet{
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		this.doPost(request, response);
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		UserDAO user = new UserDAO();
    		if(user.checkUser(username,password)){
    			//用户合法,跳转到页面
    			HttpSession session = request.getSession();
    			session.setAttribute("username", username);
    			HdfsDAO hdfs = new HdfsDAO();
    			FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    			request.setAttribute("documentList", documentList);
    			System.out.println("得到list数据"+documentList);
    			request.getRequestDispatcher("index.jsp").forward(request, response);
    		}else{
    			//用户不合法,调回登录界面,并提示错误信息
    			request.getRequestDispatcher("login.jsp").forward(request, response);
    		}
    	}
    }

    继续com.controller下创建deleteServlet.java的类文件,与删除文件有关系的文件

    package com.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    
    public class DeleteFileServlet extends HttpServlet{
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		String filePath = new String(request.getParameter("filePath").getBytes("ISO-8859-1"),"GB2312");
    		HdfsDAO hdfs = new HdfsDAO();
    		hdfs.deleteFromHdfs(filePath);
    		System.out.println("===="+filePath+"====");
    		FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    		request.setAttribute("documentList", documentList);
    		System.out.println("得到list数据"+documentList);
    		request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		this.doGet(request, response);
    	}
    }

    接下来右键-->com.Bean,new-->class,名为UserBean,

    package com.bean;
    
    public class UserBean {
    	private int id;
    	private String name;
    	private String password;
    	public int getID(){
    		return id;
    	}
    	public void setID(int id){
    		this.id = id;
    	}
    	public String getName(){
    		return name;
    	}
    	public void setName(){
    		this.name = name;
    	}
    	public String getPassword(){
    		return password;
    	}
    	public void setPassword(String password){
    		this.password = password;
    	}
    	@Override
    	public String toString(){
    		return "UserBean [id=" + id + ", name=" + name + ", password=" + password + "]"; 
    	}
    	public UserBean(int id, String name, String password){
    		super();
    		this.id = id;
    		this.name = name;
    		this.password = password;
    	}
    	public UserBean(){
    		super();
    	}
    }

    右键,com.model,分别创建ConnDB.java, HdfsDAO.java, UserDAO.ja

    package com.model;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class ConnDB {
    	private Connection ct = null;
    	public Connection getConn(){
    		try{
    			//加载驱动
    			Class.forName("com.mysql.jdbc.Driver");
    			//得到链接
    			ct = DriverManager.getConnection("jdbc:mysql://192.168.100.12:3306/hadoop?user=root&password=*****&useSSL=false");//该IP写你的集群分布的datanode的IP地址,3306是连接数据库的端口号,后面的user和password和你创建MySQL数据库时的用户有关系,一般用户是root,密码根据你自己设置的密码填写
    		} catch (Exception e){
    			//TODO Auto-genetated catch block
    			e.printStackTrace();
    		}
    		return ct;
    	}
    }
    package com.model;
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.URI;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FileStatus;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    
    public class HdfsDAO {
    	private static String hdfsPath = "hdfs://192.168.100.10:8020/aa";//该IP和端口是你在配置分布式集群系统时候的DataNode的ip,端口也是你自己设置的一个端口,我这里设置的是8020,后面的路径,就是在Hadoop hdfs上的路径,可以通过在终端输入hadoop fs -ls /来查看你上面的目录,之后上传或者下载文件等操作会运用到这个目录
    	Configuration conf = new Configuration();
    	public void copyFile(String local) throws IOException{
    		FileSystem fs = FileSystem.get(URI.create(hdfsPath),conf);
    		//remote---/用户/用户下的文件或文件夹
    		fs.copyFromLocalFile(new Path(local), new Path(hdfsPath));
    		fs.close();
    	}
    	/**从HDFS上下载数据*/
    	public void download(String remote,String local) throws IOException{
    		FileSystem fs = FileSystem.get(URI.create(hdfsPath),conf);
    		fs.copyToLocalFile(false, new Path(remote),new Path(local),true);
    		System.out.println("download: from"+remote+" to "+local);
    		fs.close();
    	}
    	/**从HDFS上删除文件*/
    	public void deleteFromHdfs(String deletePath) throws FileNotFoundException, IOException{
    		Configuration conf = new Configuration();
    		FileSystem fs = FileSystem.get(URI.create(deletePath),conf);
    		fs.deleteOnExit(new Path(deletePath));
    		fs.close();
    	}
    	/**遍历HDFS上的文件和目录*/
    	public static FileStatus[] getDirectoryFromHdfs() throws FileNotFoundException, IOException{
    		Configuration conf = new Configuration();
    		FileSystem fs = FileSystem.get(URI.create(hdfsPath),conf);
    		FileStatus[] list = fs.listStatus(new Path(hdfsPath));
    		if(list != null)
    			for(FileStatus f:list){
    				System.out.printf("name: %s, folder: %s,size: %d\n",f.getPath().getName(),f.isDir(),f.getLen());
    			}
    		fs.close();
    		return list;
    	}
    }
    package com.model;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class UserDAO {
    	private Statement sm = null;
    	private Connection ct = null;
    	private ResultSet rs = null;
    	public void close(){
    		try{
    			if(sm != null){
    				sm.close();
    				sm = null;
    			}
    			if(ct != null){
    				ct.close();
    				ct = null;
    			}
    			if(rs != null){
    				rs.close();
    				rs = null;
    			}
    		}catch (SQLException e){
    			//TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	//检查用户是否合法
    	public boolean checkUser(String user,String password){
    		boolean b = false;
    		try{
    			//获得连接
    			ct = new ConnDB().getConn();
    			//创建statement
    			sm = ct.createStatement();
    			String sql = "select * from student where name=\""+user+"\"";
    			rs = sm.executeQuery(sql);
    			if(rs.next()){
    				//说明用户存在
    				String pwd = rs.getString(3);
    				if(password.equals(pwd)){
    					//说明密码正确
    					b = true;
    				}
    				else{
    					b = false;
    				}
    			}
    			else{
    				b = false;
    			}
    		}
    		catch (SQLException e){
    			e.printStackTrace();
    		}finally{
    			this.close();
    		}
    		return b;
    	}
    	public void insert(String name,String password) throws SQLException{
    		int i = 0;
    		//获得连接
    		ct = new ConnDB().getConn();
    		//创建statement
    		sm = ct.createStatement();
    		String sql = "insert into student (name,password) values ('"+name+"','"+password+"')";
    		System.out.println(sql+"333333333");
    		i = sm.executeUpdate(sql);
    	}
    }

    配置一下你的web.xml文件,该文件位于WEB-INF下面,如果没有,右键new一个就可以了

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>hadoop</display-name>
      <welcome-file-list>
        <welcome-file>login.html</welcome-file>
        <welcome-file>login.htm</welcome-file>
        <welcome-file>login.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
    
      <servlet>
      	<description></description>
      	<display-name>UploadServlet</display-name>
      	<servlet-name>UploadServlet</servlet-name>
      	<servlet-class>com.simple.controller.UploadServlet</servlet-class>
      </servlet>
      <context-param>
      	<description>Location to store uploaded file</description>
      	<param-name>file-upload</param-name>
      	<param-value>
      	/soft/file-directory
      	</param-value>//这个目录是你centos上的目录,可自己设定,确保目录存在
      	
      </context-param>
      <servlet-mapping>
      	<servlet-name>UploadServlet</servlet-name>
      	<url-pattern>/UploadServlet</url-pattern>
      </servlet-mapping>
        <servlet>
      	<description></description>
      	<display-name>DeleteFileServlet</display-name>
      	<servlet-name>DeleteFileServlet</servlet-name>
      	<servlet-class>com.simple.controller.DeleteFileServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      	<servlet-name>DeleteFileServlet</servlet-name>
      	<url-pattern>/DeleteFileServlet</url-pattern>
      </servlet-mapping>
      
      <servlet>
      	<description></description>
      	<display-name>DownloadServlet</display-name>
      	<servlet-name>DownloadServlet</servlet-name>
      	<servlet-class>com.simple.controller.DownloadServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      	<servlet-name>DownloadServlet</servlet-name>
      	<url-pattern>/DownloadServlet</url-pattern>
      </servlet-mapping>
      <servlet>
      	<description></description>
      	<display-name>LoginServlet</display-name>
      	<servlet-name>LoginServlet</servlet-name>
      	<servlet-class>com.simple.controller.LoginServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      	<servlet-name>LoginServlet</servlet-name>
      	<url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>
      <servlet>
      	<description></description>
      	<display-name>RegisterServlet</display-name>
      	<servlet-name>RegisterServlet</servlet-name>
      	<servlet-class>com.simple.controller.RegisterServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      	<servlet-name>RegisterServlet</servlet-name>
      	<url-pattern>/RegisterServlet</url-pattern>
      </servlet-mapping>
    </web-app>

    如果对于web.xml里面的内容不理解,尽量自己搜索理解清楚,上面涉及到的内容还是比较容易理解的。

    接下来,我们应该创建页面内容了,这些内容基于jsp文件的实现,下面做的是最简单的例子,如果自己需要更好美观的界面,可以自行去设置调整,创建注册登录页面,选中WEB-INF-->右键-->new-->JSP File,(没有这个选项就选择other,里面搜索会出现JSP文件)

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
    	function checkUser(){
    		if(document.login.inputname.value == ""){
    			alert("用户名不能为空。");
    			return false;
    		}
    		if(document.login.inputpass.value == ""){
    			alert("密码不能为空。");
    			return false;
    		}
    		return true;
    	}
    </script>
    <title>数据云盘</title>
    <link rel = "stylesheet" href = "assets/css/style.css">
    <body style = "background-color:lightblue;background-position:center;background-repeat:repeat-y">
    	<div class="login-container" style="margin-left:100px;">
    		<h1>数据网盘</h1>
    		<div class="connect">
    			<p>www.shiyanbar.com</p>
    		</div>
    		<form action="LoginServlet" method="post" id="loginForm" name="login" onsubmit="return checkUser()">
    			<div>
    				<input type="text" id="inputname" name="username" class="username" placeholder="用户名" autocomplete="off">
    			</div>
    			<div>
    				<input type="password" id="inputpass" name="password" class="password" placeholder="密码" oncontextmenu="return false" onpaste="return false">
    			</div>
    			<button id="submit" type="submit">登录</button>
    		</form>
    		<a href="register.jsp">
    			<button type="button" class="register-tis">还没有账号?</button>
    		</a>
    	</div>
    	<div style="text-align: center;margin: 50px 0;font:normal 14px/24px 'MicroSoft YaHei';">
    		<p>
    			适用浏览器:360、FireFox、Chrome、Opera、傲游、搜狗、世界之窗。不支持IE8及以下浏览器。
    		</p>
    
    	</div>
    </body>
    </html>

    同样的方法创建主界面index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
    <%@ include file="head.jsp" %> 
    <%@page import="org.apache.hadoop.fs.FileStatus" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>数据云盘</title>
    </head>
    <body style="text-align: center;margin-bottom: 100px;">
    	<div class="navbar">
    		<div class="navbar-inner">
    			<a class="brand" href="#" style="margin-left: 200px;font-size:20px;" style="color: #000000">网盘</a>
    			<ul class="nav" style="line-height: 40px;float: right;">
    				<li><a style="color: #000000 size=40"><%=session.getAttribute("username")%></a></li>
    				<li><a href="login.jsp"><input type="button" value="退出"></a></li>
    			</ul>
    		</div>
    	</div>
    	<div style="margin: 0px auto;text-align: left;width: 1000px;height: 50px;">
    		<form class="form-inline" method="POST" enctype="MULTIPART/FORM-DATA" action="UploadServlet">
    			<div style="line-height: 50px;float: left;margin-left:100px;">
    				<input style="background-color:#cccccc;" type="submit" name="submit" value="上传文件">
    			</div>
    			<div style="line-height: 50px;float: left;">
    				<input type="file" name="file1" size="30">
    			</div>
    		</form>
    	</div>
    	<div style="margin: 0px auto;width: 1000px;height: 500px;background: #fff">
    		<table class="table table-hover" style="width: 800px;margin-left: 100px;">
    			<tr>
    				<td>文件名</td>
    				<td>属性</td>
    				<td>大小</td>
    				<td>操作</td>
    				<td>操作</td>
    			</tr>
    			<%
    			FileStatus[] list = (FileStatus[])request.getAttribute("documentList");
    			String name = (String)request.getAttribute("username");
    			if(list != null)
    			for(int i=0;i<list.length;i++){
    				%>
    			<tr style="border-bottom: 2px solid #ddd">
    				<%
    					if(list[i].isDir())//DocumentServlet
    					{
    						out.print("<td><a href=\"UploadServlet?filePath="+list[i].getPath()+"\">"+list[i].getPath().getName()+"></a></td>");
    					}
    					else{
    					out.print("<td>"+list[i].getPath().getName()+"</td>");
    				}
    				%>
    				<td><%= (list[i].isDir()?"目录":"文件")%></td>
    				<td><%= (list[i].getLen()) %></td>
    				<td><a style="color: #000000" href="DeleteFileServlet?filePath=<%=java.net.URLEncoder.encode(list[i].getPath().toString(),"GB2312") %>">删除</a></td>
    				<td><a style="color: #000000" href="DownloadServlet?filePath=<%=java.net.URLEncoder.encode(list[i].getPath().toString(),"GB2312") %>">下载</a></td>
    			</tr>
    			<%
    			}
    			%>
    		</table>
    	</div>
    </body>
    </html>

    同样的方法创建注册页面register.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
    <%@ include file="head.jsp" %> 
    <%@page import="org.apache.hadoop.fs.FileStatus" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>数据云盘</title>
    </head>
    <body style="text-align: center;margin-bottom: 100px;">
    	<div class="navbar">
    		<div class="navbar-inner">
    			<a class="brand" href="#" style="margin-left: 200px;font-size:20px;" style="color: #000000">网盘</a>
    			<ul class="nav" style="line-height: 40px;float: right;">
    				<li><a style="color: #000000 size=40"><%=session.getAttribute("username")%></a></li>
    				<li><a href="login.jsp"><input type="button" value="退出"></a></li>
    			</ul>
    		</div>
    	</div>
    	<div style="margin: 0px auto;text-align: left;width: 1000px;height: 50px;">
    		<form class="form-inline" method="POST" enctype="MULTIPART/FORM-DATA" action="UploadServlet">
    			<div style="line-height: 50px;float: left;margin-left:100px;">
    				<input style="background-color:#cccccc;" type="submit" name="submit" value="上传文件">
    			</div>
    			<div style="line-height: 50px;float: left;">
    				<input type="file" name="file1" size="30">
    			</div>
    		</form>
    	</div>
    	<div style="margin: 0px auto;width: 1000px;height: 500px;background: #fff">
    		<table class="table table-hover" style="width: 800px;margin-left: 100px;">
    			<tr>
    				<td>文件名</td>
    				<td>属性</td>
    				<td>大小</td>
    				<td>操作</td>
    				<td>操作</td>
    			</tr>
    			<%
    			FileStatus[] list = (FileStatus[])request.getAttribute("documentList");
    			String name = (String)request.getAttribute("username");
    			if(list != null)
    			for(int i=0;i<list.length;i++){
    				%>
    			<tr style="border-bottom: 2px solid #ddd">
    				<%
    					if(list[i].isDir())//DocumentServlet
    					{
    						out.print("<td><a href=\"UploadServlet?filePath="+list[i].getPath()+"\">"+list[i].getPath().getName()+"></a></td>");
    					}
    					else{
    					out.print("<td>"+list[i].getPath().getName()+"</td>");
    				}
    				%>
    				<td><%= (list[i].isDir()?"目录":"文件")%></td>
    				<td><%= (list[i].getLen()) %></td>
    				<td><a style="color: #000000" href="DeleteFileServlet?filePath=<%=java.net.URLEncoder.encode(list[i].getPath().toString(),"GB2312") %>">删除</a></td>
    				<td><a style="color: #000000" href="DownloadServlet?filePath=<%=java.net.URLEncoder.encode(list[i].getPath().toString(),"GB2312") %>">下载</a></td>
    			</tr>
    			<%
    			}
    			%>
    		</table>
    	</div>
    </body>
    </html>

    同样的方法创建,head.jsp文件,该文件引用了一些css等HTML文件

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    	<link rel="stylesheet" type="text/css" href="assets/css/bootmetro.css">
    	<link rel="stylesheet" type="text/css" href="assets/css/bootmetro-responsive.css">
    	<link rel="stylesheet" type="text/css" href="assets/css/bootmetro-icons.css">
    	<link rel="stylesheet" type="text/css" href="assets/css/bootmetro-ui-light.css">
    	<link rel="stylesheet" type="text/css" href="assets/css/datepicker.css">
    	<!--these two css are to use only for documentation-->
    	<link rel="stylesheet" type="text/css" href="assets/css/site.css">
    	<!--Le fav and touch icons-->
    	<link rel="shortcut icon" type="text/css" href="assets/ico/favicon.ico">
    	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
    	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
    	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
    	<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
    	<!--All JavaScript at the bottom, except for Modernizr and Respond.
    		Modernizr enables HTML5 elements & feature detects;Respond is a polyfill for min/max-width CSS3 Media Queries
    		For optimal performance, use a custom Modernizr build
    		www.modenizr.com/download/-->
    	<script src="assets/js/modenizr-2.6.2.min.js"></script>
    	<meta http-equiv="Content-Type" content="text/html"; charset="utf-8">
    	<title>Insert title here</title>
    </head>
    </html>

    网上下载bootmetro-master框架(搜索就会出现),将里面的assets下面的文件夹导入 项目的WebContent文件夹下面,美化用户的操作界面

    将MySQL的驱动包导入至lib文件夹下,这个包在网上可以下载,右击jar包选择“Build Path”→“Add to Build Path”在项目中添加。,在MySQL中创建名为student的表create table student; 创建一下属性

    涉及MySQL的语句的简单使用,

    接下来就可以运行啦,确保tomcat已经安装好了,MySQL也已经启动了,最重要的是,终端启动start-dfs.sh以及start-yarn.sh

    输入jps命令,查看集群启动是否成功,成功后就可以执行啦。

    eclipse选中你的项目,右键-->RUN AS-->Run on server -->选择tomcat服务器

    接下来就是页面啦

    一定要装好MySQL,为了让我的第一台机器轻松一点,MySQL我装在了第二台上面,web.xml一定要配置正确!!!,这个文件连接了你的前端和后端,所以字母拼错了就可能导致报错。

    如果大家有什么报错的地方,可以留言给大家一起交流。我也还只是在慢慢学习中!!!

    展开全文
  • HDFS数据云盘搭建

    2021-06-22 12:46:02
    代码编写 7.1 index.jsp 7.2 head.jsp 7.3 UploadServlet.java 7.4 HdfsDAO.java 7.5 DeleteFileServlet.java 7.6 DownloadServlet.java 7.7 UserBean.java 7.8 ConnDB.java 7.9 login.jsp 7.10 register.jsp 7.11 ...

    1.配置host

    注:所有操作均在1号机中进行
    为了防止之后因端口被占用导致启动Tomcat失败,把这两句话:

    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    

    添加回/etc/hosts配置文件开头即可。

    su
    输入密码
    
    vi /etc/hosts
    

    变为:

    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    192.168.100.10 bigdata-senior01.chybinmy.com
    192.168.100.12 bigdata-senior02.chybinmy.com
    192.168.100.13 bigdata-senior03.chybinmy.com
    

    2.设置共享文件夹

    使用VMware Tools实现虚拟机和宿主机之间的文件传输有时候会死机,建议使用共享文件夹。
    在VMware菜单栏-虚拟机-设置-选项-共享文件夹-总是启用
    在这里插入图片描述
    -添加-下一步
    在这里插入图片描述
    选择路径-下一步
    在这里插入图片描述
    -完成
    在虚拟机中的路径为:Computer-Filesystem-mnt-hgfs-share

    3.安装mysql

    将mysql-5.7.26-linux-glibc2.12-x86_64.tar.gz复制到共享文件夹share中
    移动到tmp目录下,在共享文件夹中解压可能会报错

    cd /mnt/hgfs/share/
    mv mysql-5.7.26-linux-glibc2.12-x86_64.tar.gz /tmp/
    

    进行解压

    cd /tmp/
    tar -xvf mysql-5.7.26-linux-glibc2.12-x86_64.tar.gz
    

    移动位置并重命名为mysql

    mv mysql-5.7.26-linux-glibc2.12-x86_64 /usr/local/mysql
    

    创建mysql用户组和用户并修改权限

    groupadd mysql
    useradd -r -g mysql mysql
    

    创建数据目录并赋予权限

    mkdir -p  /data/mysql
    chown mysql:mysql -R /data/mysql
    

    配置my.cnf

    vi /etc/my.cnf
    

    改为:

    [mysqld]
    bind-address=0.0.0.0
    port=3306
    user=mysql
    basedir=/usr/local/mysql
    datadir=/data/mysql
    socket=/tmp/mysql.sock
    log-error=/data/mysql/mysql.err
    pid-file=/data/mysql/mysql.pid
    #character config
    character_set_server=utf8mb4
    symbolic-links=0
    explicit_defaults_for_timestamp=true
    

    初始化数据库
    进入mysql的bin目录

    cd /usr/local/mysql/bin/
    

    初始化

    ./mysqld --defaults-file=/etc/my.cnf --basedir=/usr/local/mysql/ --datadir=/data/mysql/ --user=mysql --initialize
    

    查看密码

    cat /data/mysql/mysql.err
    

    记住这个随机生成的密码

    启动mysql,并更改root 密码
    先将mysql.server放置到/etc/init.d/mysql中

    cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysql
    

    启动mysql

    service mysql start
    ps -ef|grep mysql
    

    登录mysql

    ./mysql -u root -p
    

    输入刚才随机生成的密码,进入到mysql数据库

    进行密码的重置,设置为123456

    SET PASSWORD = PASSWORD('123456');
    ALTER USER 'root'@'localhost' PASSWORD EXPIRE NEVER;
    FLUSH PRIVILEGES; 
    

    使root能再任何host访问

    use mysql
    update user set host = '%' where user = 'root';
    FLUSH PRIVILEGES;
    

    新建student表,之后用到

    CREATE TABLE student (
     id INTEGER (10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
     name VARCHAR (20) NOT NULL,
     password VARCHAR (20) NOT NULL
    );
    

    可以看表结构

    desc student;
    

    查看表中所有数据

    select * from student;
    

    注:每次运行项目时都要启动mysql

    cd /usr/local/mysql/bin/
    service mysql start
    ./mysql -u root -p
    输入密码123456
    
    use mysql;
    desc student;
    

    可以进行表的删除

    DELETE FROM student;
    

    退出mysql命令行

    exit;
    

    4.在eclipse中安装并新建Dynamic Web Project

    cd /usr/eclipse/
    ./eclipse 
    

    -OK
    菜单栏-Help-Install New Software
    在搜索框输入Mars,双击选择对应网址
    在这里插入图片描述

    Next-Next
    在这里插入图片描述
    -Finish
    安装完后重启eclipse
    打开Eclipse,选择File-New-Project-选择Dynamic Web Project
    Project name为clouddisk
    -Next-Next
    勾选生成web.xml
    在这里插入图片描述
    -Finish

    5.Tomcat安装

    我的Tomcat为8.5,eclipse中无法识别,先进行修改
    将apache-tomcat-8.5.66在本机上进行解压缩
    在其lib目录下找到Catalina.jar包
    右键-打开方式-选择压缩文件打开
    在其中找到org\apache\catalina\util\ServerInfo.properties文件
    可右键用记事本打开
    将此处改为8.0.0,并保存
    在这里插入图片描述
    再将修改后的整个apache-tomcat-8.5.66文件夹复制到共享文件夹share中

    在eclipse中的菜单栏-Windows – Preference – Server – Runtime Environment – Add
    在这里插入图片描述
    -Next
    在这里插入图片描述
    -Finish-OK
    在下方窗口中New-Server
    在这里插入图片描述
    在这里插入图片描述
    双击服务器,进行更改,并保存
    在这里插入图片描述
    右键服务器-Start
    在浏览器中输入:http://localhost:8080/
    显示如下,则成功
    在这里插入图片描述

    6.进行jar包的拷贝

    新开一个命令行窗口

    su
    输入密码
    

    1.导入Hadoop相关的jar包
    拷贝“hadoop-hdfs-2.8.5.jar”包

    cp /opt/modules/app/hadoop-2.8.5/share/hadoop/hdfs/hadoop-hdfs-2.8.5.jar /root/workspace/clouddisk/WebContent/WEB-INF/lib/
    

    拷贝$HADOOP_HOME/share/hadoop/hdfs/lib/下的所有jar包

    cp /opt/modules/app/hadoop-2.8.5/share/hadoop/hdfs/lib/* /root/workspace/clouddisk/WebContent/WEB-INF/lib/
    

    拷贝“hadoop-common-2.8.5.jar”包

    cp /opt/modules/app/hadoop-2.8.5/share/hadoop/common/hadoop-common-2.8.5.jar /root/workspace/clouddisk/WebContent/WEB-INF/lib/
    

    拷贝$HADOOP_HOME/share/hadoop/common/lib下的所有jar包

    cp /opt/modules/app/hadoop-2.8.5/share/hadoop/common/lib/* /root/workspace/clouddisk/WebContent/WEB-INF/lib/
    

    有一些jar包是重复的,出现提示回车覆盖即可
    2.文件传输相关的jar包
    将commons-fileupload-1.4-bin.tar.gz和commons-io-2.8.0-bin.tar.gz复制到共享文件夹share中

    cd /mnt/hgfs/share/
    tar -xzf commons-fileupload-1.4-bin.tar.gz
    cd commons-fileupload-1.4-bin
    cp commons-fileupload-1.4.jar /root/workspace/clouddisk/WebContent/WEB-INF/lib/
    
    tar -xzf commons-io-2.8.0-bin.tar.gz
    cd /mnt/hgfs/share/commons-io-2.8.0
    cp commons-io-2.8.0.jar /root/workspace/clouddisk/WebContent/WEB-INF/lib/
    

    3.mysql相关jar包
    将mysql-connector-java-8.0.25.jar复制到共享文件夹share中

    cd /mnt/hgfs/share/
    cp mysql-connector-java-8.0.25.jar /root/workspace/clouddisk/WebContent/WEB-INF/lib/
    

    右键项目-Refresh,可看到lib文件夹下出现jar包
    右键项目-Build Path-Configure Build Path
    在这里插入图片描述
    选到当前的lib目录
    在这里插入图片描述
    CRTL+A全部选中-OK-OK
    便出现引用的类库

    7.代码编写

    复制粘贴代码时可能格式会乱,可粘贴完进行自动缩进
    Eclipse 自动缩进:Ctrl+Shift+F

    7.1 index.jsp

    右键单击WebContent 选择 “New”→“JSP File”新建名为 “index.jsp” 的文件,打开index.jsp文件,通过html编译网盘的主界面,展示hdfs的内容以及相关操作的布局。

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
    	function checkUser() {
    		if (document.login.inputname.value == "") {
    			alert("用户名不能为空.");
    			return false;
    		}
    		if (document.login.inputpass.value == "") {
    			alert("密码不能为空.");
    			return false;
    		}
    		return true;
    	}
    </script>
    <title>登录srk的网盘</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <body
    	style="background-color: #FFD700; background-position: center; background-repeat: repeat-y">
    	<div class="login-container">
    		<h1>hdfs网盘</h1>
    		<form action="LoginServlet" method="post" id="loginForm" name="login"
    			onsubmit="return checkUser()">
    			<div>
    				<input type="text" id="inputname" name="username" class="username"
    					placeholder="用户名" autocomplete="off" />
    			</div>
    			<div>
    				<input type="password" id="inputpass" name="password"
    					class="password" placeholder="密码" oncontextmenu="return false"
    					onpaste="return false" />
    			</div>
    			<button id="submit" type="submit">登 录</button>
    		</form>
    		<a href="register.jsp">
    			<button type="button" class="register-tis">账号注册</button>
    		</a>
    	</div>
    
    </body>
    </html>
    

    7.2 head.jsp

    右键单击 WebContent选择 “New”→“JSP File” 新建名为“head.jsp”的文件,打开并编译head.jsp文件,对项目的界面进行美化。

    head.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="assets/css/bootmetro.css">
    <link rel="stylesheet" type="text/css"
    	href="assets/css/bootmetro-responsive.css">
    <link rel="stylesheet" type="text/css"
    	href="assets/css/bootmetro-icons.css">
    <link rel="stylesheet" type="text/css"
    	href="assets/css/bootmetro-ui-light.css">
    <link rel="stylesheet" type="text/css" href="assets/css/datepicker.css">
    <!-- these two css are to use only for documentation -->
    <link rel="stylesheet" type="text/css" href="assets/css/site.css">
    <!-- Le fav and touch icons -->
    <link rel="shortcut icon" href="assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144"
    	href="assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114"
    	href="assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72"
    	href="assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed"
    	href="assets/ico/apple-touch-icon-57-precomposed.png">
    <!-- All JavaScript at the bottom, except for Modernizr and Respond.
    	Modernizr enables HTML5 elements & feature detects; Respond is a polyfill for  min/max-width CSS3 Media Queries
    	For optimal performance, use a custom Modernizr build:  www.modernizr.com/download/ -->
    <script src="assets/js/modernizr-2.6.2.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>欢迎使用srk的网盘</title>
    </head>
    </html>
    

    使用bootmetro-master框架,将框架里面的src/assets下面的文件夹导入项目的WebContent文件夹下面,美化用户的操作界面。
    先将assets文件夹粘贴到共享文件夹share中
    再复制到WebContent文件夹下面

    cp -r /mnt/hgfs/share/assets /root/workspace/clouddisk/WebContent/
    

    7.3 UploadServlet.java

    右键单击hadoop/Java Resources下的src,选择 “New”→“Package”,新建名为“com.simple.controller”包名,相同操作步骤,新建名为“com.simple.bean”与“com.simple.model” 包名。

    右击com.simple.controller包名选择 “New”→“Class”,新建名为 “UploadServlet” 的类文件并继承 HttpServlet ,重写doGet和doPost方法,对该类进行编译,操作对本地文 件上传至HDFS的 内容,基于安全考虑,无法获取文件的绝对路径,首先将得到的文件保存 至本地指定的地址,在从指定的地址拼 接文件的url得到文件的绝对路径,将文件上传至hdfs上。

    UploadServlet.java

    package com.simple.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    
    public class UploadServlet extends HttpServlet {
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		this.doPost(request, response);
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    		File file;
    		int maxFileSize = 50 * 1024 * 1024; // 50M
    		int maxMemSize = 50 * 1024 * 1024; // 50M
    		ServletContext context = getServletContext();
    		String filePath = context.getInitParameter("file-upload");
    		System.out.println("source file path:" + filePath + "");
    		// 验证上传内容的类型
    		String contentType = request.getContentType();
    		if (contentType == null) { // if you clicked a folder in the index.jsp,
    									// you will be here.
    			System.out.println(request.getParameter("filePath"));
    			HdfsDAO hdfs = new HdfsDAO();
    			FileStatus[] documentList = hdfs.getDirectoryFromHdfs(request.getParameter("filePath"));
    			// FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    			request.setAttribute("documentList", documentList);
    			System.out.println("得到list数据" + documentList);
    			request.getRequestDispatcher("index.jsp").forward(request, response);
    		} else if ((contentType.indexOf("multipart/form-data") >= 0)) {
    			DiskFileItemFactory factory = new DiskFileItemFactory();
    			// 设置内存中存储文件的最大值
    			factory.setSizeThreshold(maxMemSize);
    			// 本地存储的数据大于maxMemSize.
    			factory.setRepository(new File("/tmp"));
    			// 创建一个新的文件上传处理程序
    			ServletFileUpload upload = new ServletFileUpload(factory);
    			// 设置最大上传的文件大小
    			upload.setSizeMax(maxFileSize);
    			try {
    				// 解析获取的文件
    				List fileItems = upload.parseRequest(request);
    				// 处理上传的文件
    				Iterator i = fileItems.iterator();
    				System.out.println("begin to uploadfile to tomcat server</p>");
    				while (i.hasNext()) {
    					FileItem fi = (FileItem) i.next();
    					if (!fi.isFormField()) {
    						// 或取上传文件的参数
    						String fieldName = fi.getFieldName();
    						String fileName = fi.getName();
    						String fn = fileName.substring(fileName.lastIndexOf("\\") + 1);
    						System.out.println("<br>" + fn + "<br>");
    						boolean isInMemory = fi.isInMemory();
    
    						long sizeInBytes = fi.getSize();
    						// 写入文件
    						if (fileName.lastIndexOf("\\") >= 0) {
    							file = new File(filePath, fileName.substring(fileName.lastIndexOf("\\")));
    						} else {
    							file = new File(filePath, fileName.substring(fileName.lastIndexOf("\\") + 1));
    						}
    						fi.write(file);
    						System.out.println("upload file to tomcat server success!");
    						System.out.println("begin to upload file to hadoop hdfs</p>");
    						String name = filePath + "/" + fileName;
    						// 将tomcat上的文件上传到hadoop上
    						HdfsDAO hdfs = new HdfsDAO();
    						hdfs.copyFile(name);
    						System.out.println("upload file to hadoop hdfs success!");
    						FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    						request.setAttribute("documentList", documentList);
    						System.out.println("得到list数据" + documentList);
    						request.getRequestDispatcher("index.jsp").forward(request, response);
    					}
    				}
    			} catch (Exception ex) {
    				System.out.println(ex);
    			}
    		} else
    
    		{
    			System.out.println("<p>No file uploaded</p>");
    		}
    	}
    }
    

    7.4 HdfsDAO.java

    右键单击 com.simple.model 包名选择“New”→“Class”新建名为 “HdfsDAO”的类文件,操作对HDFS的增删改查的方法,需要对hdfs做什么操作,只需在本类中调用相应的方法。

    HdfsDAO.java

    package com.simple.model;
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.URI;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FileStatus;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    
    public class HdfsDAO {
    	private static String hdfsPath = "hdfs://192.168.100.10:8020/tmp";
    	// 该IP和端口是你在配置分布式集群系统时候的NameNode的ip,端口也是你自己设置的一个端口,
    	// 我这里设置的是8020,后面的路径,就是在Hadoop hdfs上的路径,可以通过在终端输入hadoop fs -ls /
    	// 来查看你上面的目录,之后上传或者下载文件等操作会运用到这个目录
    	Configuration conf = new Configuration();
    
    	/** 上传文件到HDFS上去 */
    	public void copyFile(String local) throws IOException {
    		FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
    		// remote---/用户/用户下的文件或文件夹
    		fs.copyFromLocalFile(new Path(local), new Path(hdfsPath));
    		fs.close();
    	}
    
    	/** 从HDFS上下载数据 **/
    	public void download(String remote, String local) throws IOException {
    		FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
    		fs.copyToLocalFile(false, new Path(remote), new Path(local), true);
    		System.out.println("download: from" + remote + " to " + local);
    		fs.close();
    	}
    
    	/** 从HDFS上删除文件 */
    	public static void deleteFromHdfs(String deletePath) throws FileNotFoundException, IOException {
    		Configuration conf = new Configuration();
    		FileSystem fs = FileSystem.get(URI.create(deletePath), conf);
    		fs.deleteOnExit(new Path(deletePath));
    		fs.close();
    	}
    
    	/** 遍历HDFS上的文件和目录 */
    	public static FileStatus[] getDirectoryFromHdfs(String... paths) throws FileNotFoundException, IOException {
    		Configuration conf = new Configuration();
    		FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
    		FileStatus[] list = fs.listStatus(new Path(hdfsPath));
    		for (String path : paths) {
    			if (path == null || "".equals(path)) {
    
    			} else {
    				fs = FileSystem.get(URI.create(path), conf);
    				list = fs.listStatus(new Path(path));
    			}
    		*斜体样式*}
    		if (list != null)
    			for (FileStatus f : list) {
    				System.out.printf("name: %s, folder: %s, size: %d\n", f.getPath().getName(), f.isDir(), f.getLen());
    			}
    		fs.close();
    		return list;
    	}
    }
    

    7.5 DeleteFileServlet.java

    右键单击com.simple.controller包名选择 “New”→“Class”新建名为 “DeleteFileServlet” 的类文件,操作对HDFS文件删除的内容。

    DeleteFileServlet.java

    package com.simple.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    
    public class DeleteFileServlet extends HttpServlet {
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String filePath = new String(request.getParameter("filePath").getBytes("ISO-8859-1"), "GB2312");
    		HdfsDAO hdfs = new HdfsDAO();
    		hdfs.deleteFromHdfs(filePath);
    		System.out.println("====" + filePath + "====");
    		FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    		request.setAttribute("documentList", documentList);
    		System.out.println(" 得 到 list 数 据 " + documentList);
    		request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		this.doGet(request, response);
    	}
    }
    

    7.6 DownloadServlet.java

    右击com.simple.controller包名选择 “New”→“Class”新建名为 “DownloadServlet”的类文件,操作对文件下载的内容。

    DownloadServlet.java

    package com.simple.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    
    public class DownloadServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String local = "/tmp";
    		String filePath = new String(request.getParameter("filePath").getBytes("ISO-8859-1"), "GB2312");
    		HdfsDAO hdfs = new HdfsDAO();
    		hdfs.download(filePath, local);
    		FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    		request.setAttribute("documentList", documentList);
    		System.out.println(" 得 到 list 数 据 " + documentList);
    		request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		this.doGet(request, response);
    	}
    }
    

    其中String local = “/tmp”;指定了下载位置为tmp文件夹

    7.7 UserBean.java

    右键单击com.simple.bean包 名选择 “New”→“Class”新建名为 “UserBean”的类文件,操作用户的属性的内容,用户的ID,name,password属 性,重写属性的set与get方法。

    UserBean.java

    package com.simple.bean;
    
    public class UserBean {
    	private int id;
    	private String name;
    	private String password;
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	@Override
    	public String toString() {
    		return "UserBean [id=" + id + ", name=" + name + ", password=" + password + "]";
    	}
    
    	public UserBean(int id, String name, String password) {
    		super();
    		this.id = id;
    		this.name = name;
    		this.password = password;
    	}
    
    	public UserBean() {
    		super();
    	}
    }
    

    7.8 ConnDB.java

    右击com.simple.model包 名选择 “New”→“Class” 新建名为“ConnDB”的类文件,操作连接 数据库的内容。

    ConnDB.java

    package com.simple.model;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class ConnDB {
    	private Connection ct = null;
    
    	public Connection getConn() {
    
    		try {
    			// 加载驱动
    			Class.forName("com.mysql.jdbc.Driver");
    
    			// 得到连接
    			ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?user=root&password=123456");
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    
    		return ct;
    	}
    }
    

    其中的数据库连接可以根据自己情况修改

    DriverManager.getConnection("jdbc:mysql://localhost:3306/hadoop?user=root&password=123456");
    

    7.9 login.jsp

    右键单击WebContent选择 “New”→“JSP File” 新建名为“login.jsp”的文件,打开并编译login.jsp文件,操作用户的登录界面及设置监听。

    login.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
    	function checkUser() {
    		if (document.login.inputname.value == "") {
    			alert("用户名不能为空.");
    			return false;
    		}
    		if (document.login.inputpass.value == "") {
    			alert("密码不能为空.");
    			return false;
    		}
    		return true;
    	}
    </script>
    <title>登录srk的网盘</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <body
    	style="background-color: #FFD700; background-position: center; background-repeat: repeat-y">
    	<div class="login-container">
    		<h1>hdfs网盘</h1>
    		<form action="LoginServlet" method="post" id="loginForm" name="login"
    			onsubmit="return checkUser()">
    			<div>
    				<input type="text" id="inputname" name="username" class="username"
    					placeholder="用户名" autocomplete="off" />
    			</div>
    			<div>
    				<input type="password" id="inputpass" name="password"
    					class="password" placeholder="密码" oncontextmenu="return false"
    					onpaste="return false" />
    			</div>
    			<button id="submit" type="submit">登 录</button>
    		</form>
    		<a href="register.jsp">
    			<button type="button" class="register-tis">账号注册</button>
    		</a>
    	</div>
    
    </body>
    </html>
    

    7.10 register.jsp

    右键单击WebContent选择 “New”→“JSP File”新建名为 “register.jsp”的文件,打开并编译register.jsp文件,操作用户的注册界面并 对用户的操作作监听。

    register.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
    	function checkRegister() {
    		if (document.register.inputname.value == "") {
    			alert("用户名不能为空.");
    			return false;
    		} else {
    			if (document.register.inputpass.value == "") {
    				alert("密码不能为空.");
    				return false;
    			} else {
    				if (document.register.surepass.value == "") {
    					alert("确认密码不能为空.");
    					return false;
    				} else {
    					if (document.register.inputpass.value != document.register.surepass.value) {
    						alert("两次密码不一致。");
    						return false;
    					}
    				}
    			}
    		}
    		return true;
    	}
    </script>
    <title>注册srk的网盘</title>
    <link rel="stylesheet" href="assets/css/login.css">
    <body>
    	<div>
    		<h1>注册</h1>
    		<div class="connect">
    			<p>信息注册</p>
    		</div>
    		<form action="RegisterServlet" method="post" id="registerForm"
    			onsubmit="return checkRegister()" name="register">
    			<div>
    				<input type="text" name="username" id="inputname" class="username"
    					placeholder="您的用户名" autocomplete="off" />
    			</div>
    			<div>
    				<input type="password" name="password" id="inputpass"
    					class="password" placeholder="输入密码" />
    			</div>
    			<div>
    				<input type="password" name="surepass" id="surepass"
    					class="surepass" placeholder="再次输入密码" />
    			</div>
    			<button id="submit" type="submit">注 册</button>
    		</form>
    		<a href="login.jsp">
    			<button type="button" class="register-tis">已经有账号?</button>
    		</a>
    	</div>
    </body>
    </html>
    

    7.11 LoginServlet.java

    右键单击 com.simple.controller包名选择“New”→“Class” 新建名为“LoginServlet”的类文件,并对该类进行编译,操作登录对用户的 登录信息在数据库中查询,存在登录成功,否则登录失败。

    LoginServlet.java

    package com.simple.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    import com.simple.model.UserDAO;
    
    public class LoginServlet extends HttpServlet {
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		this.doPost(request, response);
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		UserDAO user = new UserDAO();
    		if (user.checkUser(username, password)) {
    			// 用户合法,跳转到页面
    			HttpSession session = request.getSession();
    			session.setAttribute("username", username);
    			HdfsDAO hdfs = new HdfsDAO();
    			FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    			request.setAttribute("documentList", documentList);
    			System.out.println("得到list数据" + documentList);
    			request.getRequestDispatcher("index.jsp").forward(request, response);
    		} else {
    			// 用户不合法,调回登录界面,并提示错误信息
    			request.getRequestDispatcher("login.jsp").forward(request, response);
    		}
    	}
    }
    

    7.12 UserDAO.java

    右键单击com.simple.model包名选择“New”→“Class”新建名为“UserDAO”的类文件,操作对数据验证,插入数据至数据库的内容。

    UserDAO.java

    package com.simple.model;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class UserDAO {
    	private Statement sm = null;
    	private Connection ct = null;
    	private ResultSet rs = null;
    
    	public void close() {
    		try {
    			if (sm != null) {
    				sm.close();
    				sm = null;
    			}
    			if (ct != null) {
    				ct.close();
    				ct = null;
    			}
    			if (rs != null) {
    				rs.close();
    				rs = null;
    			}
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	// 检查用户是否合法
    	public boolean checkUser(String user, String password) {
    		boolean b = false;
    		try {
    			// 获得连接
    			ct = new ConnDB().getConn();
    			// 创建statement
    			sm = ct.createStatement();
    			String sql = "select * from student where name=\"" + user + "\"";
    			rs = sm.executeQuery(sql);
    			if (rs.next()) {
    				// 说明用户存在
    				String pwd = rs.getString(3);
    				if (password.equals(pwd)) {
    					// 说明密码正确
    					b = true;
    				} else {
    					b = false;
    				}
    			} else {
    				b = false;
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} finally {
    			this.close();
    		}
    		return b;
    	}
    
    	public void insert(String name, String password) throws SQLException {
    		int i = 0;
    		// 获得连接
    		ct = new ConnDB().getConn();
    		// 创建statement
    		sm = ct.createStatement();
    		String sql = "insert into student (name,password) values ('" + name + "','" + password + "')";
    		System.out.println(sql + "333333333");
    		i = sm.executeUpdate(sql);
    	}
    }
    

    7.13 RegisterServlet.java

    右键单击com.simple.controller包名选择 “New”→“Class” 新建名为 “RegisterServlet” 的类文件,操作用户注册的信息,并将用户的信息保存至 MySQL中。

    RegisterServlet.java

    package com.simple.controller;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.apache.hadoop.fs.FileStatus;
    
    import com.simple.model.HdfsDAO;
    import com.simple.model.UserDAO;
    
    public class RegisterServlet extends HttpServlet {
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		this.doPost(request, response);
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		HttpSession session = request.getSession();
    		session.setAttribute("username", username);
    		UserDAO user = new UserDAO();
    		try {
    			user.insert(username, password);
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		HdfsDAO hdfs = new HdfsDAO();
    		FileStatus[] documentList = hdfs.getDirectoryFromHdfs();
    		request.setAttribute("documentList", documentList);
    		request.getRequestDispatcher("index.jsp").forward(request, response);
    	}
    }
    

    7.14 web.xml

    打开“WEB-INF”下的web.xml文件

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	id="WebApp_ID" version="2.5">
    	<display-name>hadoop</display-name>
    	<welcome-file-list>
    		<welcome-file>login.html</welcome-file>
    		<welcome-file>login.htm</welcome-file>
    		<welcome-file>login.jsp</welcome-file>
    		<welcome-file>default.html</welcome-file>
    		<welcome-file>default.htm</welcome-file>
    		<welcome-file>default.jsp</welcome-file>
    	</welcome-file-list>
    
    	<servlet>
    		<description></description>
    		<display-name>UploadServlet</display-name>
    		<servlet-name>UploadServlet</servlet-name>
    		<servlet-class>com.simple.controller.UploadServlet</servlet-class>
    	</servlet>
    	<servlet>
    		<description></description>
    		<display-name>DeleteFileServlet</display-name>
    		<servlet-name>DeleteFileServlet</servlet-name>
    		<servlet-class>com.simple.controller.DeleteFileServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>DeleteFileServlet</servlet-name>
    		<url-pattern>/DeleteFileServlet</url-pattern>
    	</servlet-mapping>
    
    	<servlet>
    		<description></description>
    		<display-name>DownloadServlet</display-name>
    		<servlet-name>DownloadServlet</servlet-name>
    		<servlet-class>com.simple.controller.DownloadServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>DownloadServlet</servlet-name>
    		<url-pattern>/DownloadServlet</url-pattern>
    	</servlet-mapping>
    
    	<servlet>
    		<description></description>
    		<display-name>LoginServlet</display-name>
    		<servlet-name>LoginServlet</servlet-name>
    		<servlet-class>com.simple.controller.LoginServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>LoginServlet</servlet-name>
    		<url-pattern>/LoginServlet</url-pattern>
    	</servlet-mapping>
    	<servlet>
    		<description></description>
    		<display-name>RegisterServlet</display-name>
    		<servlet-name>RegisterServlet</servlet-name>
    		<servlet-class>com.simple.controller.RegisterServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>RegisterServlet</servlet-name>
    		<url-pattern>/RegisterServlet</url-pattern>
    	</servlet-mapping>
    
    	<context-param>
    		<description>Location to store uploaded file</description>
    		<param-name>file-upload</param-name>
    		<param-value>
    			/root/Upload-files
    		</param-value>
    	</context-param>
    	<servlet-mapping>
    		<servlet-name>UploadServlet</servlet-name>
    		<url-pattern>/UploadServlet</url-pattern>
    	</servlet-mapping>
    </web-app>
    

    其中

    <param-value>
    	/root/Upload-files
    </param-value>
    

    代表了上传的文件的存储位置。

    需要先建立Upload-files文件夹

    mkdir /root/Upload-files
    

    8.效果展示

    首先要启动mysql服务

    cd /usr/local/mysql/bin/
    service mysql start
    ./mysql -u root -p
    输入密码123456
    

    新开一个命令行窗口

    su
    输入密码
    
    start-dfs.sh
    

    开启3台虚拟机,启动hdfs集群

    start-dfs.sh
    

    打开eclipse

    cd /usr/eclipse/
    ./eclipse 
    

    左键项目-Run As-Run on Server
    在这里插入图片描述
    复制下地址,到浏览器中访问http://localhost:8080/clouddisk/
    主界面如下:
    在这里插入图片描述
    可进行用户的登录和账号的注册
    在这里插入图片描述

    点Browse可选择要上传的文件,再点击上传文件,文件便上传到hdfs上
    在这里插入图片描述
    并可以进行文件的下载和删除

    点击下载后,文件下载到/tmp路径下

    使用结束后关闭集群

    stop-dfs.sh
    

    注:有一个小bug,当注册两个同样账号密码的用户时,会出现无法登录的情况

    展开全文
  • 结合个人项目浅谈云盘存储

    千次阅读 2015-01-08 21:34:53
    这个项目的灵感来自最近用得比较多的云盘云盘的主要功能除了以上几个外,还有回收站、分享自己的文件、将别的用户分享的文件转存到自己的云盘中,除此之外,有些云盘还具有关注他人、甚至是手机找回的附加功能。
  • 利用HDFS和JavaWeb实现数据云盘初步开发 1.index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE ...
  • 环境:centos7 Tomcat8.0 IDEAL MySQL hadoop 本云盘系统是基于Hadoop hdfs的集群分布式系统 技术 : 前端: html5+css3+vue 后端: springboot+spring+jpa+spring security+验证码 依赖管理: maven 数据库: ...
  • 使用java/jsp/mysql(javabean/servlet/jdbc),技术实现的微云盘系统,适合学习; 项目封装了大量通用工具以及很好的代码规范
  • ICloud 一个练手的云盘Java WEb项目 该项目没有使用框架,纯由jsp+servlet写成,适合于新人练手,页面代码来自于平台上另一位同学的源码,做了改动 项目效果如下:
  • 基于Hadoop实现的云盘系统,受到Hadoop文件读写机制的影响,采用Hadoop提供的API进行HDFS文件系统访问,文件读取时默认是顺序、逐block读取;写入时是顺序写入。 二、读写机制  首先来看文件读取机制:尽管...
  • Spring-Boot框架学习视频-百度云盘

    万次阅读 热门讨论 2018-07-30 22:14:25
    百度云盘下载地址 提取密码:bxif 1. 简介 蚂蚁课堂出品,本篇文章作者看了26讲,其中的内容清晰易懂,余胜军老师年少有为,而且也是一名孝子,值得我们学习。 2. 课程大纲 第一节-SpringBoot2.0课程介绍 ...
  • 一、本节说明 ...二、Struts相关配置 ...如果没有引入,请参考:Struts2项目实战 微云盘(二):项目结构Step2:配置Struts的核心Filter 在WEB-INF新建web.xml文件修改为如下格式:<?xml version="1.0" encoding="UT
  • 基于Hadoop2.2.0版本分布式云盘的设计与实现

    千次阅读 热门讨论 2014-04-25 22:34:59
    基于Hadoop2.2.0版本分布式云盘的设计与实现
  • Hadoop安全云盘开发(第4篇)

    千次阅读 2013-06-26 23:43:03
    在完成了在java程序中调用hadoop hdfs API 之后,我们开始了下一步的计划——做一个云盘(暂时不考虑加密)。 这个思路其实并不复杂,就是把调用API对hdfs文件系统进行操作的java程序布置到web端,做一个简单的网站...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 994
精华内容 397
热门标签
关键字:

jsp云盘