这是我在慕课网学习此课程的课后回顾与总结
课程地址:http://www.imooc.com/learn/154项目前端页面示例:
后端管理页面示例:
list.jsp
项目技术栈:
前期还是用JDBC,后面会用Mybatis,这样能更好更清晰的认识到Mybatis与JDBC的差别和好处项目目录:
JavaBean:Message类
public class Message {
private String id; //主键
private String command; //命令名称
private String description; //命令描述
private String content; //命令回复内容
get、set方法略.......
MessageDao类
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=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/we_chat","root","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 pre=conn.prepareStatement(sql.toString());
for(int i=0;i<paramList.size();i++){
pre.setString(i+1, paramList.get(i));
}
ResultSet rs=pre.executeQuery();
while(rs.next()){
Message message=new Message();
message.setId(rs.getString("id"));
message.setCommand(rs.getString("command"));
message.setContent(rs.getString("content"));
message.setDescription(rs.getString("description"));
messageList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageList;
}
}
ListService类
public class ListService {
public List<Message> queryMessageList(String command,String description){
MessageDao messageDao=new MessageDao();
return messageDao.queryMessageList(command, description);
}
}
ListServlet类
public class ListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码
req.setCharacterEncoding("UTF-8");
String command=req.getParameter("command");
String description=req.getParameter("description");
//向页面传值
req.setAttribute("command", command);
req.setAttribute("description", description);
ListService listService=new ListService();
req.setAttribute("messageList", listService.queryMessageList(command, description));
req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(req, resp);
}
}
数据库表结构
command表:command_content表:
message表: