servlet实现jsp列表的搜索框

这里我们对一个列表的信息进行搜索,根据姓名 部门
在这里插入图片描述用到的工具和jsp的位置
在这里插入图片描述

jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>Title</title>
    <style type="text/css">
        table{
            background: dimgrey;
            margin: auto;
            width: 40%;
        }
        th,td{
            background: white;
        }
    </style>
</head>
<body>

 <table>
     <tr>
        <td colspan="6">
            <form action="${pageContext.request.contextPath}/FindServlet" method="post" style="margin: auto">
            姓名:<input type="text" name="name">
            部门:<select id="dept" name="deptno">
                    <option value="0">请选择</option>
                </select>
            <input type="submit" value="搜索">
        </form>
        </td>
     </tr>
     <tr>
         <th>id</th>
         <th>姓名</th>
         <th>工作</th>
         <th>部门编号</th>
         <th>部门名称</th>
         <th>操作</th>
     </tr>
     <c:forEach items="${emps}" var="e">
         <tr align="center">
             <td>${e.empno}</td>
             <td>${e.ename}</td>
             <td>${e.job}</td>
             <td>${e.dept.deptno}</td>
             <td>${e.dept.dname}</td>
             <td><a href="javascript:del(${e.empno})">删除</a>&nbsp;&nbsp;
                 <a href="${pageContext.request.contextPath}/Servlet?method=edit&id=${e.empno}">修改</a> </td>
         </tr>
     </c:forEach>
 </table>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.1.0.min.js" ></script>
<script type="text/javascript">
    文档加载时,就执行 该函数
    $(function () {//这里是部门下拉框的数据显示
        //alert(11);
        $.ajax({
            url:'${pageContext.request.contextPath}/Servlet?method=findDepts',
            type:'get',
            dataType:'json',
            success:function (data) {   //data保存回调数据
                //alert(data);
                //[{},{},{}]
                $(data).each(function (index,item) {    // index索引 ,item 被查询出来的对象 dept
                    $("#dept").append("<option value='"+item.deptno+"'>"+item.dname+"</option>")
                });
            }

        });
    });
   
    //列表的删除
    function del(id) {
        if(confirm("确认删除吗")){
            window.location.href="${pageContext.request.contextPath}/Servlet?method=del&id="+id;
        }
    }
</script>
</html>

Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request,response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   	request.setCharacterEncoding("UTF-8");
 	EmpService es=new EmpServiceImpl();
	//查询所有部门的数据
	List<Dept> d=es.fineD();//这里在数据库里获取所有部门信息,用于部门下拉显示
	String json = JSON.toJSONString(d);
	//将json写入客户端
	PrintWriter writer = response.getWriter();
	writer.print(json);//传到前端  
   }

DaoImpl

public List<Dept> findD() {
    Connection conn = db.getConnection();//获取数据库的信息
    List<Dept> depts=new ArrayList<>();//新建集合 用于接收部门信息
    try {
        PreparedStatement ps = conn.prepareStatement("select * FROM dept");//根据SQL查询部门表
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            Dept d=new Dept();
            d.setDeptno(rs.getInt("deptno"));
            d.setDname(rs.getString("dname"));
            d.setLoc(rs.getString("loc"));
            depts.add(d);
        }
        return depts;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

以上做的是搜索框下拉选项的数据显示

以下是关于搜索的显示
     比如当只输入了名字没有选择部门(只根据姓名模糊查询)
     没有输入名字只选择了部门(只根据部门查找)
     两个都没有输入(查询所有)
     两个都输入(根据姓名和部门查找)

查询的Servlet

@WebServlet("/FindServlet")
public class FindServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        Integer deptno=Integer.valueOf(request.getParameter("deptno"));
        EmpService es=new EmpServiceImpl();
        boolean b = StrUtil.isEmpty(name);//判断字符串name是否为空 如果为空返回true 不为空返回false
        if(b==true&&deptno==0){//搜索框都为空时,搜索全部
            //这里直接调用的查询所有的Servlet
            request.getRequestDispatcher("/Servlet?method=login").forward(request,response);
        }else if (b==false&&deptno==0){//根据名字搜索
           List<Emp> list= es.findByEname(name);//查询方法
           //将数据传到前台
            request.setAttribute("emps",list);
            //跳转的页面
            request.getRequestDispatcher("WEB-INF/jsp/elist.jsp").forward(request,response);
        }else if(b==true&&deptno>0){//根据deptno搜索
            List<Emp> list= es.findByDeptno(deptno);
            //将数据传到前台
            request.setAttribute("emps",list);
             //跳转的页面
            request.getRequestDispatcher("WEB-INF/jsp/elist.jsp").forward(request,response);
        }else{//两个都输入
            List<Emp> list= es.findByAll(name,deptno);
            //将数据传到前台
            request.setAttribute("emps",list);
             //跳转的页面
            request.getRequestDispatcher("WEB-INF/jsp/elist.jsp").forward(request,response);
        }

    }

}

DaoImpl
根据名字模糊查询

/**
 * 根据名字进行模糊查询
 * 搜索框的搜索名字
 * @param name
 * @return
 */
@Override
public List<Emp> findByEname(String name) {
    Connection conn = db.getConnection();
    List<Emp> emps=new ArrayList<>();
    try {
        PreparedStatement ps = conn.prepareStatement("select * from emp e,dept d where e.deptno=d.deptno and e.ename like ?");
        ps.setString(1,"%"+name+"%");
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            System.out.println();
            Emp e=new Emp();
            e.setEmpno(rs.getInt("empno"));
            e.setEname(rs.getString("ename"));
            e.setJob(rs.getString("job"));

            Dept d=new Dept();
            d.setDeptno(rs.getInt("deptno"));
            d.setDname(rs.getString("dname"));

            e.setDept(d);
            emps.add(e);
        }
        return emps;
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

根据部门id查询

/**
 * 根据部门的id进行查询
 * 用于搜索框
 * @param deptno
 * @return
 */
@Override
public List<Emp> findByDeptno(Integer deptno) {
    Connection conn = db.getConnection();
    List<Emp> emps=new ArrayList<>();
    try {
        PreparedStatement ps = conn.prepareStatement("select * from emp e,dept d where e.deptno=d.deptno and d.deptno=?");
        ps.setInt(1,deptno);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            System.out.println();
            Emp e=new Emp();
            e.setEmpno(rs.getInt("empno"));
            e.setEname(rs.getString("ename"));
            e.setJob(rs.getString("job"));

            Dept d=new Dept();
            d.setDeptno(rs.getInt("deptno"));
            d.setDname(rs.getString("dname"));

            e.setDept(d);
            emps.add(e);
        }
        return emps;
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

根据姓名和部门查找

/**
 * 根据部门和姓名查找
 * 用于搜索框回显
 * @param name
 * @param deptno
 * @return
 */
@Override
public List<Emp> findByAll(String name, Integer deptno) {
    Connection conn = db.getConnection();
    List<Emp> emps=new ArrayList<>();
    try {
        PreparedStatement ps = conn.prepareStatement("select * from emp e,dept d where e.deptno=d.deptno and e.ename like ? and d.deptno=?");
        ps.setString(1,"%"+name+"%");
        ps.setInt(2,deptno);
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            System.out.println();
            Emp e=new Emp();
            e.setEmpno(rs.getInt("empno"));
            e.setEname(rs.getString("ename"));
            e.setJob(rs.getString("job"));

            Dept d=new Dept();
            d.setDeptno(rs.getInt("deptno"));
            d.setDname(rs.getString("dname"));

            e.setDept(d);
            emps.add(e);
        }
        return emps;
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

两张表的信息 由于数据太多查询只简单的获取了几个字段
在这里插入图片描述
在这里插入图片描述

  • 6
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
实现搜索功能需要以下几个步骤: 1. 在jsp页面中添加搜索框搜索按钮,并设置表单提交方式为GET方法。例如: ``` <form action="search.jsp" method="GET"> <input type="text" name="keyword" placeholder="请输入关键字"> <button type="submit">搜索</button> </form> ``` 2. 在servlet中获取用户输入的关键字,并根据关键字查询数据库。例如: ``` String keyword = request.getParameter("keyword"); String sql = "SELECT * FROM my_table WHERE name LIKE '%" + keyword + "%'"; ResultSet rs = statement.executeQuery(sql); ``` 注意:这种拼接SQL语句的方式存在SQL注入的风险,建议使用PreparedStatement进行参数化查询,具体实现可以自行搜索学习。 3. 将查询结果封装成List或者其他数据结构,并将其存储到request中,以便在jsp页面中显示搜索结果。例如: ``` List<MyObject> resultList = new ArrayList<>(); while (rs.next()) { MyObject obj = new MyObject(); obj.setId(rs.getInt("id")); obj.setName(rs.getString("name")); // ... resultList.add(obj); } request.setAttribute("resultList", resultList); ``` 4. 在jsp页面中遍历搜索结果,并将其展示出来。例如: ``` <ul> <c:forEach items="${resultList}" var="obj"> <li>${obj.name}</li> </c:forEach> </ul> ``` 注意:这里使用了JSTL标签库来简化jsp页面的编写,需要在jsp页面头部添加以下代码: ``` <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> ``` 以上就是用jsp servlet mysql实现搜索功能的基本步骤,具体实现还需要根据自己的业务需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值