曲不为直终必弯,养狼当犬看家难,墨染鸬鹚黑不久,粉刷乌鸦白不坚,
蜜饯黄莲终清苦,强摘瓜果不能甜,好事总得善人做,那有凡人做神仙!


准备工作:JSP JSTL EL JS/JQUERY

Servlet JavaBean

JDBC —》Mybatis MySQL

这里写图片描述

这里写图片描述

案例演示

这里写图片描述

页面跳转

这里写图片描述

这里写图片描述

项目路径:文章最后会给出完整项目示例代码

这里写图片描述

web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MicroMessage</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
   <servlet-name>ListServlet</servlet-name>
   <servlet-class>com.imooc.servlet.ListServlet</servlet-class>
  </servlet>

  <servlet-mapping>
   <servlet-name>ListServlet</servlet-name>
   <url-pattern>/List.action</url-pattern>
  </servlet-mapping>
</web-app>

list.jsp文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%
  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="" id="mainForm" method="post">
            <div class="right">
                <div class="current">当前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">内容管理</a> &gt; 内容列表</div>
                <div class="rightCont">
                    <p class="g_title fix">内容列表 <a class="btn03" href="#">新 增</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn03" href="#">删 除</a></p>
                    <table class="tab1">
                        <tbody>
                            <tr>
                                <td width="90" align="right">演示字段1:</td>
                                <td>
                                    <input type="text" class="allInput" value=""/>
                                </td>
                                <td width="90" align="right">演示字段2:</td>
                                <td>
                                    <input type="text" class="allInput" value=""/>
                                </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>演示字段1</th>
                                    <th>演示字段2</th>
                                    <th>操作</th>
                                </tr>
                                <tr>
                                    <td><input type="checkbox" /></td>
                                    <td>1</td>
                                    <td>演示值1</td>
                                    <td>演示值2</td>
                                    <td>
                                        <a href="#">修改</a>&nbsp;&nbsp;&nbsp;
                                        <a href="#">删除</a>
                                    </td>
                                </tr>
                                <tr style="background-color:#ECF6EE;">
                                    <td><input type="checkbox" /></td>
                                    <td>2</td>
                                    <td>演示值1</td>
                                    <td>演示值2</td>
                                    <td>
                                        <a href="#">修改</a>&nbsp;&nbsp;&nbsp;
                                        <a href="#">删除</a>
                                    </td>
                                </tr>
                                <tr>
                                    <td><input type="checkbox" /></td>
                                    <td>3</td>
                                    <td>演示值1</td>
                                    <td>演示值2</td>
                                    <td>
                                        <a href="#">修改</a>&nbsp;&nbsp;&nbsp;
                                        <a href="#">删除</a>
                                    </td>
                                </tr>
                                <tr style="background-color:#ECF6EE;">
                                    <td><input type="checkbox" /></td>
                                    <td>4</td>
                                    <td>演示值1</td>
                                    <td>演示值2</td>
                                    <td>
                                        <a href="#">修改</a>&nbsp;&nbsp;&nbsp;
                                        <a href="#">删除</a>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <div class='page fix'><b>4</b><a href='###' class='first'>首页</a>
                            <a href='###' class='pre'>上一页</a>
                            当前第<span>1/1</span><a href='###' class='next'>下一页</a>
                            <a href='###' class='last'>末页</a>
                            跳至&nbsp;<input type='text' value='1' class='allInput w28' />&nbsp;页&nbsp;
                            <a href='###' class='go'>GO</a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </body>
</html>

ListServlet.java类

package com.imooc.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 列表页面初始化控制
 */
@SuppressWarnings("serial")
public class ListServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        this.doGet(req, resp);
    }
}

数据库连接

这里写图片描述

对应下面的字段

这里写图片描述

创建bean包,Message.java实体类

package com.imooc.bean;

/*
 * 与消息表对应的实体类
 */
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;
    }
}

ListServlet.java增加

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/micro_message","root","root");
            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);
    }

数据展示

修改list.jsp文件,使用JSTL进行数据导入,eclipse可以参考JSTL+EL JSP常用标签 进行配置

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%
    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="" id="mainForm" method="post">
        <div class="right">
            <div class="current">
                当前位置:<a href="javascript:void(0)" style="color: #6E6E6E;">内容管理</a>
                &gt; 内容列表
            </div>
            <div class="rightCont">
                <p class="g_title fix">
                    内容列表 <a class="btn03" href="#">新 增</a>&nbsp;&nbsp;&nbsp;&nbsp;<a
                        class="btn03" href="#">删 除</a>
                </p>
                <table class="tab1">
                    <tbody>
                        <tr>
                            <td width="90" align="right">演示字段1:</td>
                            <td><input type="text" class="allInput" value="" /></td>
                            <td width="90" align="right">演示字段2:</td>
                            <td><input type="text" class="allInput" value="" /></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>
                                <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>&nbsp;&nbsp;&nbsp; <a href="#">删除</a>
                                    </td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                    <div class='page fix'><b>4</b><a href='###' class='first'>首页</a> <a href='###'
                            class='pre'>上一页</a> 当前第<span>1/1</span><a href='###'
                            class='next'>下一页</a> <a href='###' class='last'>末页</a> 跳至&nbsp;<input
                            type='text' value='1' class='allInput w28' />&nbsp;页&nbsp; <a
                            href='###' class='go'>GO</a>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

同时需要在lib文件下添加mysql-connector-java-5.1.18-bin.jar包,会再文章最后的参考示例中的下载链接中给出

这里写图片描述

这里写图片描述

列表查询

修改list.jsp

这里写图片描述

这里写图片描述

修改ListServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            String command = req.getParameter("command");
            String description = req.getParameter("description");
            req.setAttribute("command", command);
            req.setAttribute("description", description);
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/micro_message","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 statement = conn.prepareStatement(sql.toString());
            for(int i=0;i< paramList.size();i++) {
                   statement.setString(i+1, paramList.get(i));
            }

            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);
    }

代码重构

ListServlet.java类

package com.imooc.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.bean.Message;
import com.imooc.service.ListService;

/*
 * 列表页面初始化控制
 */
@SuppressWarnings("serial")
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 {

        this.doGet(req, resp);
    }
}

新建dao层
新建MessageDao.java类

package com.imooc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.imooc.bean.Message;

/*
 * 和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 = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/micro_message", "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 statement = conn.prepareStatement(sql.toString());
            for (int i = 0; i < paramList.size(); i++) {
                statement.setString(i + 1, paramList.get(i));
            }

            ResultSet rs = statement.executeQuery();

            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"));
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return messageList;
    }
}

新建service层
新建ListService.java类

package com.imooc.service;

import java.util.List;

import com.imooc.bean.Message;
import com.imooc.dao.MessageDao;

/*
 * 列表相关的业务功能
 */
public class ListService {

    public List<Message> queryMessageList(String command, String description) {
        MessageDao messageDao = new MessageDao();

        return messageDao.queryMessageList(command, description);
    }
}

Mybatis的下载并搭建核心架构

Mybatis下载地址
https://github.com/mybatis/mybatis-3/releases

下载如下图所示的文件

这里写图片描述

将下载好的架包放在工程的lib文件下

这里写图片描述

这里写图片描述

参考下载的演示版配置文件

这里写图片描述

这里写图片描述

新建com.imooc.config包,专门放置配置文件,把上图中的文件拷贝至其中

在配置文件中找到相关配置,并将jdbc的设置代码(我们在MessageDao.java类中设置过的)拷贝到其中

这里写图片描述

这里写图片描述

并将暂时用不到的配置注释掉

这里写图片描述

这里写图片描述

创建com.imooc.db数据库连接层

新建DBAccess.java类

package com.imooc.db;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/*
 * 访问数据库类
 */
public class DBAccess {

    public SqlSession getSqlSession() throws IOException {
        //通过配置文件获取数据库连接信息
        Reader reader = Resources.getResourceAsReader("com/imooc/config/Configuration.xml");
        //通过配置信息构建一个SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //通过SqlSessionFactory打开一个数据库会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

修改MessageDao.java层

使用Mybatis方式连接数据库

package com.imooc.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.imooc.bean.Message;
import com.imooc.db.DBAccess;

/*
 * 和message表相关的数据库操作
 */
public class MessageDao {
    /*
     * 根据查询条件查询消息列表
     */
    public List<Message> queryMessageList(String command, String description) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            //通过sqlSeesion执行SQL语句

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        MessageDao messageDao = new MessageDao();
        messageDao.queryMessageList("", "");
    }
}

SQL基本配置与执行

在com.imooc.config目录下创建子目录

这里写图片描述

从Configuration.xml的同级目录下复制User.xml文件至com.imooc.config.sqlxml下

这里写图片描述

这里写图片描述

然后把User.xml重命名为Message.xml

完善Message.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Message">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="BOOLEAN" property="content"/>
  </resultMap>

  <select id="queryMessageList" resultMap="MessageResult">
    SELECT ID,COMMAND,DESCRIPTION,CONTENT FROM MESSAGE WHERE 1=1
  </select>

</mapper>

完善MessageDao.java类

package com.imooc.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.imooc.bean.Message;
import com.imooc.db.DBAccess;

/*
 * 和message表相关的数据库操作
 */
public class MessageDao {
    /*
     * 根据查询条件查询消息列表
     */
    public List<Message> queryMessageList(String command, String description) {
        DBAccess dbAccess = new DBAccess();
        List<Message> messageList = new ArrayList<Message>();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            //通过sqlSeesion执行SQL语句
            messageList = sqlSession.selectList("Message.queryMessageList");//这里的Message是配置文件中的namespace

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
        return messageList;
    }
}

动态SQL拼接

这里写图片描述

这里写图片描述

完善Message.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Message">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>

  <select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
    SELECT ID,COMMAND,DESCRIPTION,CONTENT FROM MESSAGE WHERE 1=1
    <if test="command != null and !&quot;&quot;.equals(command.trim())">
      AND COMMAND=#{command}
    </if>

    <if test="description != null and !&quot;&quot;.equals(description.trim())">
      AND DESCRIPTION LIKE '%' #{description} '%'
    </if>
  </select>

</mapper>

完善MessageDao.java代码

package com.imooc.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.imooc.bean.Message;
import com.imooc.db.DBAccess;

/*
 * 和message表相关的数据库操作
 */
public class MessageDao {
    /*
     * 根据查询条件查询消息列表
     */
    public List<Message> queryMessageList(String command, String description) {
        DBAccess dbAccess = new DBAccess();
        List<Message> messageList = new ArrayList<Message>();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            Message message = new Message();
            message.setCommand(command);
            message.setDescription(description);

            //通过sqlSeesion执行SQL语句
            messageList = sqlSession.selectList("Message.queryMessageList",message);//这里的Message是配置文件中的namespace

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
        return messageList;
    }
}

应用log4j调试动态SQL

首先把配置文件和架包复制到工程里面,没有的话到最后的工程源码中找。

这里写图片描述

log4j.properties配置文件

log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

这里写图片描述

log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
//%d产生日志的时间,
%t是产生日志所处的线程名称,
%-5p输出日志的级别,将占5位字符,不足5位用空格填补,-指的是在右边补齐,
%c你输出日志的包以及类的全名,
%m是你附加的信息
%n是换行

配置完毕进行测试
这里写图片描述

这里写图片描述

实现单条信息删除

Message.xml新增代码

<delete id="deleteOne">
   DELETE FROM MESSAGE WHERE ID = #{_parameter}
</delete>

MessageDao.java新增代码

     /*
     * 单条删除
     */
    public void deleteOne(int id) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            //通过sqlSeesion执行SQL语句
            sqlSession.selectList("Message.deleteOne",id);//这里的Message是配置文件中的namespace
            sqlSession.commit();//主动提交
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
    }

新增MaintainService.java维护Service层

package com.imooc.service;

import com.imooc.dao.MessageDao;

/*
 * 维护相关的业务功能
 */
public class MaintainService {

    /*
     * 单条删除
     */
    public void deleteOne(String id) {
        if(id !=null && !"".equals(id.trim())) {
            MessageDao messageDao = new MessageDao();
            messageDao.deleteOne(Integer.valueOf(id));
        }       
    }
}

新增DeleteOneServlet.java 删除单条Servlet层

package com.imooc.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.service.ListService;
import com.imooc.service.MaintainService;

/*
 * 单条删除控制层
 */
@SuppressWarnings("serial")
public class DeleteOneServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("UTF-8");
        //接受页面的值
        String id = req.getParameter("id");

        MaintainService  maintainService = new MaintainService();
        maintainService.deleteOne(id);
        //向页面跳转
        req.getRequestDispatcher("/List.action").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        this.doGet(req, resp);
    }
}

web.xml文件新增代码

 <servlet>
   <servlet-name>DeleteOneServlet</servlet-name>
   <servlet-class>com.imooc.servlet.DeleteOneServlet</servlet-class>
  </servlet>

  <servlet-mapping>
   <servlet-name>DeleteOneServlet</servlet-name>
   <url-pattern>/DeleteOneServlet.action</url-pattern>
  </servlet-mapping>

修改list.jsp文件

这里写图片描述

执行顺序为list.jsp 使用web.xml配置的“servlet”项,<servlet-class>com.imooc.servlet.DeleteOneServlet</servlet-class> 进入DeleteOneServlet.java Servlet层,通过Servlet层maintainService.deleteOne(id); 调用MaintainService.java Service层deleteOne ,通过Service层messageDao.deleteOne(Integer.valueOf(id)); 调用 Dao层
MessageDao.java 通过Dao层sqlSession.delete("Message.deleteOne",id); 调用Message.xml配置文件使用SQL语句

JavaWeb MVC框架中Controller层的具体划分:
Action层:接受View层的值、调用Service层进行查询、进行传值、跳转到下一个View或者Action层
Service层:接受Action层调用进行业务逻辑判断操作,非空检验,算法等处理,调用DAO层返回数据库连接访问的结果。
Dao层:接受Service层调用,进行数据库的操作,一般分为数据库查询和数据库操作2种类型。其底层可划分出DB层通过JDBC、Mybatis、Hibernate等数据库连接操作框架进行数据库连接访问操作
DB层:负责获取连接、加载驱动,并为Dao层实现对象与数据库的交互和Sql语句执行

实现信息批量删除

Message.xml新增

<delete id="deleteBatch" parameterType="java.util.List">
   DELETE FROM MESSAGE WHERE ID in(
     <foreach collection="list" item="item" separator=",">
       #{item}
     </foreach>
   )
   </delete>

MessageDao.java新增

/*
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            //通过sqlSeesion执行SQL语句
            sqlSession.delete("Message.deleteBatch",ids);//这里的Message是配置文件中的namespace
            sqlSession.commit();//主动提交
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(sqlSession !=null){
                sqlSession.close();
            }
        }
    }

MaintainService.java新增

    /*
     * 批量删除
     */
    public void deleteBatch(String[] ids) {

        MessageDao messageDao = new MessageDao();
        List<Integer> idList = new ArrayList<Integer>();
        for(String id:ids) {
            idList.add(Integer.valueOf(id));
        }
        messageDao.deleteBatch(idList);
    }

新建DeleteBatchServlet.java

package com.imooc.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.service.MaintainService;

/*
 * 批量删除控制层
 */
@SuppressWarnings("serial")
public class DeleteBatchServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("UTF-8");
        //接受页面的值
        String[] ids = req.getParameterValues("id");

        MaintainService  maintainService = new MaintainService();
        maintainService.deleteBatch(ids);
        //向页面跳转
        req.getRequestDispatcher("/List.action").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        this.doGet(req, resp);
    }
}

web.xml新增

<servlet>
   <servlet-name>DeleteBatchServlet</servlet-name>
   <servlet-class>com.imooc.servlet.DeleteBatchServlet</servlet-class>
  </servlet>

  <servlet-mapping>
   <servlet-name>DeleteBatchServlet</servlet-name>
   <url-pattern>/DeleteBatchServlet.action</url-pattern>
  </servlet-mapping>

新建js文件,list.js文件

这里写图片描述

/*
*调用后台批量删除方法
*/
function deleteBatch(basePath) {
    $("#mainForm").attr("action",basePath + "DeleteBatchServlet.action");
    $("#mainForm").submit();
}

list.jsp 修改:

导入js文件

<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" />
<script src="<%=basePath%>resources/js/jquery-1.8.0.min.js"></script>
<script src="<%=basePath%>resources/js/list.js"></script>

</head>

修改删除点击href,使用js脚本,修改临时action路径

<p class="g_title fix">
                    内容列表 <a class="btn03" href="#">新 增</a>&nbsp;&nbsp;&nbsp;&nbsp;<a
                        class="btn03" href="javascript:deleteBatch('<%=basePath %>')">删 除</a>
                </p>

修改checkbox name属性为id,value属性为${message.id}

<tr
                                    <c:if test="${status.index % 2 !=0}">style="background-color: #ECF6EE;"</c:if>>
                                    <td><input type="checkbox" name="id" value="${message.id}"/></td>
                                    <td>${status.index + 1}</td>
                                    <td>${message.command }</td>
                                    <td>${message.description }</td>
                                    <td><a href="#">修改</a>&nbsp;&nbsp;&nbsp;
                                    <!-- <a href="${basePath}DeleteOneServlet.action?id=${message.id}">删除</a>--> 
                                    <a href="javascript:judgeDelete(${message.id})">删除</a>
                                    </td>
                                </tr>

实现自动回复功能

示例代码:
https://github.com/Goddreamwt/MyBatis.git

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐