JAVAWEB exercise-complete simple user login function case, complete file download

Complete user login function case

  1. Case analysis
    Step 1: Make the page first, and then submit the data to the background.
    Step 2: The background is Servlet, which contains commonly used database processing

  2. Code
    Step 1: Make a form page first

<!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>

Step 2: Writing 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();
			}
		}
	}
}

Step 3: Create a database called web13, and create a table in it, named users
Insert picture description here
Step 4: Write the content of the Servlet

@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);
	}

}

Complete file download

Analysis:
The essence of file download isFile copyTo copy files from the server to the browser. So download the file IO technology will require server-side files InputStreamread, in use ServletOutputStreamwrites response缓冲区in

  1. Question: Under what circumstances will the file be downloaded? ?
    Download files that the browser cannot parse
  2. Question: Under what circumstances need to write file download code on the server side?
    In theory, the browser can parse the code and need to write file download code. In actual development, as long as it is downloaded files, write file download code

Write an html document first

<!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();

    }

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/109160936
Recommended