我正在尝试编写一个简单的servlet程序,只需单击HTML页面中的一个按钮,即可获取DB表中的所有详细信息并将其显示为HTML表。
但是,在单击“查看详细信息”按钮时,出现空白页。在验证URL时,可以看到正在访问Servlet,因为它更改为http://localhost:8080/WebApplication2/NewServlet1
我参考了以下教程来学习->(https://www.tutorialspoint.com/servlets/servlets-database-access.htm)
MY HTML CODE
<html>
<head>
<title>Employee Deatils</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<form action="NewServlet1" method="post">
<h1> Press button to view employee details </h1>
<input type="submit" name="view" value="VIEW DETAILS"/>
</form>
</div>
</body>
</html>
SERVLET CODE:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class NewServlet1 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:/localhost:3306/test","root","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Employees;");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet1</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border = '1' width = '100%'>\n" +
"<tr>\n" +
"<th>Emp ID</th>\n" +
"<th>First Name</th>\n" +
"<th>Last Name</th>\n" +
"<th>Age</th>\n" +
"</tr>");
while (rs.next()){
out.println("<tr>");
out.println("<td>"+rs.getInt(1)+"</td>" );
out.println("<td>"+rs.getString(3)+"</td>" );
out.println("<td>"+rs.getString(4)+"</td>");
out.println("<td>"+rs.getInt(2)+"</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
rs.close();
st.close();
conn.close();
}catch (Exception e){
e.printStackTrace();
}
}
}