网上图书商城项目学习中,总结一些前后端联合的代码方便后续查阅
思路
html页面:
以from形式提交要搜索的内容
<form action="bookManager" method="get">
<input type="hidden" name="method" value="selectByBookName" />
<input type="text" placeholder="十万个为什么" name="bookName" id="bookName"/>
<button type="search" class="iconfont icon-search" ></button>
</form>
Servlet方法
调用BookManagerServlet中的selectByName方法,并将数据存储到请求域
//搜索查找图书
public void selectByBookName(HttpServletRequest request,HttpServletResponse response)throws Exception{
//获取从客户端传入的bookName
String bookName = request.getParameter("bookName");
try{
List<Book> typeList = bookService.selectBookByName(bookName);
request.setAttribute("typeList",typeList);
processTemplate("type/type",request,response);
}catch (Exception e){
e.printStackTrace();
}
}
搜索结果显示(搜索内容为“的”)
Sql语句
调用bookDaoImpl实现模糊查询
//搜索查询
@Override
public List<Book> selectBookByName(String bookName)
{ // % 为sql语句中的通配符
bookName='%'+bookName+'%';
String sql = "select book_id bookId,book_name bookName,author,price,sales,stock,img_path imgPath,book_type bookType from t_book where book_name like ?";
return getBeanList(Book.class,sql,bookName);
}
返回请求的html页面(仅参考)
<div class="list">
<div class="list-content" th:if="${#lists.isEmpty(typeList)}">
图书列表为空
</div>
<div class="list-content" th:unless="${#lists.isEmpty(typeList)}">
<div class="list-item" th:each="book : ${typeList}">
<img src="static/uploads/huozhe.jpg" th:src="${book.imgPath}" alt="">
<p><span>书名:</span><span th:text="${book.bookName}">活着</span</p>
<p><span>作者:</span><span th:text="${book.author}">余华</span></p>
<p><span>价格:</span><span th:text="${book.price}">¥66.6</span></p>
<p><span>销量:</span><span th:text="${book.sales}">230</span></p>
<p><span>库存:</span><span th:text="${book.stock}">1000</span></p>
</div>
</div>
</div>