我希望将java代码(在servlet中)与html代码分开。
此代码在jsp中显示mySql表的数据。
不使用scriptlet的最佳实践是什么?
谢谢你的帮助。
<%
String id = request.getParameter("userId");
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost/";
String dbName = "db";
String userId = "root";
String password = "root";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<table>
<td style="border:none"><a href="index.jsp" class="LinkButton">home</a> <br></td>
<tr>
<th>id</th>
<th>Data</th>
.....
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);
statement=connection.createStatement();
String sql ="SELECT * FROM table";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("id") %></td>
<td><%=resultSet.getString("Data") %></td>
...
</tr>
<%
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>发布于 2018-06-20 09:34:04
使用Get方法和servlet。您可以用servlet编写所有java代码,如下所示:
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost/";
String dbName = "db";
String userId = "root";
String password = "root";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try{
connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);
statement=connection.createStatement();
String sql ="SELECT * FROM table";
resultSet = statement.executeQuery(sql);
// Now convert this result set into a class having field id and data..
// like MyClass{ String id; String data;}
// make a list of List<MyClass>list = new ArrayList<>();
request.setAttribute("list",list);
this.getServletContext().getRequestDispatcher("/jsp/yourPageName.jsp").
include(request, response);
}现在使用request.getAttribute("list");在jsp文件中获取名为"list“的属性。把它排成单子。并进行迭代并相应地打印。
发布于 2018-06-20 02:16:43
如果您只想分离java代码,那么可以使用JSTL。
<jsp:include page="somecode.jsp" />你可以在这里找到更多关于它的信息。
https://www.safaribooksonline.com/library/view/head-first-servlets/9780596516680/ch09s18.html
我认为最好将逻辑与视图完全分开,有许多框架可以帮助您实现这一点,比如Spring。如果您想在不使用任何框架的情况下实现,可以按照下面的链接进行操作。
发布于 2018-06-20 23:04:06
在没有scriptlet或JSTL的情况下,不可能循环While,即使您可以将数据库提取作业放在servlet中。
如果要删除任何服务器端脚本,则需要将体系结构划分为两层。
而且您不使用数据库连接池,而是直接建立数据库连接。挺贵的。如果你忘记关闭连接,你可能会耗尽资源。非常危险。
https://stackoverflow.com/questions/50937614
复制相似问题