模糊查询
主页新增查询功能
在GoodsDao建立模糊查询方法
public List<Goods> seach(String keyword) {
List<Goods> goodsList = new ArrayList<>();
try {
con = JDBCUtil.getCon();
String sql = "select * from t_goods where gname like concat('%',?,'%')";
ps = con.prepareStatement(sql);
ps.setObject(1,keyword);
rs = ps.executeQuery();
while (rs.next()) {
//把当前数据行中的数据取出来,存储到Goods对象中
Goods goods = new Goods();
goods.setGid(rs.getInt("gid"));
goods.setGname(rs.getString("gname"));
goods.setPrice(rs.getDouble("price"));
goods.setMark(rs.getString("mark"));
//把Goods对象存储到集合中
goodsList.add(goods);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
if(rs!=null) {
rs.close();
}
if(ps!=null) {
ps.close();
}
if(con!=null){
con.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
return goodsList;
}
查询按键进行请求
package servlet;
import bean.Goods;
import dao.GoodsDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/Seach")
public class Seach extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String keyword = req.getParameter("keyword");
//执行jdbc的模糊查询
GoodsDao goodsDao=new GoodsDao();
List<Goods> goodsList = goodsDao.seach(keyword);
//把秘糊查海到的商品信息集合存储到session中
HttpSession session = req.getSession();
session.setAttribute( "goodsList",goodsList);
//跳技到大页进行信县显示
resp.sendRedirect("zhuye.jsp");
}
}