JAVAWEB演習-単純なユーザーログイン機能のケースを完了し、ファイルのダウンロードを完了します

完全なユーザーログイン機能のケース

  1. ケース分析
    ステップ1:最初にページを作成してから、データをバックグラウンドに送信します。
    ステップ2:背景は、一般的に使用されるデータベース処理を含むサーブレットです。

  2. コード
    ステップ1:最初にフォームページを作成する

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1 style="text-align: center;">简易登陆平台</h1>
	<div style="width:100%;text-align :center">
	<form action="/WEB13_UserLogin/LoginServlet"  method="post">
		用户名:<input type="text" name="username" placeholder="请输入用户名....."><br/>
		密码:<input type="password" name="password" placeholder="请输入密码..."><br/>
		<input type="submit" value="提交">
	</form>
	</div>
</body>
</html>

ステップ2:JDBCUtilsを作成する

public class JDBCUtils {
    
    
  private static Connection conn;

  static {
    
    
	  try {
    
    
		Class.forName("com.mysql.jdbc.Driver");
		String url="jdbc:mysql:///web13";
		String username="root";
		String password="123";
		conn=DriverManager.getConnection(url,username,password);
	} catch (Exception e) {
    
    
		e.printStackTrace();
	}
	  
  }
  public static Connection getConnection() {
    
    
	  return conn;
  }
  public static void close(Connection connection,ResultSet resultSet,PreparedStatement preparedStatemnt) {
    
    
		if ( connection !=null) {
    
    
			try {
    
    
				connection.close();
			} catch (SQLException e) {
    
    
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if ( resultSet !=null) {
    
    
			try {
    
    
				resultSet.close();
			} catch (SQLException e) {
    
    
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if ( preparedStatemnt !=null) {
    
    
			try {
    
    
				preparedStatemnt.close();
			} catch (SQLException e) {
    
    
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
	public static void close(Connection connection,Statement statement) {
    
    
		if ( connection !=null) {
    
    
			try {
    
    
				connection.close();
			} catch (SQLException e) {
    
    
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		if ( statement !=null) {
    
    
			try {
    
    
				statement.close();
			} catch (SQLException e) {
    
    
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
}

ステップ3:web13という名前のデータベースを作成し、その中にusersという名前のテーブルを作成します
ここに写真の説明を挿入
ステップ4:サーブレットのコンテンツを書き込む

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    
    
	public static Connection connection =JDBCUtils.getConnection();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		response.setContentType("text/html;charset=utf-8");
		String username =request.getParameter("username");
		String password =request.getParameter("password");
		String sql ="SELECT * FROM users WHERE username='"+username+"'and password ='"+password+"'";
		try {
    
    
			Statement st =connection.createStatement();
			ResultSet rs= st.executeQuery(sql);
			if (rs.next()) {
    
    
				response.getWriter().write("登陆成功");
			}else {
    
    
				response.getWriter().write("登陆失败");
			}
			
		} catch (SQLException e) {
    
    		
			response.getWriter().write("登陆失败");
			e.printStackTrace();
		}
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		doGet(request, response);
	}

}

完全なファイルのダウンロード

分析:
ファイルダウンロードの本質はファイルコピーサーバーからブラウザーにファイルをコピーします。したがって、ファイルIOテクノロジーをダウンロードするには、サーバー側のファイルをInputStream読み取り、使用中にServletOutputStream書き込みresponse缓冲区行う必要があります。

  1. 質問:どのような状況でファイルがダウンロードされますか?
    ブラウザが解析できないファイルをダウンロードする
  2. 質問:どのような状況で、サーバー側でファイルダウンロードコードを記述する必要がありますか?
    理論的には、ブラウザはコードを解析でき、ファイルダウンロードコードを作成する必要があります。実際の開発では、ファイルをダウンロードする限り、ファイルダウンロードコードを記述します

最初にhtmlドキュメントを書く

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件下载</title>
</head>
<body>
<body>
        <h1>使用a标签直接指向服务器上的资源</h1>
        <a href="download/a.flv">a.flv</a><br/>
        <a href="download/a.mp4">a.mp4</a><br/>
        <a href="download/a.mp3">a.mp3</a><br/>
        <a href="download/a.jpg">a.jpg</a><br/>
        <a href="download/a.txt">a.txt</a><br/>
        <a href="download/a.zip">a.zip</a><br/>
        <h1>使用服务器端编码方式实现文件下载</h1>
        <a href="/DownloadServlet?filename=a.flv">a.flv</a><br/>
        <a href="/DownloadServlet?filename=a.mp4">a.mp4</a><br/>
        <a href="/DownloadServlet?filename=a.mp3">a.mp3</a><br/>
        <a href="/DownloadServlet?filename=a.jpg">a.jpg</a><br/>
        <a href="/DownloadServlet?filename=a.txt">a.txt</a><br/>
        <a href="/DownloadServlet?filename=a.zip">a.zip</a><br/>
</body>

</body>
</html>
public class DownloadServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获得需要下载的文件名称
        String filename = request.getParameter("filename");
        //要下载的这个文件的类型-------客户端通过文件的MIME类型区别文件类型
        response.setContentType(this.getServletContext().getMimeType(filename));
        //告诉客户端该文件不是直接解析而是以附件形式打开(下载)
        response.setHeader("Content-Disposition","attachment;filename="+filename);
        //获取文件的绝对路径
        String path = this.getServletContext().getRealPath("download"+filename);
        //获得该文件的输入流
        InputStream inputStream =new FileInputStream(path);
        //获得输出流--通过response获得的输出流用于向客户端写内容
        ServletOutputStream outputStream = response.getOutputStream();
        //文件拷贝的模板代码
        int len = 0;
        byte [] buffer =new byte[1024];
        while((len = inputStream.read(buffer))>0){
    
    
            outputStream.write(buffer,0,len);
        }
        inputStream.close();
        //outputStream.close();

    }

おすすめ

転載: blog.csdn.net/Mr_GYF/article/details/109160936