简单实现从浏览器下载文件

最容易出错到点

  • JDBC连接数据库却忘记导包:mysql-connector-java-5.1.7-bin.jar
  • 使用Servlet却忘记导tomcat的包:servlet-api.jar,这个包在tomcat/lib中找到
  • 自己手写Servlet却忘记到web.xml中写配置

登陆页面实现


<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
用户名:<br> 密码:<br> form> body> html>

登陆对应的Servlet

package vipdownload;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login_Servlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 制定编码表
		resp.setContentType("text/html;charset=utf-8");

		// 获取页面登录名与密码
		ArrayList<String> list = new ArrayList<>();
		Enumeration<String> parameterNames = req.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String key = (String) parameterNames.nextElement();
			list.add(req.getParameter(key));

		}

		// 校验登录名与密码是否存在于数据库中
		Connection conne = JDBC_util.getConnetion();
		PreparedStatement pst = null;
		String sql = "select * from user where username=? && password=?";
		try {
			pst = conne.prepareStatement(sql);
			pst.setString(1, list.get(0));
			pst.setString(2, list.get(1));

			ResultSet resultSet = pst.executeQuery();

			if (resultSet.next()) {
				// 存在,登陆成功,跳转下载页面
				resp.setStatus(302);
				resp.setHeader("Location", "download.html");
			} else {
				// 不存在,登录失败
				resp.getWriter().write("登录失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBC_util.release(conne, pst);
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

}


注册页面


<html>
<head>
<meta charset="utf-8">
<title>会员注册title>

<script>
	//获取焦点事件
	function checkTips(spanId, msg) {
		var span = document.getElementById(spanId);
		span.innerHTML = msg;
	}

	//失去焦点事件,校验用户名
	function checkUserName() {
		var username = document.getElementById("username").value;
		var span = document.getElementById("span_username");
		if (username.length > 13 || username.length < 3) {
			span.innerHTML = "用户名长度不符合";
		} else {
			span.innerHTML = "用户名可用";
			return true;
		}

	}

	//失去焦点事件,校验密码
	function checkPassWord() {
		var password = document.getElementById("password").value;
		var span = document.getElementById("span_password");
		if (password.length < 6) {
			span.innerHTML = "密码长度小于6位";
		} else {
			span.innerHTML = "密码可用";
			return true;
		}
	}

	//失去焦点事件,校验确认密码
	function checkRePassWord() {
		var repassword = document.getElementById("repassword").value;
		var password = document.getElementById("password").value;
		var span = document.getElementById("span_repassword");
		if (password == repassword) {
			span.innerHTML = "密码一致"
			return true;
		} else {
			span.innerHTML = "密码不一致"
		}
	}

	//表单提交事件
	function checkFrom() {
		var flag = checkUserName() && checkPassWord() && checkRePassWord();
		if (flag) {
			return flag;
		}
		return false;
	}
script>

head>
<body>
	<form action="Register_Servlet" method="get" onsubmit="checkFrom()">
		用户名:<input type="text" id="username" name="username"
			onfocus="checkTips('span_username','用户名取值为3-12个字符')"
			onblur="checkUserName()" onkeyup="checkUserName()"><span id="span_username">span><br> 
			
		密码:<input type="text" name="password"
			id=password onfocus="checkTips('span_password','密码长度必须大于等于6')"
			onblur="checkPassWord()" onkeyup="checkPassWord()"><span id="span_password">span><br> 
			
		确认密码:<input type="text" name="repassword"
			id=repassword onfocus="checkTips('span_repassword','密码必须一致')"
			onkeyup="checkRePassWord()" onblur="checkRePassWord()"><span id="span_repassword">span><br> 
			
		<input type="submit" value="注册">
	form>

body>
html>

注册对应到Servlet

package vipdownload;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//注册校验

public class Register_Servlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 判断用户名是否符合规则
		resp.setContentType("text/html;charset=utf-8");

		// 获取数据连接对象
		Connection conne = JDBC_util.getConnetion();
		
		//数据库操作对象
		PreparedStatement pst = null;
		
		//数据库返回数据对象
		ResultSet rs = null;
		
		
		try {
			
			//sql查询语句
			String sql = "select * from user where username=?";
			
			//预处理sql语句
			pst = conne.prepareStatement(sql);
			
			//设置第一个?的值
			pst.setString(1, req.getParameter("username"));
			System.out.println(req.getParameter("username"));
			
			//获取数据库返回值
			rs = pst.executeQuery();
			
			//判断是否存在数据
			if (rs.next()) {
				resp.getWriter().write("用户名已存在!");
			} else {
				resp.getWriter().write("注册成功!");
				
				//将注册信息存储到数据库
				String username = req.getParameter("username");
				String password = req.getParameter("password");
				
				//SQL语句
				String insertSQL = "insert into user values(null,?,?,null)";
				
				PreparedStatement pst2 = conne.prepareStatement(insertSQL);
				
				//给占位符赋值
				pst2.setString(1, username);
				pst2.setString(2, password);
				
				//将数据插入数据库
				pst2.executeUpdate();
				
				
				//重新定向url
				resp.setStatus(302);

				//指向新到url地址
				resp.setHeader("Location", "download.html");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//释放资源
			JDBC_util.release(conne, pst, rs);
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}

下载页面


<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
head>
<body>
我很幸福.mkva><br>
歌词.cfga><br>
美女.jpga><br>
body>
html>

下载页面对应的Servlet

package vipdownload;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoad_Servlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//		resp.setContentType("text/html;charset=utf-8");

		// 获取页面元素对应到文件名
		String filename = req.getParameter("name");

		// 获取文件在tomcat中到绝对路径
		String path = getServletContext().getRealPath("DownLoad/" + filename);

		// 设置编码格式,get带过来到是UTF-8格式的,tomcat向客户端写出时ISO-8859-1格式的
//		filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
		
		//效果同上
		filename = URLEncoder.encode(filename, "UTF-8");

	/*	// 获取浏览器类型
		String clientType = req.getHeader("User-Agent");

		// 根据不同的浏览器设置编码表
		if (clientType.contains("Firefox")) {
			// 如果浏览器是Firefox火狐

			BASE64Encoder base64Encoder = new BASE64Encoder();
			
			filename = "=?UTF-8?B?" + new String(base64Encoder.encode(filename).getBytes("UTF-8")) + "?=";
			
		} else {
			// 如果浏览器实IE或者chrome
			filename = URLEncoder.encode(filename, "UTF-8");
		}*/

		// 设置响应头,告知浏览器下载文件
		resp.setHeader("Content-Disposition", "attachment;filename=" + filename);

		// 下载文件
		InputStream is = new FileInputStream(path);

		OutputStream os = resp.getOutputStream();
		byte[] arr = new byte[1024 * 8];
		int len = 0;

		while ((len = is.read(arr)) != -1) {
			os.write(arr, 0, len);
		}

		os.close();
		is.close();

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);

	}
}

你可能感兴趣的:(我的笔记)