承接前文的项目。
ListServlet.java :
在doGet()方法中添加:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/message","root","123456");
String sql = "select ID,COMMAND,DESCRIPTION,CONTENT from MESSAGE";
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
List<Message>messageList = new ArrayList<Message>();
while(rs.next()){
Message message = new Message();
messageList.add(message);
message.setId(rs.getString("ID"));
message.setCommand(rs.getString("COMMAND"));
message.setDescription(rs.getString("DESCRIPTION"));
message.setContent(rs.getString("CONTENT"));
}
req.setAttribute("messageList", messageList);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, resp);
创建bean包,Message类:
package bean;
/**
* 与消息表对应的实体类 (alt+shift+j:自动添加类的文档注释)
*/
public class Message {
/*
* 主键
*/
private String id;
/*
* 指令名称
*/
private String command;
/*
* 描述
*/
private String description;
/*
* 内容
*/
private String content;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
在list.jsp中的<%%>前再添加c标签的引用:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
uri地址在c.tld文件中可以找到。
更改list.jsp文件:
<div class="zixun fix">
<table class="tab2" width="100%">
<tbody>
<tr>
<th><input type="checkbox" id="all" οnclick="checkAll(this)"/></th>
<th>序号</th>
<th>指令名称</th>
<th>描述</th>
<th>操作</th>
</tr>
<c:forEach items="${messageList}" var="message" varStatus="status">
<tr <c:if test="${status.index%2 != 0}">style='background-color:#ECF6EE;'</c:if>>
<td><input type="checkbox" /></td>
<td>${status.index + 1}</td>
<td>${message.command}</td>
<td>${message.description}</td>
<td>
<a href="#">修改</a>
<a href="#">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div class='page fix'>
发布效果图: