java中级学完之后就可以自己写一些小项目,比如一些博客、商城。用到的技术也只是Servlet+JSP,练习才是最好的老师。下面介绍一个最简单的练手项目,模仿windows的文件管理,功能比较单一。就是输入地址http://localhost:8080/file/index会进入写好的首页,然后有C,E,F盘,点击每个磁盘会去读取磁盘下的文件展示在右边的空白处,显示的内容也是一个个超链接,可以继续点击,如果是文件夹继续展示,如果是文件就会进行下载。其中会进行日志记录,每一次点击操作(查看文件夹、下载文件)都会记录在数据库中。效果图如下,前台就是简单的JSP页面,一个主页面包含左右两个JSP。
项目目录结构如下图
整个实现流程是:首先输入http://localhost:8080/file/index网址进入IndexController直接转发到file.jsp页面,就是我们的首页。当继续点击C、E、F盘时,都是一个超链接
<a href="file?act=c:/" target="body">系统保留(C:)</a> <br>
点击后转到FileController进行处理,拿到请求参数act(也就是需要查询的盘符C:/),调用FileService类中的处理方法,判断该文件是目录还是文件,如果是目录就查出所有文件并返回,返回的是一个Map,key值放入文件名,value放入文件路径作为下次点击请求的act参数。如果是文件就进行下载。下面是每个类的源码:
package gtja.controller;
import gtja.service.FileService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/index")
public class IndexController extends HttpServlet {
FileService fileService = new FileService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("jsp/file.jsp").forward(req,resp);
}
}
package gtja.controller;
import gtja.service.FileService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@WebServlet(urlPatterns = "/file")
public class FileController extends HttpServlet {
FileService fileService = new FileService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String act = req.getParameter("act");
Map<String,String> fileList = fileService.queryFile(act,resp,req);
req.setAttribute("fileList",fileList);
//resp.sendRedirect("right.jsp");
req.getRequestDispatcher("jsp/right.jsp").forward(req,resp);
}
}
package gtja.service;
import gtja.util.MyUtil;
import gtja.vo.FileLog;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class FileService {
static FileLog fileLog = new FileLog();
//private static Logger logger = Logger.getLogger(FileService.class);
public Map<String,String> queryFile(String act,HttpServletResponse resp,HttpServletRequest req) {
Map<String,String> map = new HashMap<>();
File file = new File(act);
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i = 0; i<files.length; i++){
String str = files[i].toString();
String key = str.substring(str.lastIndexOf("\\")+1);
map.put(key,str.replace("\\","/"));
}
//日志记录
myJDBC(req,"查看文件夹");
}else{
FileInputStream in = null;
OutputStream out = null;
try {
resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(act, "UTF-8"));
in = new FileInputStream(file);
out = resp.getOutputStream();
}catch (Exception e){
e.printStackTrace();
}
byte[] buffer = new byte[1024];
int len = 0;
try {
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
myJDBC(req,"下载文件");
}
return map;
}
public static void myJDBC(HttpServletRequest req ,String a){
fileLog.setIp(FileService.getIpAddress(req));
fileLog.setAction(a);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
fileLog.setTime(df.format(new Date()));
String sql = "insert into db_log(ip,action,time) values(?,?,?) ";
Connection conn = MyUtil.getConnection();
PreparedStatement ps = null;
try {
ps= conn.prepareStatement(sql);
ps.setString(1,fileLog.getIp());
ps.setString(2,fileLog.getAction());
ps.setString(3,fileLog.getTime());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}
MyUtil.closeResouce(conn);
}
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
package gtja.util;
import java.sql.*;
public class MyUtil {
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1874");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void closeResouce(Connection conn){
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static boolean isEmpty(String str){
boolean flag = false;
if(null==str||"".equals(str)){
flag = true;
}
return flag;
}
}
file.jsp
<%--
Created by IntelliJ IDEA.
User: gm
Date: 2017/10/24
Time: 9:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>File Action</title>
<style type="text/css">
*{
font-size:10pt;
}
body{
text-align:center;
}
.table{
width:1024px;
height:100%;
border:1px solid gray;/*固定边框,1像素*/
border-collapse: collapse;/*单线的列表边框*/
}
.table td{
border:1px solid gray;/*固定边框,1像素*/
}
iframe {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<table class="table" align="center">
<tr>
<td width="120" style="padding:5px;" align="center" valign="top">
<iframe frameborder="0" scrolling="no" width="120" src="<c:url value='/jsp/left.jsp'/>" name="left"></iframe>
</td>
<td>
<iframe frameborder="0" scrolling="no" src="<c:url value='/jsp/body.jsp'/>" name="body"></iframe>
</td>
</tr>
</table>
</body>
</html>
left.jsp
<%--
Created by IntelliJ IDEA.
User: gm
Date: 2017/10/24
Time: 14:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>Title</title>
</head>
<body>
<div id="menu" style="background-color:#FFE4C4;height:1000px;width:150px;float:left;">
<br>
<a href="file?act=c:/" target="body">系统保留(C:)</a> <br>
<br>
<a href="file?act=e:/" target="body">新加卷(E:)</a> <br>
<br>
<a href="file?act=f:/" target="body">新加卷(F:)</a> <br>
</div>
</body>
</html>
body.jsp
<%--
Created by IntelliJ IDEA.
User: gm
Date: 2017/10/24
Time: 15:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>请选择文件夹</h2>
</body>
</html>
right.jsp
<%--
Created by IntelliJ IDEA.
User: gm
Date: 2017/10/24
Time: 14:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>Title</title>
</head>
<body>
<div id="content" style="background-color:#EEEEEE;height:1000px;width:950px;">
<c:if test="${!empty fileList }">
<c:forEach var="list" items="${fileList }" >
<a href="file?act=${list.value}">${list.key}</a> <br>
</c:forEach>
</c:if>
</div>
</body>
</html>