一、目标效果
1、能实现对数据库中的数据进行打印
这里的数据来自于数据库手动添加,暂时没有数据添加页面。隔行换色需要实现。
2、输入框能够实现查询工作
两个输入框都能单一和配合查询,描述支持模糊查询。
可以直接跳到末尾查看动图效果
二、工作准备
1、涉及的知识点
jsp/" title="查看与 JSP 相关的文章" target="_blank" style="box-sizing: inherit; -webkit-tap-highlight-color: rgba(255, 0, 0, 0); border: 0px; font-family: inherit; font-style: inherit; margin: 0px; outline: 0px; padding: 0px; vertical-align: baseline; color: rgb(47, 136, 154); text-decoration: none;">JSP
JSTL
EL
2、jar 包准备
3、开发工具
IntelliJ IDEA
Navicat Premium
三、代码实现
1、新建数据库,micro_message。再建一个表,message。表的结构如下
2、新建 Web 项目 MicroMessage
3、新建包
com.liuyanzhao.bean,存放实体类
com.liuyanzhao.servlet,存放Servlet类,实现控制,要调用 service 类
com.liuyanzhao.dao,存放数据库操作类,增查改查等方法
com.liuyanzhao.service,存放业务功能类,调用 dao 类,返回一个数据集合
4、在 WEB-INF 下新建一个 lib 文件夹,放 jar 包,然后将 jar 包添加到环境(path)中
注意:Eclipse只需要右键 Build path;
IntelliJ IDEA 可以快捷键 Ctrl+Alt+Shift+S 打开下图,选择指定项目点击右边的绿色的 + ,添加 jar包到环境中
5、依次按顺序新建下面文件
① com.liuyanzhao.bean 下新建 Message.java
package com.liuyanzhao.bean;
/**
* 与消息对应的实体类
*/
public class Message {
private int id;
private String command;
private String description;
private String content;
public Message() {
}
public int getId() {
return id;
}
public void setId(int 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;
}
}
② com.liuyanzhao.servlet 下新建 ListServlet.java
package com.liuyanzhao.servlet;
import com.liuyanzhao.service.ListService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 列表页面初始化控制
*/
public class ListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决乱码
request.setCharacterEncoding("utf-8");
//接受表单内容
String command = request.getParameter("command");
String description = request.getParameter("description");
//向页面传值
request.setAttribute("command",command);
request.setAttribute("description",description);
//业务需要
ListService listService = new ListService();
//查询消息列表并传给页面
request.setAttribute("messageList",listService.queryMessageList(command,description));
//向页面跳转
request.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
③ 在WEB-INF 下 新建 web.xml,给 Listservlet 类添加映射
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>ListServlet</servlet-name>
<servlet-class>com.liuyanzhao.servlet.ListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListServlet</servlet-name>
<url-pattern>/List.action</url-pattern>
</servlet-mapping>
</web-app>
④ 在 WEB-INF 下新建一个文件夹 名 jsp,在 jsp内新建一个文件夹 名back,在 back 下新建 list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE" />
<title>内容列表页面</title>
<link href="<%=basePath%>resources/css/all.css" rel="stylesheet" type="text/css" />
</head>
<body style="background: #e1e9eb;">
<form action="<%=basePath%>List.action" id="mainForm" method="post">
<div class="right">
<div class="current">当前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">内容管理</a> > 内容列表</div>
<div class="rightCont">
<p class="g_title fix">内容列表 <a class="btn03" href="#">新 增</a> <a class="btn03" href="#">删 除</a></p>
<table class="tab1">
<tbody>
<tr>
<td width="90" align="right">指令名称:</td>
<td>
<input name="command" type="text" class="allInput" value="${command}"/>
</td>
<td width="90" align="right">描述:</td>
<td>
<input name="description" type="text" class="allInput" value="${description}"/>
</td>
<td width="85" align="right"><input type="submit" class="tabSub" value="查 询" /></td>
</tr>
</tbody>
</table>
<div class="zixun fix">
<table class="tab2" width="100%">
<tbody>
<tr>
<th><input type="checkbox" id="all" onclick="#"/></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>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</form>
</body>
</html>
注意:
jsp 中的css样式和图片这里就不添加了,这里主要还是学习 JavaWeb,主要还是 看 form 标签之前的内容
第四行的 jstl 核心库
bathPath 是获得 根目录的路径,即 index.php的路径
${command} 和 ${description} 是 EL 表达式,通过 Servlet 传值
<c:forEach> 和 <c:if> 都是 jstl 的内容
⑤ com.liuyanzhao.dao 下新建 MessageDao.java
package com.liuyanzhao.dao;
import com.liuyanzhao.bean.Message;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 和message表相关的操作
*/
public class MessageDao {
/**
* 根据查询条件查询消息列表
*/
public List<Message> queryMessageList(String command,String description) {
List<Message> messageList = new ArrayList<Message>();
//数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/micro_message" +
"?useUnicode=true&characterEncoding=utf8","root","");
StringBuilder sql = new StringBuilder(" SELECT id,command,description,content FROM message where 1=1 ");
List<String> paramList = new ArrayList<String>();
if(command != null && !"".equals(command.trim())) {
sql.append(" and command=? ");
paramList.add(command);
}
if(description != null && !"".equals(description.trim())) {
sql.append(" and description like '%' ? '%' ");
paramList.add(description);
}
PreparedStatement ptmt = conn.prepareStatement(sql.toString());
for (int i=0;i<paramList.size();i++) {
ptmt.setString(i+1,paramList.get(i));
}
ResultSet rs = ptmt.executeQuery();
while (rs.next()) {
Message message = new Message();
messageList.add(message);
message.setId(rs.getInt("id"));
message.setCommand(rs.getString("command"));
message.setDescription(rs.getString("description"));
message.setContent(rs.getString("content"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return messageList;
}
}
注意:
第 27 行,SELECT 所有要查询的字段,不要用 SELECT *
sql 语句最好前后都加个 空格,因为空格是分隔符
第 35 行,模糊查询处,问号的两边别忘了加空格
messageList 定义在 try 外面,防止异常出现,空指针
因为我们查询的是不是单条语句,是多条的,所以用集合,而不用对象
⑥ com.liuyanzhao.service 下新建 ListService.java
package com.liuyanzhao.service;
import com.liuyanzhao.bean.Message;
import com.liuyanzhao.dao.MessageDao;
import java.util.List;
/**
*列表相关的业务功能
*/
public class ListService {
public List<Message> queryMessageList(String command, String description) {
MessageDao messageDao = new MessageDao();
return messageDao.queryMessageList(command,description);
}
}
四、运行程序
1、配置 Tomcat 服务器,并启动
2、运行结果如下