我有一個servlet,我從Sql Server使用ResultSet
獲取數據。我使用 request.setAttribute("list", list); request.getRequestDispatcher("Display.jsp").forward(request, response);
在jsp中顯示爲表格。爲什麼url顯示/ ServletName,雖然顯示的是從jsp
但在Chrome的多功能框中,我看到/ ServletName而不是/JSPName.jsp。根據從servlet接收到的list
,該表使用foreach
在jsp中顯示。
這是servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection connection = null;
Statement stmt = null;
try {
StringBuffer data = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DesktopScreen","sa","sa123");
stmt = connection.createStatement();
ArrayList list = new ArrayList();
String query = "select * from ClientLogin";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String UniqueId,ClientId,RequestedDateTime,ConnectionStatus;
UniqueId = rs.getString("UniqueID");
ClientId = rs.getString("ClientId");
RequestedDateTime = rs.getString("RequestDateTime");
ConnectionStatus = rs.getString("ConnectionStatus");
BeanClass beanClass = new BeanClass();
beanClass.setUniqueId(UniqueId);
beanClass.setClientId(ClientId);
beanClass.setConnectionStatus(ConnectionStatus);
beanClass.setRequestDateTime(RequestedDateTime);
list.add(beanClass);
}
request.setAttribute("list", list);
request.getRequestDispatcher("Display.jsp").forward(request, response);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
這是Display.jsp:
<table border ="1" style="border: border-collapse">
<tr><td>UniqueId</td><td>ClientId</td><td>Request Date and Time</td><td>Connection Status</td></tr>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.getUniqueId()}</td>
<td>${item.getClientId()}</td>
<td>${item.getRequestDateTime()}</td>
<td>${item.getConnectionStatus()}</td>
</tr>
</c:forEach>
</table>
'forward'方法不會更改瀏覽器的網址。嘗試['sendRedirect'](http://www.javatpoint.com/sendRedirect() - 方法)。閱讀[JSP Servlet中的SendRedirect()和Forward()之間的區別](http://javarevisited.blogspot.com/2011/09/sendredirect-forward-jsp-servlet.html#ixzz41izgW1fO) – Braj