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盘时,都是一个超链接
点击后转到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 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 queryFile(String act,HttpServletResponse resp,HttpServletRequest req) {
Map map = new HashMap<>();
File file = new File(act);
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i = 0; i0){
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;
}
}
<%--
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" %>
File Action
<%--
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+"/";
%>
Title
<%--
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" %>
Title
请选择文件夹
<%--
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+"/";
%>
Title