JavaWeb开发的Hadoop网盘(3)

文章目录

  • 一、dao层
    • 1、封装增删改查(BaseDao )
    • 2、登陆注册的接口(UserDao )
    • 3、登陆注册接口的实现类(UserDaoImpl ,需要继承BaseDao类、实现UserDao接口)
  • 二、HDFS类
  • 三、实体类(User )
  • 四、连接数据库jdbc(JdbcUtil )
  • 五、登陆注册页面(login.jsp)
  • 六、显示文件页面(index.jsp)

一、dao层

JavaWeb开发的Hadoop网盘(3)_第1张图片

1、封装增删改查(BaseDao )

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.rowset.CachedRowSet;

import com.sun.rowset.CachedRowSetImpl;

import util.JdbcUtil;

//封装所有的crud
public class BaseDao {
	//封装增删改   pst.executeUpdate
	public void	 modify	(String sql,Object...objects) {
		//获得connection对象
		Connection con=null;
		try {
			 con= JdbcUtil.getCon();
			//创建预编译对象,且预先执行sql语句
			PreparedStatement pst = con.prepareStatement(sql);
			for (int i = 0; i < objects.length; i++) {
				pst.setObject(i+1, objects[i]);
			}
			//提交
			pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//关闭资源
			JdbcUtil.closeCon(con);
		}
	}	
	

	//封装查询
	//返回的是缓存的结果集
	public CachedRowSet  search(String sql,Object...objects) {
			//获得connection对象
				Connection con=null;
				try {
					 con= JdbcUtil.getCon();
					//创建预编译对象,且预先执行sql语句
					PreparedStatement pst = con.prepareStatement(sql);
					for (int i = 0; i < objects.length; i++) {
						pst.setObject(i+1, objects[i]);
					}
					//提交并返回结果集
					ResultSet rs = pst.executeQuery();
					//创建缓存的结果集
					CachedRowSet crs= new CachedRowSetImpl();
					//将结果集放入到缓存的结果集中
					crs.populate(rs);
					//返回
					return  crs;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					//关闭资源
					JdbcUtil.closeCon(con);
				}
		return null;
		
	}
	
}

2、登陆注册的接口(UserDao )

package dao;
import pojo.User;
public interface UserDao {
	//注册
	void addUser(User user);
	//登陆
	User login(String username,String userpwd);
	//查找用户名
	User findUserName(String username);
}

3、登陆注册接口的实现类(UserDaoImpl ,需要继承BaseDao类、实现UserDao接口)

JavaWeb开发的Hadoop网盘(3)_第2张图片

package dao.impl;

import java.sql.SQLException;

import javax.sql.rowset.CachedRowSet;

import dao.BaseDao;
import dao.UserDao;
import pojo.User;

public class UserDaoImpl extends BaseDao implements UserDao {

	@Override
	public void addUser(User user) {
		String sql="insert into user(username,userpwd) values "+"(?,?)";
		modify(sql, user.getUsername(),user.getUserpwd());
		
	}

	@Override
	public User login(String username, String userpwd) {
		String sql="select * from user where username=? and userpwd=?";
		CachedRowSet result=this.search(sql, username,userpwd);
		User user=null;
		try {
			if (result.next()) {
				user=new User();
				user.setUserid(result.getInt("userid"));
				user.setUsername(result.getString("username"));
				user.setUserpwd(result.getString("userpwd"));
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public User findUserName(String username) {
		String sql="select * from user where username=?";
		// TODO Auto-generated method stub
		CachedRowSet result=this.search(sql, username);
		User user=null;
		try {
			if (result.next()) {
				user=new User();
				user.setUserid(result.getInt("userid"));
				user.setUsername(result.getString("username"));
				user.setUserpwd("null");
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}


}

二、HDFS类

JavaWeb开发的Hadoop网盘(3)_第3张图片
通过servlet来调用该类,实现HDFS中的上传、下载、删除文件等方法。

package hdfs;


import java.io.*;
import java.net.URI;

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HdfsOper {
	static Configuration conf = new Configuration();	
	public static void init() throws IOException {
		conf.set("fs.defaultFS","hdfs://localhost:9000");
	    conf.set("fs.hdfs.impl","org.apache.hadoop.hdfs.DistributedFileSystem");
	}
	//在用户目录下创建目录
	public static void CrDir(String PATH,String dir) throws IOException {
		init();
		FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		String file1=PATH+"/"+dir+"/";
		Path a=new Path(file1);
		fs.mkdirs(a);
		fs.close();
	}
	//为每个用户创建一个目录
	public static void mk(String username) throws IOException{
		init();
		FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		String upremote="/"+username;
		Path a = new Path(upremote);
		fs.mkdirs(a);
		fs.close();
	}
	//上传文件
	public static void copyFile(String fileName,InputStream in) throws IOException{
		init();
		//String filePath="/"+fileName;
	    FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
	    FSDataOutputStream out=fs.create(new Path(fileName));
	    IOUtils.copy(in,out);
	    fs.close();
	}

	//遍历用户根目录下的文件与目录
	public static FileStatus[] ShowFiles(String username) throws IOException{
		init();
		String filePath="/"+username+"/";
	    FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		FileStatus[] list=fs.listStatus(new Path(filePath));
		if (list!=null) {
			for (FileStatus f:list) {
				//System.out.printf("name %s,folder:%s,size:%d\n",f.getPath(),f.isDir(),f.getLen());
			}
		}
		fs.close();
		return list;
	}
	//遍历用户目录下的文件夹下面的文件
	public static FileStatus[] ShowDirFiles(String filePath) throws IOException{
		init();
		//String filePath1="/"+username+"/"+filePath+"/";
	    FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		FileStatus[] list=fs.listStatus(new Path(filePath));
		if (list!=null) {
			for (FileStatus f:list) {
				//System.out.printf("name %s,folder:%s,size:%d\n",f.getPath(),f.isDir(),f.getLen());
			}
		}
		fs.close();
		return list;
	}
	//下载文件夹
	public static void DownloadFile(String DirPath,String oldPath) throws IOException {
		//String oldPath="/user/hadoop/myLocalFile.txt";
		init();
		FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		//String name="myLocalFile.txt";
		String newPath="/home/hadoop/桌面";
		String oldPath1="/"+DirPath+"/"+oldPath;
		fs.copyToLocalFile(false, new Path(oldPath1),new Path(newPath),true);
		//Path ofile = new Path(oldPath);
		fs.close();

	}
	//通过流下载文件
	public static InputStream down(String filePath) throws IOException {
		init();
		FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		String filePath1="/"+filePath+"/";
		FSDataInputStream in=fs.open(new Path(filePath1));
		return in;
	}
	//删除文件
	public static void DeleteFile(String DirPath,String deletePath) throws IOException {
		init();
		FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		String deletePath1="/"+DirPath+"/"+deletePath;
		fs.deleteOnExit(new Path(deletePath1));
		fs.close();
	}
	//移动
	public static void ReName(String path1,String path2) throws IOException {
		// 1获取对象
		init();
		String filePath1 =path1 + "/";
		String filePath2 =path2 + "/";
		FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
		boolean re = fs.rename(new Path(filePath1), new Path(filePath2));
        System.out.println("rename:"+re);
	}
}

三、实体类(User )

JavaWeb开发的Hadoop网盘(3)_第4张图片

package pojo;

public class User {
	private int userid;
	private String username;
	private String userpwd;
	
	
	public User() {
	}
	
	public User(int userid, String username, String userpwd) {
		super();
		this.userid = userid;
		this.username = username;
		this.userpwd = userpwd;
	}
	@Override
	public String toString() {
		return "User [userid=" + userid + ", username=" + username + ", userpwd=" + userpwd + "]";
	}
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUserpwd() {
		return userpwd;
	}
	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}
}

四、连接数据库jdbc(JdbcUtil )

JavaWeb开发的Hadoop网盘(3)_第5张图片

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcUtil {
	private static String url="jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
	private static String username="debian-sys-maint";
	private static String password="Y3SWr5aeHtXxZ9QI";
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static Connection getCon() throws SQLException{
		
		return  (Connection) DriverManager.getConnection(url, username, password);
		
	}
	public static void closeCon(Connection con) {
		try {
			if (con!=null)
			{
				con.close();
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

五、登陆注册页面(login.jsp)

登陆注册是一个页面。代码里面引用了外部的js

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <title>Hadoop网盘</title>
    
	<script src="https://use.fontawesome.com/b729cab93f.js"></script>
    
<link rel="icon" href="http://img3.imgtn.bdimg.com/it/u=1870932651,3659050372&fm=26&gp=0.jpg" type="image/x-icon">
   <!--  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css"> -->
    <link rel="stylesheet" href="css/style.css">
    
</head>

<body style="background: url(img/test1.jpg)">
    <div class="dowebok" id="dowebok">
        <div class="form-container sign-up-container">
            <form action="register.do" method="post">
                <h1>注册</h1>
                <div class="social-container">
                    <a href="#" class="social"><i class="fa fa-qq"></i></a>
                    <a href="#" class="social"><i class="fa fa-link"></i></a>
                    <a href="#" class="social"><i class="fa fa-twitter"></i></a>
                </div>
                <input type="text" placeholder="用户名" name="username">
                <input type="password" placeholder="密码" name="userpwd">
                <input type="password" placeholder="确认密码" name="userpwd1">
                <button type="submit">注册</button>
                <br/>
				<span style="color: red">${message}</span>
            </form>
        </div>
        <div class="form-container sign-in-container">
            <form action="login.do" method="post">
                <h1>登录</h1>
                <div class="social-container">
                    <a href="#" class="social"><i class="fa fa-qq"></i></a>
                    <a href="#" class="social"><i class="fa fa-link"></i></a>
                    <a href="#" class="social"><i class="fa fa-twitter"></i></a>
                </div>
                <span>使用您的帐号</span>
                <input type="text" placeholder="用户名" name="username">
                <input type="password" placeholder="密码" name="userpwd">
                <a href="#">忘记密码?</a>
                <button type="submit">登录</button>
            </form>
        </div>
        <div class="overlay-container">
            <div class="overlay">
                <div class="overlay-panel overlay-left">
                    <h1>已有帐号?</h1>
                    <p>请使用您的帐号进行登录</p>
                    <button class="ghost" id="signIn">登录</button>
                </div>
                <div class="overlay-panel overlay-right">
                    <h1>没有帐号?</h1>
                    <p>立即注册加入我们,和我们一起开始旅程吧</p>
                    <button class="ghost" id="signUp">注册</button>
                </div>
            </div>
        </div>
    </div>
    <script src="js/index.js"></script>
</body>

</html>

六、显示文件页面(index.jsp)

<%@page import="java.io.File"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@page import="org.apache.hadoop.fs.FileStatus"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎使用-Hadoop网盘</title>
<!-- 新 Bootstrap4 核心 CSS 文件 -->
<link rel="stylesheet"
	href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="icon"
	href="http://img3.imgtn.bdimg.com/it/u=1870932651,3659050372&fm=26&gp=0.jpg"
	type="image/x-icon">
<link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet">
</head>
<body class="container" >

<%
FileStatus[] list = (FileStatus[]) request.getAttribute("list");
String name = (String) session.getAttribute("username");
String result;
if (list.length != 0) {
	result = list[0].getPath().getParent().toString().substring(22);
}else{
	result = name;
}
//
%>
<%
String PATH=(String)request.getAttribute("filePath");

if (PATH==null){
	PATH="/"+name;
}
File file=new File(PATH);
String PATH1=file.getParent();
if (PATH1==null){
	PATH1="/"+name;
}
//request.setAttribute("PATH", PATH);
%>

	<nav class="navbar navbar-expand-lg navbar-light bg-light mt-5">
		<a class="navbar-brand" href="#">Hadoop网盘</a>
		<button class="navbar-toggler" type="button" data-toggle="collapse"
			data-target="#navbarSupportedContent"
			aria-controls="navbarSupportedContent" aria-expanded="false"
			aria-label="Toggle navigation">
			<span class="navbar-toggler-icon"></span>
		</button>	

		<a> <input  class="form-control mr-sm-2 col-5" type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索..."> </a>
		<a class="nav-link col-3">当前路径:<%=PATH %></a>
			<form class="form-inline my-2 my-lg-0" action="UserCreDicServlet?PATH=<%=PATH %>" method="post" >
				<input class="form-control mr-sm-2 col-5" type="text"
					placeholder="输入文件夹名称" name="mkdir">
				<button class="btn btn-outline-success my-2 my-sm-0" type="submit">创建</button>
			</form>
	
			<form action="UserCopyServlet?PATH=<%=PATH %>" method="post" enctype="multipart/form-data">
			<div class="row">
			
			<div  class="col-8">
			<input type="file"
				class="filestyle" data-badgeName="badge-danger" data-badge="true" data-placeholder="未选择文件"
				data-text="点击上传文件" name="file1"> 
			</div>
			<div class="col-3 ml-0 pl-0">
			<button 
				class="btn btn-secondary my-2 my-sm-0" type="submit" >提交</button>
			</div>

	
			</div>
			</form>
			
			
	
	</nav>
	<table id="myTable" class="table table-hover " style="text-align: center">
		<thead class="thead-dark">
			<tr>
				<th scope="col">序号</th>
				<th scope="col">文件名</th>
				<th scope="col">属性</th>
				<th scope="col">大小</th>
				<th scope="col">可执行操作</th>
			</tr>
		</thead>
		<%String cut=(String) request.getAttribute("cut"); %>
		<tbody>
			<%
			
			if (list != null) {

				for (int i = 0; i < list.length; i++) {
			%>
			<tr>
				<%
					out.print("" + (i + 1) + "");
				if (list[i].isDir())//DocumentServlet
				{
					out.print("+"/"+result+"/"+list[i].getPath().getName()+"&&cut="+cut+"\">"+list[i].getPath().getName()+">");
		
				} else {
					out.print(""+list[i].getPath().getName()+"");
				}
				%>
				<td><%=(list[i].isDir() ? "目录" : "文件")%></td>
				<td><%=(list[i].getLen())%></td>
				
				<td><a role='button' class='btn btn-outline-success' aria-pressed='true' href="/Test-BigData/UserDownServlet?oldPath=<%=(list[i].getPath().getName()) %>&&name=<%=name %>&&result=<%=result %>&&isDir=<%=list[i].isDir() %>" class="btn btn-primary"><i class='fa fa-sign-in mr-1' aria-hidden='true'></i>下载</a>;
				 <a role="button" class="btn btn-outline-danger"
					aria-pressed="true"
					 href="javascript: if(window.confirm('是否删除?')){window.location.href='/Test-BigData/UserDeleteServlet?deletePath=<%= (list[i].getPath().getName()) %>&&name=<%=name %>&&result=<%=result %>'}">删除</a>
				
				<%
			 if (cut == null||cut.equals("null")) {
			 	out.print(" ");
			 } else if (!cut.equals("null")&&cut != null && list[i].isDir()) {
			 	out.print("粘贴");
		 }
 %>			
				</td>
				
			<tr>
				<%
					}
				}
				if (list.length == 0) {
					out.print("没有任何文件哦");
				}
				%>
	</table>
	<div class="row">
		<div class="col-3 offset-9">
		<div class="row">
		<a role="button" class="btn btn-outline-secondary col-6 mr-1" href="/Test-BigData/DirShowFilesServlet?filePath=<%=PATH1 %>&&name=<%=name %>" class="btn btn-danger"><i class="fa fa-arrow-left" aria-hidden="true"></i>返回上一级</a>
		<a class="btn btn-danger col-4" href="javascript: if(window.confirm('是否注销?')){window.location.href='login.jsp'}" role="button">注销登录</a>
		</div>
		
		</div>
	</div>
	

	
</body>
<footer>
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<!-- 搜索功能js -->
	<script>
	function myFunction() {
		  // 声明变量
		  var input, filter, table, tr, td, i;
		  input = document.getElementById("myInput");
		  filter = input.value.toUpperCase();
		  table = document.getElementById("myTable");
		  tr = table.getElementsByTagName("tr");
		 
		  // 循环表格每一行,查找匹配项
		  for (i = 0; i < tr.length; i++) {
		    td = tr[i].getElementsByTagName("td")[0];
		    if (td) {
		      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
		        tr[i].style.display = "";
		      } else {
		        tr[i].style.display = "none";
		      }
		    } 
		  }
		}
	</script>

	<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
	<script
		src="https://cdn.bootcdn.net/ajax/libs/bootstrap-filestyle/2.1.0/bootstrap-filestyle.js"></script>
	<!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
	<script  src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
	
	<script
		src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
	<script type="text/javascript">
		// get
		$(":file").filestyle({
		   'onChange': function (files) {
		      console.log(files)
		   }
		}
		$(":file").filestyle({text: "Find file"});
		</script>
		</script>
		<script type="text/javascript" color="100,50,100" opacity='1' zIndex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.1/canvas-nest.min.js"></script>
</footer>
</html>




你可能感兴趣的:(JavaWeb开发的Hadoop网盘(3))